Handle "show remote memory-write-packet-size" when not connected
[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 static const target_info remote_target_info = {
88   "remote",
89   N_("Remote serial target in gdb-specific protocol"),
90   remote_doc
91 };
92
93 class remote_target : public target_ops
94 {
95 public:
96   remote_target ()
97   {
98     to_stratum = process_stratum;
99   }
100
101   const target_info &info () const override
102   { return remote_target_info; }
103
104   thread_control_capabilities get_thread_control_capabilities () override
105   { return tc_schedlock; }
106
107   /* Open a remote connection.  */
108   static void open (const char *, int);
109
110   void close () override;
111
112   void detach (inferior *, int) override;
113   void disconnect (const char *, int) override;
114
115   void commit_resume () override;
116   void resume (ptid_t, int, enum gdb_signal) override;
117   ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
118
119   void fetch_registers (struct regcache *, int) override;
120   void store_registers (struct regcache *, int) override;
121   void prepare_to_store (struct regcache *) override;
122
123   void files_info () override;
124
125   int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
126
127   int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
128                          enum remove_bp_reason) override;
129
130
131   bool stopped_by_sw_breakpoint () override;
132   bool supports_stopped_by_sw_breakpoint () override;
133
134   bool stopped_by_hw_breakpoint () override;
135
136   bool supports_stopped_by_hw_breakpoint () override;
137
138   bool stopped_by_watchpoint () override;
139
140   bool stopped_data_address (CORE_ADDR *) override;
141
142   bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
143
144   int can_use_hw_breakpoint (enum bptype, int, int) override;
145
146   int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
147
148   int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
149
150   int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
151
152   int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
153                          struct expression *) override;
154
155   int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
156                          struct expression *) override;
157
158   void kill () override;
159
160   void load (const char *, int) override;
161
162   void mourn_inferior () override;
163
164   void pass_signals (int, unsigned char *) override;
165
166   int set_syscall_catchpoint (int, bool, int,
167                               gdb::array_view<const int>) override;
168
169   void program_signals (int, unsigned char *) override;
170
171   bool thread_alive (ptid_t ptid) override;
172
173   const char *thread_name (struct thread_info *) override;
174
175   void update_thread_list () override;
176
177   const char *pid_to_str (ptid_t) override;
178
179   const char *extra_thread_info (struct thread_info *) override;
180
181   ptid_t get_ada_task_ptid (long lwp, long thread) override;
182
183   thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
184                                              int handle_len,
185                                              inferior *inf) override;
186
187   void stop (ptid_t) override;
188
189   void interrupt () override;
190
191   void pass_ctrlc () override;
192
193   enum target_xfer_status xfer_partial (enum target_object object,
194                                         const char *annex,
195                                         gdb_byte *readbuf,
196                                         const gdb_byte *writebuf,
197                                         ULONGEST offset, ULONGEST len,
198                                         ULONGEST *xfered_len) override;
199
200   ULONGEST get_memory_xfer_limit () override;
201
202   void rcmd (const char *command, struct ui_file *output) override;
203
204   char *pid_to_exec_file (int pid) override;
205
206   void log_command (const char *cmd) override
207   {
208     serial_log_command (this, cmd);
209   }
210
211   CORE_ADDR get_thread_local_address (ptid_t ptid,
212                                       CORE_ADDR load_module_addr,
213                                       CORE_ADDR offset) override;
214
215   bool has_all_memory ()  override { return default_child_has_all_memory (); }
216   bool has_memory ()  override { return default_child_has_memory (); }
217   bool has_stack ()  override { return default_child_has_stack (); }
218   bool has_registers ()  override { return default_child_has_registers (); }
219   bool has_execution (ptid_t ptid)  override { return default_child_has_execution (ptid); }
220
221   bool can_execute_reverse () override;
222
223   std::vector<mem_region> memory_map () override;
224
225   void flash_erase (ULONGEST address, LONGEST length) override;
226
227   void flash_done () override;
228
229   const struct target_desc *read_description () override;
230
231   int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
232                      const gdb_byte *pattern, ULONGEST pattern_len,
233                      CORE_ADDR *found_addrp) override;
234
235   bool can_async_p () override;
236
237   bool is_async_p () override;
238
239   void async (int) override;
240
241   void thread_events (int) override;
242
243   int can_do_single_step () override;
244
245   void terminal_inferior () override;
246
247   void terminal_ours () override;
248
249   bool supports_non_stop () override;
250
251   bool supports_multi_process () override;
252
253   bool supports_disable_randomization () override;
254
255   bool filesystem_is_local () override;
256
257
258   int fileio_open (struct inferior *inf, const char *filename,
259                    int flags, int mode, int warn_if_slow,
260                    int *target_errno) override;
261
262   int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
263                      ULONGEST offset, int *target_errno) override;
264
265   int fileio_pread (int fd, gdb_byte *read_buf, int len,
266                     ULONGEST offset, int *target_errno) override;
267
268   int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
269
270   int fileio_close (int fd, int *target_errno) override;
271
272   int fileio_unlink (struct inferior *inf,
273                      const char *filename,
274                      int *target_errno) override;
275
276   gdb::optional<std::string>
277     fileio_readlink (struct inferior *inf,
278                      const char *filename,
279                      int *target_errno) override;
280
281   bool supports_enable_disable_tracepoint () override;
282
283   bool supports_string_tracing () override;
284
285   bool supports_evaluation_of_breakpoint_conditions () override;
286
287   bool can_run_breakpoint_commands () override;
288
289   void trace_init () override;
290
291   void download_tracepoint (struct bp_location *location) override;
292
293   bool can_download_tracepoint () override;
294
295   void download_trace_state_variable (const trace_state_variable &tsv) override;
296
297   void enable_tracepoint (struct bp_location *location) override;
298
299   void disable_tracepoint (struct bp_location *location) override;
300
301   void trace_set_readonly_regions () override;
302
303   void trace_start () override;
304
305   int get_trace_status (struct trace_status *ts) override;
306
307   void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
308     override;
309
310   void trace_stop () override;
311
312   int trace_find (enum trace_find_type type, int num,
313                   CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
314
315   bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
316
317   int save_trace_data (const char *filename) override;
318
319   int upload_tracepoints (struct uploaded_tp **utpp) override;
320
321   int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
322
323   LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
324
325   int get_min_fast_tracepoint_insn_len () override;
326
327   void set_disconnected_tracing (int val) override;
328
329   void set_circular_trace_buffer (int val) override;
330
331   void set_trace_buffer_size (LONGEST val) override;
332
333   bool set_trace_notes (const char *user, const char *notes,
334                         const char *stopnotes) override;
335
336   int core_of_thread (ptid_t ptid) override;
337
338   int verify_memory (const gdb_byte *data,
339                      CORE_ADDR memaddr, ULONGEST size) override;
340
341
342   bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
343
344   void set_permissions () override;
345
346   bool static_tracepoint_marker_at (CORE_ADDR,
347                                     struct static_tracepoint_marker *marker)
348     override;
349
350   std::vector<static_tracepoint_marker>
351     static_tracepoint_markers_by_strid (const char *id) override;
352
353   traceframe_info_up traceframe_info () override;
354
355   bool use_agent (bool use) override;
356   bool can_use_agent () override;
357
358   struct btrace_target_info *enable_btrace (ptid_t ptid,
359                                             const struct btrace_config *conf) override;
360
361   void disable_btrace (struct btrace_target_info *tinfo) override;
362
363   void teardown_btrace (struct btrace_target_info *tinfo) override;
364
365   enum btrace_error read_btrace (struct btrace_data *data,
366                                  struct btrace_target_info *btinfo,
367                                  enum btrace_read_type type) override;
368
369   const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
370   bool augmented_libraries_svr4_read () override;
371   int follow_fork (int, int) override;
372   void follow_exec (struct inferior *, char *) override;
373   int insert_fork_catchpoint (int) override;
374   int remove_fork_catchpoint (int) override;
375   int insert_vfork_catchpoint (int) override;
376   int remove_vfork_catchpoint (int) override;
377   int insert_exec_catchpoint (int) override;
378   int remove_exec_catchpoint (int) override;
379   enum exec_direction_kind execution_direction () override;
380
381 protected:
382   static void open_1 (const char *name, int from_tty, int extended_p);
383   void start_remote (int from_tty, int extended_p);
384 };
385
386 static const target_info extended_remote_target_info = {
387   "extended-remote",
388   N_("Extended remote serial target in gdb-specific protocol"),
389   remote_doc
390 };
391
392 /* Set up the extended remote target by extending the standard remote
393    target and adding to it.  */
394
395 class extended_remote_target final : public remote_target
396 {
397 public:
398   const target_info &info () const override
399   { return extended_remote_target_info; }
400
401   /* Open an extended-remote connection.  */
402   static void open (const char *, int);
403
404   bool can_create_inferior () override { return true; }
405   void create_inferior (const char *, const std::string &,
406                         char **, int) override;
407
408   void detach (inferior *, int) override;
409
410   bool can_attach () override { return true; }
411   void attach (const char *, int) override;
412
413   void post_attach (int) override;
414   bool supports_disable_randomization () override;
415 };
416
417 /* Per-program-space data key.  */
418 static const struct program_space_data *remote_pspace_data;
419
420 /* The variable registered as the control variable used by the
421    remote exec-file commands.  While the remote exec-file setting is
422    per-program-space, the set/show machinery uses this as the 
423    location of the remote exec-file value.  */
424 static char *remote_exec_file_var;
425
426 /* The size to align memory write packets, when practical.  The protocol
427    does not guarantee any alignment, and gdb will generate short
428    writes and unaligned writes, but even as a best-effort attempt this
429    can improve bulk transfers.  For instance, if a write is misaligned
430    relative to the target's data bus, the stub may need to make an extra
431    round trip fetching data from the target.  This doesn't make a
432    huge difference, but it's easy to do, so we try to be helpful.
433
434    The alignment chosen is arbitrary; usually data bus width is
435    important here, not the possibly larger cache line size.  */
436 enum { REMOTE_ALIGN_WRITES = 16 };
437
438 /* Prototypes for local functions.  */
439 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
440 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
441                                  int forever, int *is_notif);
442
443 struct remote_state;
444
445 static int remote_vkill (int pid, struct remote_state *rs);
446
447 static void remote_kill_k (void);
448
449 static int readchar (int timeout);
450
451 static void remote_serial_write (const char *str, int len);
452
453 static void interrupt_query (void);
454
455 static void set_general_thread (ptid_t ptid);
456 static void set_continue_thread (ptid_t ptid);
457
458 static void get_offsets (void);
459
460 static void skip_frame (void);
461
462 static long read_frame (char **buf_p, long *sizeof_buf);
463
464 static int hexnumlen (ULONGEST num);
465
466 static int stubhex (int ch);
467
468 static int hexnumstr (char *, ULONGEST);
469
470 static int hexnumnstr (char *, ULONGEST, int);
471
472 static CORE_ADDR remote_address_masked (CORE_ADDR);
473
474 static void print_packet (const char *);
475
476 static int stub_unpack_int (char *buff, int fieldlength);
477
478 static ptid_t remote_current_thread (ptid_t oldptid);
479
480 static int putpkt_binary (const char *buf, int cnt);
481
482 static void check_binary_download (CORE_ADDR addr);
483
484 struct packet_config;
485
486 static void show_packet_config_cmd (struct packet_config *config);
487
488 static void show_remote_protocol_packet_cmd (struct ui_file *file,
489                                              int from_tty,
490                                              struct cmd_list_element *c,
491                                              const char *value);
492
493 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
494 static ptid_t read_ptid (const char *buf, const char **obuf);
495
496 static void remote_query_supported (void);
497
498 static void remote_check_symbols (void);
499
500 struct stop_reply;
501 static void stop_reply_xfree (struct stop_reply *);
502 static void remote_parse_stop_reply (char *, struct stop_reply *);
503 static void push_stop_reply (struct stop_reply *);
504 static void discard_pending_stop_replies_in_queue (struct remote_state *);
505 static int peek_stop_reply (ptid_t ptid);
506
507 struct threads_listing_context;
508 static void remove_new_fork_children (struct threads_listing_context *);
509
510 static void remote_async_inferior_event_handler (gdb_client_data);
511
512 static int remote_read_description_p (struct target_ops *target);
513
514 static void remote_console_output (char *msg);
515
516 static void remote_btrace_reset (void);
517
518 static void remote_btrace_maybe_reopen (void);
519
520 static int stop_reply_queue_length (void);
521
522 static void remote_unpush_and_throw (void);
523
524 static struct remote_state *get_remote_state (void);
525
526 /* For "remote".  */
527
528 static struct cmd_list_element *remote_cmdlist;
529
530 /* For "set remote" and "show remote".  */
531
532 static struct cmd_list_element *remote_set_cmdlist;
533 static struct cmd_list_element *remote_show_cmdlist;
534
535 /* Stub vCont actions support.
536
537    Each field is a boolean flag indicating whether the stub reports
538    support for the corresponding action.  */
539
540 struct vCont_action_support
541 {
542   /* vCont;t */
543   bool t = false;
544
545   /* vCont;r */
546   bool r = false;
547
548   /* vCont;s */
549   bool s = false;
550
551   /* vCont;S */
552   bool S = false;
553 };
554
555 /* Controls whether GDB is willing to use range stepping.  */
556
557 static int use_range_stepping = 1;
558
559 #define OPAQUETHREADBYTES 8
560
561 /* a 64 bit opaque identifier */
562 typedef unsigned char threadref[OPAQUETHREADBYTES];
563
564 /* About this many threadisds fit in a packet.  */
565
566 #define MAXTHREADLISTRESULTS 32
567
568 /* The max number of chars in debug output.  The rest of chars are
569    omitted.  */
570
571 #define REMOTE_DEBUG_MAX_CHAR 512
572
573 /* Data for the vFile:pread readahead cache.  */
574
575 struct readahead_cache
576 {
577   /* Invalidate the readahead cache.  */
578   void invalidate ();
579
580   /* Invalidate the readahead cache if it is holding data for FD.  */
581   void invalidate_fd (int fd);
582
583   /* Serve pread from the readahead cache.  Returns number of bytes
584      read, or 0 if the request can't be served from the cache.  */
585   int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
586
587   /* The file descriptor for the file that is being cached.  -1 if the
588      cache is invalid.  */
589   int fd = -1;
590
591   /* The offset into the file that the cache buffer corresponds
592      to.  */
593   ULONGEST offset = 0;
594
595   /* The buffer holding the cache contents.  */
596   gdb_byte *buf = nullptr;
597   /* The buffer's size.  We try to read as much as fits into a packet
598      at a time.  */
599   size_t bufsize = 0;
600
601   /* Cache hit and miss counters.  */
602   ULONGEST hit_count = 0;
603   ULONGEST miss_count = 0;
604 };
605
606 /* Description of the remote protocol for a given architecture.  */
607
608 struct packet_reg
609 {
610   long offset; /* Offset into G packet.  */
611   long regnum; /* GDB's internal register number.  */
612   LONGEST pnum; /* Remote protocol register number.  */
613   int in_g_packet; /* Always part of G packet.  */
614   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
615      at present.  */
616   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
617      at present.  */
618 };
619
620 struct remote_arch_state
621 {
622   explicit remote_arch_state (struct gdbarch *gdbarch);
623
624   /* Description of the remote protocol registers.  */
625   long sizeof_g_packet;
626
627   /* Description of the remote protocol registers indexed by REGNUM
628      (making an array gdbarch_num_regs in size).  */
629   std::unique_ptr<packet_reg[]> regs;
630
631   /* This is the size (in chars) of the first response to the ``g''
632      packet.  It is used as a heuristic when determining the maximum
633      size of memory-read and memory-write packets.  A target will
634      typically only reserve a buffer large enough to hold the ``g''
635      packet.  The size does not include packet overhead (headers and
636      trailers).  */
637   long actual_register_packet_size;
638
639   /* This is the maximum size (in chars) of a non read/write packet.
640      It is also used as a cap on the size of read/write packets.  */
641   long remote_packet_size;
642 };
643
644 /* Description of the remote protocol state for the currently
645    connected target.  This is per-target state, and independent of the
646    selected architecture.  */
647
648 class remote_state
649 {
650 public:
651
652   remote_state ();
653   ~remote_state ();
654
655   /* Get the remote arch state for GDBARCH.  */
656   struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
657
658 public: /* data */
659
660   /* A buffer to use for incoming packets, and its current size.  The
661      buffer is grown dynamically for larger incoming packets.
662      Outgoing packets may also be constructed in this buffer.
663      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
664      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
665      packets.  */
666   char *buf;
667   long buf_size;
668
669   /* True if we're going through initial connection setup (finding out
670      about the remote side's threads, relocating symbols, etc.).  */
671   bool starting_up = false;
672
673   /* If we negotiated packet size explicitly (and thus can bypass
674      heuristics for the largest packet size that will not overflow
675      a buffer in the stub), this will be set to that packet size.
676      Otherwise zero, meaning to use the guessed size.  */
677   long explicit_packet_size = 0;
678
679   /* remote_wait is normally called when the target is running and
680      waits for a stop reply packet.  But sometimes we need to call it
681      when the target is already stopped.  We can send a "?" packet
682      and have remote_wait read the response.  Or, if we already have
683      the response, we can stash it in BUF and tell remote_wait to
684      skip calling getpkt.  This flag is set when BUF contains a
685      stop reply packet and the target is not waiting.  */
686   int cached_wait_status = 0;
687
688   /* True, if in no ack mode.  That is, neither GDB nor the stub will
689      expect acks from each other.  The connection is assumed to be
690      reliable.  */
691   bool noack_mode = false;
692
693   /* True if we're connected in extended remote mode.  */
694   bool extended = false;
695
696   /* True if we resumed the target and we're waiting for the target to
697      stop.  In the mean time, we can't start another command/query.
698      The remote server wouldn't be ready to process it, so we'd
699      timeout waiting for a reply that would never come and eventually
700      we'd close the connection.  This can happen in asynchronous mode
701      because we allow GDB commands while the target is running.  */
702   bool waiting_for_stop_reply = false;
703
704   /* The status of the stub support for the various vCont actions.  */
705   vCont_action_support supports_vCont;
706
707   /* True if the user has pressed Ctrl-C, but the target hasn't
708      responded to that.  */
709   bool ctrlc_pending_p = false;
710
711   /* True if we saw a Ctrl-C while reading or writing from/to the
712      remote descriptor.  At that point it is not safe to send a remote
713      interrupt packet, so we instead remember we saw the Ctrl-C and
714      process it once we're done with sending/receiving the current
715      packet, which should be shortly.  If however that takes too long,
716      and the user presses Ctrl-C again, we offer to disconnect.  */
717   bool got_ctrlc_during_io = false;
718
719   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
720      remote_open knows that we don't have a file open when the program
721      starts.  */
722   struct serial *remote_desc = nullptr;
723
724   /* These are the threads which we last sent to the remote system.  The
725      TID member will be -1 for all or -2 for not sent yet.  */
726   ptid_t general_thread = null_ptid;
727   ptid_t continue_thread = null_ptid;
728
729   /* This is the traceframe which we last selected on the remote system.
730      It will be -1 if no traceframe is selected.  */
731   int remote_traceframe_number = -1;
732
733   char *last_pass_packet = nullptr;
734
735   /* The last QProgramSignals packet sent to the target.  We bypass
736      sending a new program signals list down to the target if the new
737      packet is exactly the same as the last we sent.  IOW, we only let
738      the target know about program signals list changes.  */
739   char *last_program_signals_packet = nullptr;
740
741   gdb_signal last_sent_signal = GDB_SIGNAL_0;
742
743   bool last_sent_step = false;
744
745   /* The execution direction of the last resume we got.  */
746   exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
747
748   char *finished_object = nullptr;
749   char *finished_annex = nullptr;
750   ULONGEST finished_offset = 0;
751
752   /* Should we try the 'ThreadInfo' query packet?
753
754      This variable (NOT available to the user: auto-detect only!)
755      determines whether GDB will use the new, simpler "ThreadInfo"
756      query or the older, more complex syntax for thread queries.
757      This is an auto-detect variable (set to true at each connect,
758      and set to false when the target fails to recognize it).  */
759   bool use_threadinfo_query = false;
760   bool use_threadextra_query = false;
761
762   threadref echo_nextthread {};
763   threadref nextthread {};
764   threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
765
766   /* The state of remote notification.  */
767   struct remote_notif_state *notif_state = nullptr;
768
769   /* The branch trace configuration.  */
770   struct btrace_config btrace_config {};
771
772   /* The argument to the last "vFile:setfs:" packet we sent, used
773      to avoid sending repeated unnecessary "vFile:setfs:" packets.
774      Initialized to -1 to indicate that no "vFile:setfs:" packet
775      has yet been sent.  */
776   int fs_pid = -1;
777
778   /* A readahead cache for vFile:pread.  Often, reading a binary
779      involves a sequence of small reads.  E.g., when parsing an ELF
780      file.  A readahead cache helps mostly the case of remote
781      debugging on a connection with higher latency, due to the
782      request/reply nature of the RSP.  We only cache data for a single
783      file descriptor at a time.  */
784   struct readahead_cache readahead_cache;
785
786 private:
787   /* Mapping of remote protocol data for each gdbarch.  Usually there
788      is only one entry here, though we may see more with stubs that
789      support multi-process.  */
790   std::unordered_map<struct gdbarch *, remote_arch_state>
791     m_arch_states;
792 };
793
794 /* Private data that we'll store in (struct thread_info)->priv.  */
795 struct remote_thread_info : public private_thread_info
796 {
797   std::string extra;
798   std::string name;
799   int core = -1;
800
801   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
802      sequence of bytes.  */
803   gdb::byte_vector thread_handle;
804
805   /* Whether the target stopped for a breakpoint/watchpoint.  */
806   enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
807
808   /* This is set to the data address of the access causing the target
809      to stop for a watchpoint.  */
810   CORE_ADDR watch_data_address = 0;
811
812   /* Fields used by the vCont action coalescing implemented in
813      remote_resume / remote_commit_resume.  remote_resume stores each
814      thread's last resume request in these fields, so that a later
815      remote_commit_resume knows which is the proper action for this
816      thread to include in the vCont packet.  */
817
818   /* True if the last target_resume call for this thread was a step
819      request, false if a continue request.  */
820   int last_resume_step = 0;
821
822   /* The signal specified in the last target_resume call for this
823      thread.  */
824   gdb_signal last_resume_sig = GDB_SIGNAL_0;
825
826   /* Whether this thread was already vCont-resumed on the remote
827      side.  */
828   int vcont_resumed = 0;
829 };
830
831 remote_state::remote_state ()
832 {
833   /* The default buffer size is unimportant; it will be expanded
834      whenever a larger buffer is needed. */
835   this->buf_size = 400;
836   this->buf = (char *) xmalloc (this->buf_size);
837 }
838
839 remote_state::~remote_state ()
840 {
841   xfree (this->last_pass_packet);
842   xfree (this->last_program_signals_packet);
843   xfree (this->buf);
844   xfree (this->finished_object);
845   xfree (this->finished_annex);
846 }
847
848 /* This data could be associated with a target, but we do not always
849    have access to the current target when we need it, so for now it is
850    static.  This will be fine for as long as only one target is in use
851    at a time.  */
852 static struct remote_state *remote_state;
853
854 static struct remote_state *
855 get_remote_state_raw (void)
856 {
857   return remote_state;
858 }
859
860 /* Utility: generate error from an incoming stub packet.  */
861 static void
862 trace_error (char *buf)
863 {
864   if (*buf++ != 'E')
865     return;                     /* not an error msg */
866   switch (*buf)
867     {
868     case '1':                   /* malformed packet error */
869       if (*++buf == '0')        /*   general case: */
870         error (_("remote.c: error in outgoing packet."));
871       else
872         error (_("remote.c: error in outgoing packet at field #%ld."),
873                strtol (buf, NULL, 16));
874     default:
875       error (_("Target returns error code '%s'."), buf);
876     }
877 }
878
879 /* Utility: wait for reply from stub, while accepting "O" packets.  */
880
881 static char *
882 remote_get_noisy_reply ()
883 {
884   struct remote_state *rs = get_remote_state ();
885
886   do                            /* Loop on reply from remote stub.  */
887     {
888       char *buf;
889
890       QUIT;                     /* Allow user to bail out with ^C.  */
891       getpkt (&rs->buf, &rs->buf_size, 0);
892       buf = rs->buf;
893       if (buf[0] == 'E')
894         trace_error (buf);
895       else if (startswith (buf, "qRelocInsn:"))
896         {
897           ULONGEST ul;
898           CORE_ADDR from, to, org_to;
899           const char *p, *pp;
900           int adjusted_size = 0;
901           int relocated = 0;
902
903           p = buf + strlen ("qRelocInsn:");
904           pp = unpack_varlen_hex (p, &ul);
905           if (*pp != ';')
906             error (_("invalid qRelocInsn packet: %s"), buf);
907           from = ul;
908
909           p = pp + 1;
910           unpack_varlen_hex (p, &ul);
911           to = ul;
912
913           org_to = to;
914
915           TRY
916             {
917               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
918               relocated = 1;
919             }
920           CATCH (ex, RETURN_MASK_ALL)
921             {
922               if (ex.error == MEMORY_ERROR)
923                 {
924                   /* Propagate memory errors silently back to the
925                      target.  The stub may have limited the range of
926                      addresses we can write to, for example.  */
927                 }
928               else
929                 {
930                   /* Something unexpectedly bad happened.  Be verbose
931                      so we can tell what, and propagate the error back
932                      to the stub, so it doesn't get stuck waiting for
933                      a response.  */
934                   exception_fprintf (gdb_stderr, ex,
935                                      _("warning: relocating instruction: "));
936                 }
937               putpkt ("E01");
938             }
939           END_CATCH
940
941           if (relocated)
942             {
943               adjusted_size = to - org_to;
944
945               xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
946               putpkt (buf);
947             }
948         }
949       else if (buf[0] == 'O' && buf[1] != 'K')
950         remote_console_output (buf + 1);        /* 'O' message from stub */
951       else
952         return buf;             /* Here's the actual reply.  */
953     }
954   while (1);
955 }
956
957 struct remote_arch_state *
958 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
959 {
960   remote_arch_state *rsa;
961
962   auto it = this->m_arch_states.find (gdbarch);
963   if (it == this->m_arch_states.end ())
964     {
965       auto p = this->m_arch_states.emplace (std::piecewise_construct,
966                                             std::forward_as_tuple (gdbarch),
967                                             std::forward_as_tuple (gdbarch));
968       rsa = &p.first->second;
969
970       /* Make sure that the packet buffer is plenty big enough for
971          this architecture.  */
972       if (this->buf_size < rsa->remote_packet_size)
973         {
974           this->buf_size = 2 * rsa->remote_packet_size;
975           this->buf = (char *) xrealloc (this->buf, this->buf_size);
976         }
977     }
978   else
979     rsa = &it->second;
980
981   return rsa;
982 }
983
984 /* Fetch the global remote target state.  */
985
986 static struct remote_state *
987 get_remote_state (void)
988 {
989   struct remote_state *rs = get_remote_state_raw ();
990
991   /* Make sure that the remote architecture state has been
992      initialized, because doing so might reallocate rs->buf.  Any
993      function which calls getpkt also needs to be mindful of changes
994      to rs->buf, but this call limits the number of places which run
995      into trouble.  */
996   rs->get_remote_arch_state (target_gdbarch ());
997
998   return rs;
999 }
1000
1001 /* Cleanup routine for the remote module's pspace data.  */
1002
1003 static void
1004 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1005 {
1006   char *remote_exec_file = (char *) arg;
1007
1008   xfree (remote_exec_file);
1009 }
1010
1011 /* Fetch the remote exec-file from the current program space.  */
1012
1013 static const char *
1014 get_remote_exec_file (void)
1015 {
1016   char *remote_exec_file;
1017
1018   remote_exec_file
1019     = (char *) program_space_data (current_program_space,
1020                                    remote_pspace_data);
1021   if (remote_exec_file == NULL)
1022     return "";
1023
1024   return remote_exec_file;
1025 }
1026
1027 /* Set the remote exec file for PSPACE.  */
1028
1029 static void
1030 set_pspace_remote_exec_file (struct program_space *pspace,
1031                         char *remote_exec_file)
1032 {
1033   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
1034
1035   xfree (old_file);
1036   set_program_space_data (pspace, remote_pspace_data,
1037                           xstrdup (remote_exec_file));
1038 }
1039
1040 /* The "set/show remote exec-file" set command hook.  */
1041
1042 static void
1043 set_remote_exec_file (const char *ignored, int from_tty,
1044                       struct cmd_list_element *c)
1045 {
1046   gdb_assert (remote_exec_file_var != NULL);
1047   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1048 }
1049
1050 /* The "set/show remote exec-file" show command hook.  */
1051
1052 static void
1053 show_remote_exec_file (struct ui_file *file, int from_tty,
1054                        struct cmd_list_element *cmd, const char *value)
1055 {
1056   fprintf_filtered (file, "%s\n", remote_exec_file_var);
1057 }
1058
1059 static int
1060 compare_pnums (const void *lhs_, const void *rhs_)
1061 {
1062   const struct packet_reg * const *lhs
1063     = (const struct packet_reg * const *) lhs_;
1064   const struct packet_reg * const *rhs
1065     = (const struct packet_reg * const *) rhs_;
1066
1067   if ((*lhs)->pnum < (*rhs)->pnum)
1068     return -1;
1069   else if ((*lhs)->pnum == (*rhs)->pnum)
1070     return 0;
1071   else
1072     return 1;
1073 }
1074
1075 static int
1076 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1077 {
1078   int regnum, num_remote_regs, offset;
1079   struct packet_reg **remote_regs;
1080
1081   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1082     {
1083       struct packet_reg *r = &regs[regnum];
1084
1085       if (register_size (gdbarch, regnum) == 0)
1086         /* Do not try to fetch zero-sized (placeholder) registers.  */
1087         r->pnum = -1;
1088       else
1089         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1090
1091       r->regnum = regnum;
1092     }
1093
1094   /* Define the g/G packet format as the contents of each register
1095      with a remote protocol number, in order of ascending protocol
1096      number.  */
1097
1098   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1099   for (num_remote_regs = 0, regnum = 0;
1100        regnum < gdbarch_num_regs (gdbarch);
1101        regnum++)
1102     if (regs[regnum].pnum != -1)
1103       remote_regs[num_remote_regs++] = &regs[regnum];
1104
1105   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1106          compare_pnums);
1107
1108   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1109     {
1110       remote_regs[regnum]->in_g_packet = 1;
1111       remote_regs[regnum]->offset = offset;
1112       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1113     }
1114
1115   return offset;
1116 }
1117
1118 /* Given the architecture described by GDBARCH, return the remote
1119    protocol register's number and the register's offset in the g/G
1120    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1121    If the target does not have a mapping for REGNUM, return false,
1122    otherwise, return true.  */
1123
1124 int
1125 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1126                                    int *pnum, int *poffset)
1127 {
1128   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1129
1130   std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1131
1132   map_regcache_remote_table (gdbarch, regs.data ());
1133
1134   *pnum = regs[regnum].pnum;
1135   *poffset = regs[regnum].offset;
1136
1137   return *pnum != -1;
1138 }
1139
1140 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1141 {
1142   /* Use the architecture to build a regnum<->pnum table, which will be
1143      1:1 unless a feature set specifies otherwise.  */
1144   this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1145
1146   /* Record the maximum possible size of the g packet - it may turn out
1147      to be smaller.  */
1148   this->sizeof_g_packet
1149     = map_regcache_remote_table (gdbarch, this->regs.get ());
1150
1151   /* Default maximum number of characters in a packet body.  Many
1152      remote stubs have a hardwired buffer size of 400 bytes
1153      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
1154      as the maximum packet-size to ensure that the packet and an extra
1155      NUL character can always fit in the buffer.  This stops GDB
1156      trashing stubs that try to squeeze an extra NUL into what is
1157      already a full buffer (As of 1999-12-04 that was most stubs).  */
1158   this->remote_packet_size = 400 - 1;
1159
1160   /* This one is filled in when a ``g'' packet is received.  */
1161   this->actual_register_packet_size = 0;
1162
1163   /* Should rsa->sizeof_g_packet needs more space than the
1164      default, adjust the size accordingly.  Remember that each byte is
1165      encoded as two characters.  32 is the overhead for the packet
1166      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
1167      (``$NN:G...#NN'') is a better guess, the below has been padded a
1168      little.  */
1169   if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1170     this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1171 }
1172
1173 /* Return the current allowed size of a remote packet.  This is
1174    inferred from the current architecture, and should be used to
1175    limit the length of outgoing packets.  */
1176 static long
1177 get_remote_packet_size (void)
1178 {
1179   struct remote_state *rs = get_remote_state ();
1180   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1181
1182   if (rs->explicit_packet_size)
1183     return rs->explicit_packet_size;
1184
1185   return rsa->remote_packet_size;
1186 }
1187
1188 static struct packet_reg *
1189 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1190                         long regnum)
1191 {
1192   if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1193     return NULL;
1194   else
1195     {
1196       struct packet_reg *r = &rsa->regs[regnum];
1197
1198       gdb_assert (r->regnum == regnum);
1199       return r;
1200     }
1201 }
1202
1203 static struct packet_reg *
1204 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1205                       LONGEST pnum)
1206 {
1207   int i;
1208
1209   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1210     {
1211       struct packet_reg *r = &rsa->regs[i];
1212
1213       if (r->pnum == pnum)
1214         return r;
1215     }
1216   return NULL;
1217 }
1218
1219 static remote_target remote_ops;
1220
1221 static extended_remote_target extended_remote_ops;
1222
1223 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
1224    ``forever'' still use the normal timeout mechanism.  This is
1225    currently used by the ASYNC code to guarentee that target reads
1226    during the initial connect always time-out.  Once getpkt has been
1227    modified to return a timeout indication and, in turn
1228    remote_wait()/wait_for_inferior() have gained a timeout parameter
1229    this can go away.  */
1230 static int wait_forever_enabled_p = 1;
1231
1232 /* Allow the user to specify what sequence to send to the remote
1233    when he requests a program interruption: Although ^C is usually
1234    what remote systems expect (this is the default, here), it is
1235    sometimes preferable to send a break.  On other systems such
1236    as the Linux kernel, a break followed by g, which is Magic SysRq g
1237    is required in order to interrupt the execution.  */
1238 const char interrupt_sequence_control_c[] = "Ctrl-C";
1239 const char interrupt_sequence_break[] = "BREAK";
1240 const char interrupt_sequence_break_g[] = "BREAK-g";
1241 static const char *const interrupt_sequence_modes[] =
1242   {
1243     interrupt_sequence_control_c,
1244     interrupt_sequence_break,
1245     interrupt_sequence_break_g,
1246     NULL
1247   };
1248 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1249
1250 static void
1251 show_interrupt_sequence (struct ui_file *file, int from_tty,
1252                          struct cmd_list_element *c,
1253                          const char *value)
1254 {
1255   if (interrupt_sequence_mode == interrupt_sequence_control_c)
1256     fprintf_filtered (file,
1257                       _("Send the ASCII ETX character (Ctrl-c) "
1258                         "to the remote target to interrupt the "
1259                         "execution of the program.\n"));
1260   else if (interrupt_sequence_mode == interrupt_sequence_break)
1261     fprintf_filtered (file,
1262                       _("send a break signal to the remote target "
1263                         "to interrupt the execution of the program.\n"));
1264   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1265     fprintf_filtered (file,
1266                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1267                         "the remote target to interrupt the execution "
1268                         "of Linux kernel.\n"));
1269   else
1270     internal_error (__FILE__, __LINE__,
1271                     _("Invalid value for interrupt_sequence_mode: %s."),
1272                     interrupt_sequence_mode);
1273 }
1274
1275 /* This boolean variable specifies whether interrupt_sequence is sent
1276    to the remote target when gdb connects to it.
1277    This is mostly needed when you debug the Linux kernel: The Linux kernel
1278    expects BREAK g which is Magic SysRq g for connecting gdb.  */
1279 static int interrupt_on_connect = 0;
1280
1281 /* This variable is used to implement the "set/show remotebreak" commands.
1282    Since these commands are now deprecated in favor of "set/show remote
1283    interrupt-sequence", it no longer has any effect on the code.  */
1284 static int remote_break;
1285
1286 static void
1287 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1288 {
1289   if (remote_break)
1290     interrupt_sequence_mode = interrupt_sequence_break;
1291   else
1292     interrupt_sequence_mode = interrupt_sequence_control_c;
1293 }
1294
1295 static void
1296 show_remotebreak (struct ui_file *file, int from_tty,
1297                   struct cmd_list_element *c,
1298                   const char *value)
1299 {
1300 }
1301
1302 /* This variable sets the number of bits in an address that are to be
1303    sent in a memory ("M" or "m") packet.  Normally, after stripping
1304    leading zeros, the entire address would be sent.  This variable
1305    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
1306    initial implementation of remote.c restricted the address sent in
1307    memory packets to ``host::sizeof long'' bytes - (typically 32
1308    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
1309    address was never sent.  Since fixing this bug may cause a break in
1310    some remote targets this variable is principly provided to
1311    facilitate backward compatibility.  */
1312
1313 static unsigned int remote_address_size;
1314
1315 \f
1316 /* User configurable variables for the number of characters in a
1317    memory read/write packet.  MIN (rsa->remote_packet_size,
1318    rsa->sizeof_g_packet) is the default.  Some targets need smaller
1319    values (fifo overruns, et.al.) and some users need larger values
1320    (speed up transfers).  The variables ``preferred_*'' (the user
1321    request), ``current_*'' (what was actually set) and ``forced_*''
1322    (Positive - a soft limit, negative - a hard limit).  */
1323
1324 struct memory_packet_config
1325 {
1326   const char *name;
1327   long size;
1328   int fixed_p;
1329 };
1330
1331 /* The default max memory-write-packet-size, when the setting is
1332    "fixed".  The 16k is historical.  (It came from older GDB's using
1333    alloca for buffers and the knowledge (folklore?) that some hosts
1334    don't cope very well with large alloca calls.)  */
1335 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1336
1337 /* The minimum remote packet size for memory transfers.  Ensures we
1338    can write at least one byte.  */
1339 #define MIN_MEMORY_PACKET_SIZE 20
1340
1341 /* Get the memory packet size, assuming it is fixed.  */
1342
1343 static long
1344 get_fixed_memory_packet_size (struct memory_packet_config *config)
1345 {
1346   gdb_assert (config->fixed_p);
1347
1348   if (config->size <= 0)
1349     return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1350   else
1351     return config->size;
1352 }
1353
1354 /* Compute the current size of a read/write packet.  Since this makes
1355    use of ``actual_register_packet_size'' the computation is dynamic.  */
1356
1357 static long
1358 get_memory_packet_size (struct memory_packet_config *config)
1359 {
1360   struct remote_state *rs = get_remote_state ();
1361   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1362
1363   long what_they_get;
1364   if (config->fixed_p)
1365     what_they_get = get_fixed_memory_packet_size (config);
1366   else
1367     {
1368       what_they_get = get_remote_packet_size ();
1369       /* Limit the packet to the size specified by the user.  */
1370       if (config->size > 0
1371           && what_they_get > config->size)
1372         what_they_get = config->size;
1373
1374       /* Limit it to the size of the targets ``g'' response unless we have
1375          permission from the stub to use a larger packet size.  */
1376       if (rs->explicit_packet_size == 0
1377           && rsa->actual_register_packet_size > 0
1378           && what_they_get > rsa->actual_register_packet_size)
1379         what_they_get = rsa->actual_register_packet_size;
1380     }
1381   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1382     what_they_get = MIN_MEMORY_PACKET_SIZE;
1383
1384   /* Make sure there is room in the global buffer for this packet
1385      (including its trailing NUL byte).  */
1386   if (rs->buf_size < what_they_get + 1)
1387     {
1388       rs->buf_size = 2 * what_they_get;
1389       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1390     }
1391
1392   return what_they_get;
1393 }
1394
1395 /* Update the size of a read/write packet.  If they user wants
1396    something really big then do a sanity check.  */
1397
1398 static void
1399 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1400 {
1401   int fixed_p = config->fixed_p;
1402   long size = config->size;
1403
1404   if (args == NULL)
1405     error (_("Argument required (integer, `fixed' or `limited')."));
1406   else if (strcmp (args, "hard") == 0
1407       || strcmp (args, "fixed") == 0)
1408     fixed_p = 1;
1409   else if (strcmp (args, "soft") == 0
1410            || strcmp (args, "limit") == 0)
1411     fixed_p = 0;
1412   else
1413     {
1414       char *end;
1415
1416       size = strtoul (args, &end, 0);
1417       if (args == end)
1418         error (_("Invalid %s (bad syntax)."), config->name);
1419
1420       /* Instead of explicitly capping the size of a packet to or
1421          disallowing it, the user is allowed to set the size to
1422          something arbitrarily large.  */
1423     }
1424
1425   /* Extra checks?  */
1426   if (fixed_p && !config->fixed_p)
1427     {
1428       /* So that the query shows the correct value.  */
1429       long query_size = (size <= 0
1430                          ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1431                          : size);
1432
1433       if (! query (_("The target may not be able to correctly handle a %s\n"
1434                    "of %ld bytes. Change the packet size? "),
1435                    config->name, query_size))
1436         error (_("Packet size not changed."));
1437     }
1438   /* Update the config.  */
1439   config->fixed_p = fixed_p;
1440   config->size = size;
1441 }
1442
1443 static void
1444 show_memory_packet_size (struct memory_packet_config *config)
1445 {
1446   if (config->size == 0)
1447     printf_filtered (_("The %s is 0 (default). "), config->name);
1448   else
1449     printf_filtered (_("The %s is %ld. "), config->name, config->size);
1450   if (config->fixed_p)
1451     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1452                      get_fixed_memory_packet_size (config));
1453   else
1454     {
1455       struct remote_state *rs = get_remote_state ();
1456
1457       if (rs->remote_desc != NULL)
1458         printf_filtered (_("Packets are limited to %ld bytes.\n"),
1459                          get_memory_packet_size (config));
1460       else
1461         puts_filtered ("The actual limit will be further reduced "
1462                        "dependent on the target.\n");
1463     }
1464 }
1465
1466 static struct memory_packet_config memory_write_packet_config =
1467 {
1468   "memory-write-packet-size",
1469 };
1470
1471 static void
1472 set_memory_write_packet_size (const char *args, int from_tty)
1473 {
1474   set_memory_packet_size (args, &memory_write_packet_config);
1475 }
1476
1477 static void
1478 show_memory_write_packet_size (const char *args, int from_tty)
1479 {
1480   show_memory_packet_size (&memory_write_packet_config);
1481 }
1482
1483 static long
1484 get_memory_write_packet_size (void)
1485 {
1486   return get_memory_packet_size (&memory_write_packet_config);
1487 }
1488
1489 static struct memory_packet_config memory_read_packet_config =
1490 {
1491   "memory-read-packet-size",
1492 };
1493
1494 static void
1495 set_memory_read_packet_size (const char *args, int from_tty)
1496 {
1497   set_memory_packet_size (args, &memory_read_packet_config);
1498 }
1499
1500 static void
1501 show_memory_read_packet_size (const char *args, int from_tty)
1502 {
1503   show_memory_packet_size (&memory_read_packet_config);
1504 }
1505
1506 static long
1507 get_memory_read_packet_size (void)
1508 {
1509   long size = get_memory_packet_size (&memory_read_packet_config);
1510
1511   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1512      extra buffer size argument before the memory read size can be
1513      increased beyond this.  */
1514   if (size > get_remote_packet_size ())
1515     size = get_remote_packet_size ();
1516   return size;
1517 }
1518
1519 \f
1520 /* Generic configuration support for packets the stub optionally
1521    supports.  Allows the user to specify the use of the packet as well
1522    as allowing GDB to auto-detect support in the remote stub.  */
1523
1524 enum packet_support
1525   {
1526     PACKET_SUPPORT_UNKNOWN = 0,
1527     PACKET_ENABLE,
1528     PACKET_DISABLE
1529   };
1530
1531 struct packet_config
1532   {
1533     const char *name;
1534     const char *title;
1535
1536     /* If auto, GDB auto-detects support for this packet or feature,
1537        either through qSupported, or by trying the packet and looking
1538        at the response.  If true, GDB assumes the target supports this
1539        packet.  If false, the packet is disabled.  Configs that don't
1540        have an associated command always have this set to auto.  */
1541     enum auto_boolean detect;
1542
1543     /* Does the target support this packet?  */
1544     enum packet_support support;
1545   };
1546
1547 /* Analyze a packet's return value and update the packet config
1548    accordingly.  */
1549
1550 enum packet_result
1551 {
1552   PACKET_ERROR,
1553   PACKET_OK,
1554   PACKET_UNKNOWN
1555 };
1556
1557 static enum packet_support packet_config_support (struct packet_config *config);
1558 static enum packet_support packet_support (int packet);
1559
1560 static void
1561 show_packet_config_cmd (struct packet_config *config)
1562 {
1563   const char *support = "internal-error";
1564
1565   switch (packet_config_support (config))
1566     {
1567     case PACKET_ENABLE:
1568       support = "enabled";
1569       break;
1570     case PACKET_DISABLE:
1571       support = "disabled";
1572       break;
1573     case PACKET_SUPPORT_UNKNOWN:
1574       support = "unknown";
1575       break;
1576     }
1577   switch (config->detect)
1578     {
1579     case AUTO_BOOLEAN_AUTO:
1580       printf_filtered (_("Support for the `%s' packet "
1581                          "is auto-detected, currently %s.\n"),
1582                        config->name, support);
1583       break;
1584     case AUTO_BOOLEAN_TRUE:
1585     case AUTO_BOOLEAN_FALSE:
1586       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1587                        config->name, support);
1588       break;
1589     }
1590 }
1591
1592 static void
1593 add_packet_config_cmd (struct packet_config *config, const char *name,
1594                        const char *title, int legacy)
1595 {
1596   char *set_doc;
1597   char *show_doc;
1598   char *cmd_name;
1599
1600   config->name = name;
1601   config->title = title;
1602   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1603                         name, title);
1604   show_doc = xstrprintf ("Show current use of remote "
1605                          "protocol `%s' (%s) packet",
1606                          name, title);
1607   /* set/show TITLE-packet {auto,on,off} */
1608   cmd_name = xstrprintf ("%s-packet", title);
1609   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1610                                 &config->detect, set_doc,
1611                                 show_doc, NULL, /* help_doc */
1612                                 NULL,
1613                                 show_remote_protocol_packet_cmd,
1614                                 &remote_set_cmdlist, &remote_show_cmdlist);
1615   /* The command code copies the documentation strings.  */
1616   xfree (set_doc);
1617   xfree (show_doc);
1618   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1619   if (legacy)
1620     {
1621       char *legacy_name;
1622
1623       legacy_name = xstrprintf ("%s-packet", name);
1624       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1625                      &remote_set_cmdlist);
1626       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1627                      &remote_show_cmdlist);
1628     }
1629 }
1630
1631 static enum packet_result
1632 packet_check_result (const char *buf)
1633 {
1634   if (buf[0] != '\0')
1635     {
1636       /* The stub recognized the packet request.  Check that the
1637          operation succeeded.  */
1638       if (buf[0] == 'E'
1639           && isxdigit (buf[1]) && isxdigit (buf[2])
1640           && buf[3] == '\0')
1641         /* "Enn"  - definitly an error.  */
1642         return PACKET_ERROR;
1643
1644       /* Always treat "E." as an error.  This will be used for
1645          more verbose error messages, such as E.memtypes.  */
1646       if (buf[0] == 'E' && buf[1] == '.')
1647         return PACKET_ERROR;
1648
1649       /* The packet may or may not be OK.  Just assume it is.  */
1650       return PACKET_OK;
1651     }
1652   else
1653     /* The stub does not support the packet.  */
1654     return PACKET_UNKNOWN;
1655 }
1656
1657 static enum packet_result
1658 packet_ok (const char *buf, struct packet_config *config)
1659 {
1660   enum packet_result result;
1661
1662   if (config->detect != AUTO_BOOLEAN_TRUE
1663       && config->support == PACKET_DISABLE)
1664     internal_error (__FILE__, __LINE__,
1665                     _("packet_ok: attempt to use a disabled packet"));
1666
1667   result = packet_check_result (buf);
1668   switch (result)
1669     {
1670     case PACKET_OK:
1671     case PACKET_ERROR:
1672       /* The stub recognized the packet request.  */
1673       if (config->support == PACKET_SUPPORT_UNKNOWN)
1674         {
1675           if (remote_debug)
1676             fprintf_unfiltered (gdb_stdlog,
1677                                 "Packet %s (%s) is supported\n",
1678                                 config->name, config->title);
1679           config->support = PACKET_ENABLE;
1680         }
1681       break;
1682     case PACKET_UNKNOWN:
1683       /* The stub does not support the packet.  */
1684       if (config->detect == AUTO_BOOLEAN_AUTO
1685           && config->support == PACKET_ENABLE)
1686         {
1687           /* If the stub previously indicated that the packet was
1688              supported then there is a protocol error.  */
1689           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1690                  config->name, config->title);
1691         }
1692       else if (config->detect == AUTO_BOOLEAN_TRUE)
1693         {
1694           /* The user set it wrong.  */
1695           error (_("Enabled packet %s (%s) not recognized by stub"),
1696                  config->name, config->title);
1697         }
1698
1699       if (remote_debug)
1700         fprintf_unfiltered (gdb_stdlog,
1701                             "Packet %s (%s) is NOT supported\n",
1702                             config->name, config->title);
1703       config->support = PACKET_DISABLE;
1704       break;
1705     }
1706
1707   return result;
1708 }
1709
1710 enum {
1711   PACKET_vCont = 0,
1712   PACKET_X,
1713   PACKET_qSymbol,
1714   PACKET_P,
1715   PACKET_p,
1716   PACKET_Z0,
1717   PACKET_Z1,
1718   PACKET_Z2,
1719   PACKET_Z3,
1720   PACKET_Z4,
1721   PACKET_vFile_setfs,
1722   PACKET_vFile_open,
1723   PACKET_vFile_pread,
1724   PACKET_vFile_pwrite,
1725   PACKET_vFile_close,
1726   PACKET_vFile_unlink,
1727   PACKET_vFile_readlink,
1728   PACKET_vFile_fstat,
1729   PACKET_qXfer_auxv,
1730   PACKET_qXfer_features,
1731   PACKET_qXfer_exec_file,
1732   PACKET_qXfer_libraries,
1733   PACKET_qXfer_libraries_svr4,
1734   PACKET_qXfer_memory_map,
1735   PACKET_qXfer_spu_read,
1736   PACKET_qXfer_spu_write,
1737   PACKET_qXfer_osdata,
1738   PACKET_qXfer_threads,
1739   PACKET_qXfer_statictrace_read,
1740   PACKET_qXfer_traceframe_info,
1741   PACKET_qXfer_uib,
1742   PACKET_qGetTIBAddr,
1743   PACKET_qGetTLSAddr,
1744   PACKET_qSupported,
1745   PACKET_qTStatus,
1746   PACKET_QPassSignals,
1747   PACKET_QCatchSyscalls,
1748   PACKET_QProgramSignals,
1749   PACKET_QSetWorkingDir,
1750   PACKET_QStartupWithShell,
1751   PACKET_QEnvironmentHexEncoded,
1752   PACKET_QEnvironmentReset,
1753   PACKET_QEnvironmentUnset,
1754   PACKET_qCRC,
1755   PACKET_qSearch_memory,
1756   PACKET_vAttach,
1757   PACKET_vRun,
1758   PACKET_QStartNoAckMode,
1759   PACKET_vKill,
1760   PACKET_qXfer_siginfo_read,
1761   PACKET_qXfer_siginfo_write,
1762   PACKET_qAttached,
1763
1764   /* Support for conditional tracepoints.  */
1765   PACKET_ConditionalTracepoints,
1766
1767   /* Support for target-side breakpoint conditions.  */
1768   PACKET_ConditionalBreakpoints,
1769
1770   /* Support for target-side breakpoint commands.  */
1771   PACKET_BreakpointCommands,
1772
1773   /* Support for fast tracepoints.  */
1774   PACKET_FastTracepoints,
1775
1776   /* Support for static tracepoints.  */
1777   PACKET_StaticTracepoints,
1778
1779   /* Support for installing tracepoints while a trace experiment is
1780      running.  */
1781   PACKET_InstallInTrace,
1782
1783   PACKET_bc,
1784   PACKET_bs,
1785   PACKET_TracepointSource,
1786   PACKET_QAllow,
1787   PACKET_qXfer_fdpic,
1788   PACKET_QDisableRandomization,
1789   PACKET_QAgent,
1790   PACKET_QTBuffer_size,
1791   PACKET_Qbtrace_off,
1792   PACKET_Qbtrace_bts,
1793   PACKET_Qbtrace_pt,
1794   PACKET_qXfer_btrace,
1795
1796   /* Support for the QNonStop packet.  */
1797   PACKET_QNonStop,
1798
1799   /* Support for the QThreadEvents packet.  */
1800   PACKET_QThreadEvents,
1801
1802   /* Support for multi-process extensions.  */
1803   PACKET_multiprocess_feature,
1804
1805   /* Support for enabling and disabling tracepoints while a trace
1806      experiment is running.  */
1807   PACKET_EnableDisableTracepoints_feature,
1808
1809   /* Support for collecting strings using the tracenz bytecode.  */
1810   PACKET_tracenz_feature,
1811
1812   /* Support for continuing to run a trace experiment while GDB is
1813      disconnected.  */
1814   PACKET_DisconnectedTracing_feature,
1815
1816   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1817   PACKET_augmented_libraries_svr4_read_feature,
1818
1819   /* Support for the qXfer:btrace-conf:read packet.  */
1820   PACKET_qXfer_btrace_conf,
1821
1822   /* Support for the Qbtrace-conf:bts:size packet.  */
1823   PACKET_Qbtrace_conf_bts_size,
1824
1825   /* Support for swbreak+ feature.  */
1826   PACKET_swbreak_feature,
1827
1828   /* Support for hwbreak+ feature.  */
1829   PACKET_hwbreak_feature,
1830
1831   /* Support for fork events.  */
1832   PACKET_fork_event_feature,
1833
1834   /* Support for vfork events.  */
1835   PACKET_vfork_event_feature,
1836
1837   /* Support for the Qbtrace-conf:pt:size packet.  */
1838   PACKET_Qbtrace_conf_pt_size,
1839
1840   /* Support for exec events.  */
1841   PACKET_exec_event_feature,
1842
1843   /* Support for query supported vCont actions.  */
1844   PACKET_vContSupported,
1845
1846   /* Support remote CTRL-C.  */
1847   PACKET_vCtrlC,
1848
1849   /* Support TARGET_WAITKIND_NO_RESUMED.  */
1850   PACKET_no_resumed,
1851
1852   PACKET_MAX
1853 };
1854
1855 static struct packet_config remote_protocol_packets[PACKET_MAX];
1856
1857 /* Returns the packet's corresponding "set remote foo-packet" command
1858    state.  See struct packet_config for more details.  */
1859
1860 static enum auto_boolean
1861 packet_set_cmd_state (int packet)
1862 {
1863   return remote_protocol_packets[packet].detect;
1864 }
1865
1866 /* Returns whether a given packet or feature is supported.  This takes
1867    into account the state of the corresponding "set remote foo-packet"
1868    command, which may be used to bypass auto-detection.  */
1869
1870 static enum packet_support
1871 packet_config_support (struct packet_config *config)
1872 {
1873   switch (config->detect)
1874     {
1875     case AUTO_BOOLEAN_TRUE:
1876       return PACKET_ENABLE;
1877     case AUTO_BOOLEAN_FALSE:
1878       return PACKET_DISABLE;
1879     case AUTO_BOOLEAN_AUTO:
1880       return config->support;
1881     default:
1882       gdb_assert_not_reached (_("bad switch"));
1883     }
1884 }
1885
1886 /* Same as packet_config_support, but takes the packet's enum value as
1887    argument.  */
1888
1889 static enum packet_support
1890 packet_support (int packet)
1891 {
1892   struct packet_config *config = &remote_protocol_packets[packet];
1893
1894   return packet_config_support (config);
1895 }
1896
1897 static void
1898 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1899                                  struct cmd_list_element *c,
1900                                  const char *value)
1901 {
1902   struct packet_config *packet;
1903
1904   for (packet = remote_protocol_packets;
1905        packet < &remote_protocol_packets[PACKET_MAX];
1906        packet++)
1907     {
1908       if (&packet->detect == c->var)
1909         {
1910           show_packet_config_cmd (packet);
1911           return;
1912         }
1913     }
1914   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1915                   c->name);
1916 }
1917
1918 /* Should we try one of the 'Z' requests?  */
1919
1920 enum Z_packet_type
1921 {
1922   Z_PACKET_SOFTWARE_BP,
1923   Z_PACKET_HARDWARE_BP,
1924   Z_PACKET_WRITE_WP,
1925   Z_PACKET_READ_WP,
1926   Z_PACKET_ACCESS_WP,
1927   NR_Z_PACKET_TYPES
1928 };
1929
1930 /* For compatibility with older distributions.  Provide a ``set remote
1931    Z-packet ...'' command that updates all the Z packet types.  */
1932
1933 static enum auto_boolean remote_Z_packet_detect;
1934
1935 static void
1936 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
1937                                   struct cmd_list_element *c)
1938 {
1939   int i;
1940
1941   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1942     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1943 }
1944
1945 static void
1946 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1947                                    struct cmd_list_element *c,
1948                                    const char *value)
1949 {
1950   int i;
1951
1952   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1953     {
1954       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1955     }
1956 }
1957
1958 /* Returns true if the multi-process extensions are in effect.  */
1959
1960 static int
1961 remote_multi_process_p (struct remote_state *rs)
1962 {
1963   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1964 }
1965
1966 /* Returns true if fork events are supported.  */
1967
1968 static int
1969 remote_fork_event_p (struct remote_state *rs)
1970 {
1971   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1972 }
1973
1974 /* Returns true if vfork events are supported.  */
1975
1976 static int
1977 remote_vfork_event_p (struct remote_state *rs)
1978 {
1979   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1980 }
1981
1982 /* Returns true if exec events are supported.  */
1983
1984 static int
1985 remote_exec_event_p (struct remote_state *rs)
1986 {
1987   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1988 }
1989
1990 /* Insert fork catchpoint target routine.  If fork events are enabled
1991    then return success, nothing more to do.  */
1992
1993 int
1994 remote_target::insert_fork_catchpoint (int pid)
1995 {
1996   struct remote_state *rs = get_remote_state ();
1997
1998   return !remote_fork_event_p (rs);
1999 }
2000
2001 /* Remove fork catchpoint target routine.  Nothing to do, just
2002    return success.  */
2003
2004 int
2005 remote_target::remove_fork_catchpoint (int pid)
2006 {
2007   return 0;
2008 }
2009
2010 /* Insert vfork catchpoint target routine.  If vfork events are enabled
2011    then return success, nothing more to do.  */
2012
2013 int
2014 remote_target::insert_vfork_catchpoint (int pid)
2015 {
2016   struct remote_state *rs = get_remote_state ();
2017
2018   return !remote_vfork_event_p (rs);
2019 }
2020
2021 /* Remove vfork catchpoint target routine.  Nothing to do, just
2022    return success.  */
2023
2024 int
2025 remote_target::remove_vfork_catchpoint (int pid)
2026 {
2027   return 0;
2028 }
2029
2030 /* Insert exec catchpoint target routine.  If exec events are
2031    enabled, just return success.  */
2032
2033 int
2034 remote_target::insert_exec_catchpoint (int pid)
2035 {
2036   struct remote_state *rs = get_remote_state ();
2037
2038   return !remote_exec_event_p (rs);
2039 }
2040
2041 /* Remove exec catchpoint target routine.  Nothing to do, just
2042    return success.  */
2043
2044 int
2045 remote_target::remove_exec_catchpoint (int pid)
2046 {
2047   return 0;
2048 }
2049
2050 \f
2051 /* Asynchronous signal handle registered as event loop source for
2052    when we have pending events ready to be passed to the core.  */
2053
2054 static struct async_event_handler *remote_async_inferior_event_token;
2055
2056 \f
2057
2058 static ptid_t magic_null_ptid;
2059 static ptid_t not_sent_ptid;
2060 static ptid_t any_thread_ptid;
2061
2062 /* Find out if the stub attached to PID (and hence GDB should offer to
2063    detach instead of killing it when bailing out).  */
2064
2065 static int
2066 remote_query_attached (int pid)
2067 {
2068   struct remote_state *rs = get_remote_state ();
2069   size_t size = get_remote_packet_size ();
2070
2071   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2072     return 0;
2073
2074   if (remote_multi_process_p (rs))
2075     xsnprintf (rs->buf, size, "qAttached:%x", pid);
2076   else
2077     xsnprintf (rs->buf, size, "qAttached");
2078
2079   putpkt (rs->buf);
2080   getpkt (&rs->buf, &rs->buf_size, 0);
2081
2082   switch (packet_ok (rs->buf,
2083                      &remote_protocol_packets[PACKET_qAttached]))
2084     {
2085     case PACKET_OK:
2086       if (strcmp (rs->buf, "1") == 0)
2087         return 1;
2088       break;
2089     case PACKET_ERROR:
2090       warning (_("Remote failure reply: %s"), rs->buf);
2091       break;
2092     case PACKET_UNKNOWN:
2093       break;
2094     }
2095
2096   return 0;
2097 }
2098
2099 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
2100    has been invented by GDB, instead of reported by the target.  Since
2101    we can be connected to a remote system before before knowing about
2102    any inferior, mark the target with execution when we find the first
2103    inferior.  If ATTACHED is 1, then we had just attached to this
2104    inferior.  If it is 0, then we just created this inferior.  If it
2105    is -1, then try querying the remote stub to find out if it had
2106    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
2107    attempt to open this inferior's executable as the main executable
2108    if no main executable is open already.  */
2109
2110 static struct inferior *
2111 remote_add_inferior (int fake_pid_p, int pid, int attached,
2112                      int try_open_exec)
2113 {
2114   struct inferior *inf;
2115
2116   /* Check whether this process we're learning about is to be
2117      considered attached, or if is to be considered to have been
2118      spawned by the stub.  */
2119   if (attached == -1)
2120     attached = remote_query_attached (pid);
2121
2122   if (gdbarch_has_global_solist (target_gdbarch ()))
2123     {
2124       /* If the target shares code across all inferiors, then every
2125          attach adds a new inferior.  */
2126       inf = add_inferior (pid);
2127
2128       /* ... and every inferior is bound to the same program space.
2129          However, each inferior may still have its own address
2130          space.  */
2131       inf->aspace = maybe_new_address_space ();
2132       inf->pspace = current_program_space;
2133     }
2134   else
2135     {
2136       /* In the traditional debugging scenario, there's a 1-1 match
2137          between program/address spaces.  We simply bind the inferior
2138          to the program space's address space.  */
2139       inf = current_inferior ();
2140       inferior_appeared (inf, pid);
2141     }
2142
2143   inf->attach_flag = attached;
2144   inf->fake_pid_p = fake_pid_p;
2145
2146   /* If no main executable is currently open then attempt to
2147      open the file that was executed to create this inferior.  */
2148   if (try_open_exec && get_exec_file (0) == NULL)
2149     exec_file_locate_attach (pid, 0, 1);
2150
2151   return inf;
2152 }
2153
2154 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2155
2156 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
2157    according to RUNNING.  */
2158
2159 static void
2160 remote_add_thread (ptid_t ptid, int running, int executing)
2161 {
2162   struct remote_state *rs = get_remote_state ();
2163   struct thread_info *thread;
2164
2165   /* GDB historically didn't pull threads in the initial connection
2166      setup.  If the remote target doesn't even have a concept of
2167      threads (e.g., a bare-metal target), even if internally we
2168      consider that a single-threaded target, mentioning a new thread
2169      might be confusing to the user.  Be silent then, preserving the
2170      age old behavior.  */
2171   if (rs->starting_up)
2172     thread = add_thread_silent (ptid);
2173   else
2174     thread = add_thread (ptid);
2175
2176   get_remote_thread_info (thread)->vcont_resumed = executing;
2177   set_executing (ptid, executing);
2178   set_running (ptid, running);
2179 }
2180
2181 /* Come here when we learn about a thread id from the remote target.
2182    It may be the first time we hear about such thread, so take the
2183    opportunity to add it to GDB's thread list.  In case this is the
2184    first time we're noticing its corresponding inferior, add it to
2185    GDB's inferior list as well.  EXECUTING indicates whether the
2186    thread is (internally) executing or stopped.  */
2187
2188 static void
2189 remote_notice_new_inferior (ptid_t currthread, int executing)
2190 {
2191   /* In non-stop mode, we assume new found threads are (externally)
2192      running until proven otherwise with a stop reply.  In all-stop,
2193      we can only get here if all threads are stopped.  */
2194   int running = target_is_non_stop_p () ? 1 : 0;
2195
2196   /* If this is a new thread, add it to GDB's thread list.
2197      If we leave it up to WFI to do this, bad things will happen.  */
2198
2199   if (in_thread_list (currthread) && is_exited (currthread))
2200     {
2201       /* We're seeing an event on a thread id we knew had exited.
2202          This has to be a new thread reusing the old id.  Add it.  */
2203       remote_add_thread (currthread, running, executing);
2204       return;
2205     }
2206
2207   if (!in_thread_list (currthread))
2208     {
2209       struct inferior *inf = NULL;
2210       int pid = ptid_get_pid (currthread);
2211
2212       if (ptid_is_pid (inferior_ptid)
2213           && pid == ptid_get_pid (inferior_ptid))
2214         {
2215           /* inferior_ptid has no thread member yet.  This can happen
2216              with the vAttach -> remote_wait,"TAAthread:" path if the
2217              stub doesn't support qC.  This is the first stop reported
2218              after an attach, so this is the main thread.  Update the
2219              ptid in the thread list.  */
2220           if (in_thread_list (pid_to_ptid (pid)))
2221             thread_change_ptid (inferior_ptid, currthread);
2222           else
2223             {
2224               remote_add_thread (currthread, running, executing);
2225               inferior_ptid = currthread;
2226             }
2227           return;
2228         }
2229
2230       if (ptid_equal (magic_null_ptid, inferior_ptid))
2231         {
2232           /* inferior_ptid is not set yet.  This can happen with the
2233              vRun -> remote_wait,"TAAthread:" path if the stub
2234              doesn't support qC.  This is the first stop reported
2235              after an attach, so this is the main thread.  Update the
2236              ptid in the thread list.  */
2237           thread_change_ptid (inferior_ptid, currthread);
2238           return;
2239         }
2240
2241       /* When connecting to a target remote, or to a target
2242          extended-remote which already was debugging an inferior, we
2243          may not know about it yet.  Add it before adding its child
2244          thread, so notifications are emitted in a sensible order.  */
2245       if (!in_inferior_list (ptid_get_pid (currthread)))
2246         {
2247           struct remote_state *rs = get_remote_state ();
2248           int fake_pid_p = !remote_multi_process_p (rs);
2249
2250           inf = remote_add_inferior (fake_pid_p,
2251                                      ptid_get_pid (currthread), -1, 1);
2252         }
2253
2254       /* This is really a new thread.  Add it.  */
2255       remote_add_thread (currthread, running, executing);
2256
2257       /* If we found a new inferior, let the common code do whatever
2258          it needs to with it (e.g., read shared libraries, insert
2259          breakpoints), unless we're just setting up an all-stop
2260          connection.  */
2261       if (inf != NULL)
2262         {
2263           struct remote_state *rs = get_remote_state ();
2264
2265           if (!rs->starting_up)
2266             notice_new_inferior (currthread, executing, 0);
2267         }
2268     }
2269 }
2270
2271 /* Return THREAD's private thread data, creating it if necessary.  */
2272
2273 static remote_thread_info *
2274 get_remote_thread_info (thread_info *thread)
2275 {
2276   gdb_assert (thread != NULL);
2277
2278   if (thread->priv == NULL)
2279     thread->priv.reset (new remote_thread_info);
2280
2281   return static_cast<remote_thread_info *> (thread->priv.get ());
2282 }
2283
2284 /* Return PTID's private thread data, creating it if necessary.  */
2285
2286 static remote_thread_info *
2287 get_remote_thread_info (ptid_t ptid)
2288 {
2289   struct thread_info *info = find_thread_ptid (ptid);
2290
2291   return get_remote_thread_info (info);
2292 }
2293
2294 /* Call this function as a result of
2295    1) A halt indication (T packet) containing a thread id
2296    2) A direct query of currthread
2297    3) Successful execution of set thread */
2298
2299 static void
2300 record_currthread (struct remote_state *rs, ptid_t currthread)
2301 {
2302   rs->general_thread = currthread;
2303 }
2304
2305 /* If 'QPassSignals' is supported, tell the remote stub what signals
2306    it can simply pass through to the inferior without reporting.  */
2307
2308 void
2309 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2310 {
2311   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2312     {
2313       char *pass_packet, *p;
2314       int count = 0, i;
2315       struct remote_state *rs = get_remote_state ();
2316
2317       gdb_assert (numsigs < 256);
2318       for (i = 0; i < numsigs; i++)
2319         {
2320           if (pass_signals[i])
2321             count++;
2322         }
2323       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2324       strcpy (pass_packet, "QPassSignals:");
2325       p = pass_packet + strlen (pass_packet);
2326       for (i = 0; i < numsigs; i++)
2327         {
2328           if (pass_signals[i])
2329             {
2330               if (i >= 16)
2331                 *p++ = tohex (i >> 4);
2332               *p++ = tohex (i & 15);
2333               if (count)
2334                 *p++ = ';';
2335               else
2336                 break;
2337               count--;
2338             }
2339         }
2340       *p = 0;
2341       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2342         {
2343           putpkt (pass_packet);
2344           getpkt (&rs->buf, &rs->buf_size, 0);
2345           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2346           if (rs->last_pass_packet)
2347             xfree (rs->last_pass_packet);
2348           rs->last_pass_packet = pass_packet;
2349         }
2350       else
2351         xfree (pass_packet);
2352     }
2353 }
2354
2355 /* If 'QCatchSyscalls' is supported, tell the remote stub
2356    to report syscalls to GDB.  */
2357
2358 int
2359 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2360                                        gdb::array_view<const int> syscall_counts)
2361 {
2362   const char *catch_packet;
2363   enum packet_result result;
2364   int n_sysno = 0;
2365
2366   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2367     {
2368       /* Not supported.  */
2369       return 1;
2370     }
2371
2372   if (needed && any_count == 0)
2373     {
2374       /* Count how many syscalls are to be caught.  */
2375       for (size_t i = 0; i < syscall_counts.size (); i++)
2376         {
2377           if (syscall_counts[i] != 0)
2378             n_sysno++;
2379         }
2380     }
2381
2382   if (remote_debug)
2383     {
2384       fprintf_unfiltered (gdb_stdlog,
2385                           "remote_set_syscall_catchpoint "
2386                           "pid %d needed %d any_count %d n_sysno %d\n",
2387                           pid, needed, any_count, n_sysno);
2388     }
2389
2390   std::string built_packet;
2391   if (needed)
2392     {
2393       /* Prepare a packet with the sysno list, assuming max 8+1
2394          characters for a sysno.  If the resulting packet size is too
2395          big, fallback on the non-selective packet.  */
2396       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2397       built_packet.reserve (maxpktsz);
2398       built_packet = "QCatchSyscalls:1";
2399       if (any_count == 0)
2400         {
2401           /* Add in each syscall to be caught.  */
2402           for (size_t i = 0; i < syscall_counts.size (); i++)
2403             {
2404               if (syscall_counts[i] != 0)
2405                 string_appendf (built_packet, ";%zx", i);
2406             }
2407         }
2408       if (built_packet.size () > get_remote_packet_size ())
2409         {
2410           /* catch_packet too big.  Fallback to less efficient
2411              non selective mode, with GDB doing the filtering.  */
2412           catch_packet = "QCatchSyscalls:1";
2413         }
2414       else
2415         catch_packet = built_packet.c_str ();
2416     }
2417   else
2418     catch_packet = "QCatchSyscalls:0";
2419
2420   struct remote_state *rs = get_remote_state ();
2421
2422   putpkt (catch_packet);
2423   getpkt (&rs->buf, &rs->buf_size, 0);
2424   result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2425   if (result == PACKET_OK)
2426     return 0;
2427   else
2428     return -1;
2429 }
2430
2431 /* If 'QProgramSignals' is supported, tell the remote stub what
2432    signals it should pass through to the inferior when detaching.  */
2433
2434 void
2435 remote_target::program_signals (int numsigs, unsigned char *signals)
2436 {
2437   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2438     {
2439       char *packet, *p;
2440       int count = 0, i;
2441       struct remote_state *rs = get_remote_state ();
2442
2443       gdb_assert (numsigs < 256);
2444       for (i = 0; i < numsigs; i++)
2445         {
2446           if (signals[i])
2447             count++;
2448         }
2449       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2450       strcpy (packet, "QProgramSignals:");
2451       p = packet + strlen (packet);
2452       for (i = 0; i < numsigs; i++)
2453         {
2454           if (signal_pass_state (i))
2455             {
2456               if (i >= 16)
2457                 *p++ = tohex (i >> 4);
2458               *p++ = tohex (i & 15);
2459               if (count)
2460                 *p++ = ';';
2461               else
2462                 break;
2463               count--;
2464             }
2465         }
2466       *p = 0;
2467       if (!rs->last_program_signals_packet
2468           || strcmp (rs->last_program_signals_packet, packet) != 0)
2469         {
2470           putpkt (packet);
2471           getpkt (&rs->buf, &rs->buf_size, 0);
2472           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2473           xfree (rs->last_program_signals_packet);
2474           rs->last_program_signals_packet = packet;
2475         }
2476       else
2477         xfree (packet);
2478     }
2479 }
2480
2481 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2482    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2483    thread.  If GEN is set, set the general thread, if not, then set
2484    the step/continue thread.  */
2485 static void
2486 set_thread (ptid_t ptid, int gen)
2487 {
2488   struct remote_state *rs = get_remote_state ();
2489   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2490   char *buf = rs->buf;
2491   char *endbuf = rs->buf + get_remote_packet_size ();
2492
2493   if (ptid_equal (state, ptid))
2494     return;
2495
2496   *buf++ = 'H';
2497   *buf++ = gen ? 'g' : 'c';
2498   if (ptid_equal (ptid, magic_null_ptid))
2499     xsnprintf (buf, endbuf - buf, "0");
2500   else if (ptid_equal (ptid, any_thread_ptid))
2501     xsnprintf (buf, endbuf - buf, "0");
2502   else if (ptid_equal (ptid, minus_one_ptid))
2503     xsnprintf (buf, endbuf - buf, "-1");
2504   else
2505     write_ptid (buf, endbuf, ptid);
2506   putpkt (rs->buf);
2507   getpkt (&rs->buf, &rs->buf_size, 0);
2508   if (gen)
2509     rs->general_thread = ptid;
2510   else
2511     rs->continue_thread = ptid;
2512 }
2513
2514 static void
2515 set_general_thread (ptid_t ptid)
2516 {
2517   set_thread (ptid, 1);
2518 }
2519
2520 static void
2521 set_continue_thread (ptid_t ptid)
2522 {
2523   set_thread (ptid, 0);
2524 }
2525
2526 /* Change the remote current process.  Which thread within the process
2527    ends up selected isn't important, as long as it is the same process
2528    as what INFERIOR_PTID points to.
2529
2530    This comes from that fact that there is no explicit notion of
2531    "selected process" in the protocol.  The selected process for
2532    general operations is the process the selected general thread
2533    belongs to.  */
2534
2535 static void
2536 set_general_process (void)
2537 {
2538   struct remote_state *rs = get_remote_state ();
2539
2540   /* If the remote can't handle multiple processes, don't bother.  */
2541   if (!remote_multi_process_p (rs))
2542     return;
2543
2544   /* We only need to change the remote current thread if it's pointing
2545      at some other process.  */
2546   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2547     set_general_thread (inferior_ptid);
2548 }
2549
2550 \f
2551 /* Return nonzero if this is the main thread that we made up ourselves
2552    to model non-threaded targets as single-threaded.  */
2553
2554 static int
2555 remote_thread_always_alive (ptid_t ptid)
2556 {
2557   if (ptid_equal (ptid, magic_null_ptid))
2558     /* The main thread is always alive.  */
2559     return 1;
2560
2561   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2562     /* The main thread is always alive.  This can happen after a
2563        vAttach, if the remote side doesn't support
2564        multi-threading.  */
2565     return 1;
2566
2567   return 0;
2568 }
2569
2570 /* Return nonzero if the thread PTID is still alive on the remote
2571    system.  */
2572
2573 bool
2574 remote_target::thread_alive (ptid_t ptid)
2575 {
2576   struct remote_state *rs = get_remote_state ();
2577   char *p, *endp;
2578
2579   /* Check if this is a thread that we made up ourselves to model
2580      non-threaded targets as single-threaded.  */
2581   if (remote_thread_always_alive (ptid))
2582     return 1;
2583
2584   p = rs->buf;
2585   endp = rs->buf + get_remote_packet_size ();
2586
2587   *p++ = 'T';
2588   write_ptid (p, endp, ptid);
2589
2590   putpkt (rs->buf);
2591   getpkt (&rs->buf, &rs->buf_size, 0);
2592   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2593 }
2594
2595 /* Return a pointer to a thread name if we know it and NULL otherwise.
2596    The thread_info object owns the memory for the name.  */
2597
2598 const char *
2599 remote_target::thread_name (struct thread_info *info)
2600 {
2601   if (info->priv != NULL)
2602     {
2603       const std::string &name = get_remote_thread_info (info)->name;
2604       return !name.empty () ? name.c_str () : NULL;
2605     }
2606
2607   return NULL;
2608 }
2609
2610 /* About these extended threadlist and threadinfo packets.  They are
2611    variable length packets but, the fields within them are often fixed
2612    length.  They are redundent enough to send over UDP as is the
2613    remote protocol in general.  There is a matching unit test module
2614    in libstub.  */
2615
2616 /* WARNING: This threadref data structure comes from the remote O.S.,
2617    libstub protocol encoding, and remote.c.  It is not particularly
2618    changable.  */
2619
2620 /* Right now, the internal structure is int. We want it to be bigger.
2621    Plan to fix this.  */
2622
2623 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2624
2625 /* gdb_ext_thread_info is an internal GDB data structure which is
2626    equivalent to the reply of the remote threadinfo packet.  */
2627
2628 struct gdb_ext_thread_info
2629   {
2630     threadref threadid;         /* External form of thread reference.  */
2631     int active;                 /* Has state interesting to GDB?
2632                                    regs, stack.  */
2633     char display[256];          /* Brief state display, name,
2634                                    blocked/suspended.  */
2635     char shortname[32];         /* To be used to name threads.  */
2636     char more_display[256];     /* Long info, statistics, queue depth,
2637                                    whatever.  */
2638   };
2639
2640 /* The volume of remote transfers can be limited by submitting
2641    a mask containing bits specifying the desired information.
2642    Use a union of these values as the 'selection' parameter to
2643    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2644
2645 #define TAG_THREADID 1
2646 #define TAG_EXISTS 2
2647 #define TAG_DISPLAY 4
2648 #define TAG_THREADNAME 8
2649 #define TAG_MOREDISPLAY 16
2650
2651 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2652
2653 static char *unpack_nibble (char *buf, int *val);
2654
2655 static char *unpack_byte (char *buf, int *value);
2656
2657 static char *pack_int (char *buf, int value);
2658
2659 static char *unpack_int (char *buf, int *value);
2660
2661 static char *unpack_string (char *src, char *dest, int length);
2662
2663 static char *pack_threadid (char *pkt, threadref *id);
2664
2665 static char *unpack_threadid (char *inbuf, threadref *id);
2666
2667 void int_to_threadref (threadref *id, int value);
2668
2669 static int threadref_to_int (threadref *ref);
2670
2671 static void copy_threadref (threadref *dest, threadref *src);
2672
2673 static int threadmatch (threadref *dest, threadref *src);
2674
2675 static char *pack_threadinfo_request (char *pkt, int mode,
2676                                       threadref *id);
2677
2678 static int remote_unpack_thread_info_response (char *pkt,
2679                                                threadref *expectedref,
2680                                                struct gdb_ext_thread_info
2681                                                *info);
2682
2683
2684 static int remote_get_threadinfo (threadref *threadid,
2685                                   int fieldset, /*TAG mask */
2686                                   struct gdb_ext_thread_info *info);
2687
2688 static char *pack_threadlist_request (char *pkt, int startflag,
2689                                       int threadcount,
2690                                       threadref *nextthread);
2691
2692 static int parse_threadlist_response (char *pkt,
2693                                       int result_limit,
2694                                       threadref *original_echo,
2695                                       threadref *resultlist,
2696                                       int *doneflag);
2697
2698 static int remote_get_threadlist (int startflag,
2699                                   threadref *nextthread,
2700                                   int result_limit,
2701                                   int *done,
2702                                   int *result_count,
2703                                   threadref *threadlist);
2704
2705 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2706
2707 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2708                                        void *context, int looplimit);
2709
2710 static int remote_newthread_step (threadref *ref, void *context);
2711
2712
2713 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2714    buffer we're allowed to write to.  Returns
2715    BUF+CHARACTERS_WRITTEN.  */
2716
2717 static char *
2718 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2719 {
2720   int pid, tid;
2721   struct remote_state *rs = get_remote_state ();
2722
2723   if (remote_multi_process_p (rs))
2724     {
2725       pid = ptid_get_pid (ptid);
2726       if (pid < 0)
2727         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2728       else
2729         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2730     }
2731   tid = ptid_get_lwp (ptid);
2732   if (tid < 0)
2733     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2734   else
2735     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2736
2737   return buf;
2738 }
2739
2740 /* Extract a PTID from BUF.  If non-null, OBUF is set to one past the
2741    last parsed char.  Returns null_ptid if no thread id is found, and
2742    throws an error if the thread id has an invalid format.  */
2743
2744 static ptid_t
2745 read_ptid (const char *buf, const char **obuf)
2746 {
2747   const char *p = buf;
2748   const char *pp;
2749   ULONGEST pid = 0, tid = 0;
2750
2751   if (*p == 'p')
2752     {
2753       /* Multi-process ptid.  */
2754       pp = unpack_varlen_hex (p + 1, &pid);
2755       if (*pp != '.')
2756         error (_("invalid remote ptid: %s"), p);
2757
2758       p = pp;
2759       pp = unpack_varlen_hex (p + 1, &tid);
2760       if (obuf)
2761         *obuf = pp;
2762       return ptid_build (pid, tid, 0);
2763     }
2764
2765   /* No multi-process.  Just a tid.  */
2766   pp = unpack_varlen_hex (p, &tid);
2767
2768   /* Return null_ptid when no thread id is found.  */
2769   if (p == pp)
2770     {
2771       if (obuf)
2772         *obuf = pp;
2773       return null_ptid;
2774     }
2775
2776   /* Since the stub is not sending a process id, then default to
2777      what's in inferior_ptid, unless it's null at this point.  If so,
2778      then since there's no way to know the pid of the reported
2779      threads, use the magic number.  */
2780   if (ptid_equal (inferior_ptid, null_ptid))
2781     pid = ptid_get_pid (magic_null_ptid);
2782   else
2783     pid = ptid_get_pid (inferior_ptid);
2784
2785   if (obuf)
2786     *obuf = pp;
2787   return ptid_build (pid, tid, 0);
2788 }
2789
2790 static int
2791 stubhex (int ch)
2792 {
2793   if (ch >= 'a' && ch <= 'f')
2794     return ch - 'a' + 10;
2795   if (ch >= '0' && ch <= '9')
2796     return ch - '0';
2797   if (ch >= 'A' && ch <= 'F')
2798     return ch - 'A' + 10;
2799   return -1;
2800 }
2801
2802 static int
2803 stub_unpack_int (char *buff, int fieldlength)
2804 {
2805   int nibble;
2806   int retval = 0;
2807
2808   while (fieldlength)
2809     {
2810       nibble = stubhex (*buff++);
2811       retval |= nibble;
2812       fieldlength--;
2813       if (fieldlength)
2814         retval = retval << 4;
2815     }
2816   return retval;
2817 }
2818
2819 static char *
2820 unpack_nibble (char *buf, int *val)
2821 {
2822   *val = fromhex (*buf++);
2823   return buf;
2824 }
2825
2826 static char *
2827 unpack_byte (char *buf, int *value)
2828 {
2829   *value = stub_unpack_int (buf, 2);
2830   return buf + 2;
2831 }
2832
2833 static char *
2834 pack_int (char *buf, int value)
2835 {
2836   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2837   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2838   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2839   buf = pack_hex_byte (buf, (value & 0xff));
2840   return buf;
2841 }
2842
2843 static char *
2844 unpack_int (char *buf, int *value)
2845 {
2846   *value = stub_unpack_int (buf, 8);
2847   return buf + 8;
2848 }
2849
2850 #if 0                   /* Currently unused, uncomment when needed.  */
2851 static char *pack_string (char *pkt, char *string);
2852
2853 static char *
2854 pack_string (char *pkt, char *string)
2855 {
2856   char ch;
2857   int len;
2858
2859   len = strlen (string);
2860   if (len > 200)
2861     len = 200;          /* Bigger than most GDB packets, junk???  */
2862   pkt = pack_hex_byte (pkt, len);
2863   while (len-- > 0)
2864     {
2865       ch = *string++;
2866       if ((ch == '\0') || (ch == '#'))
2867         ch = '*';               /* Protect encapsulation.  */
2868       *pkt++ = ch;
2869     }
2870   return pkt;
2871 }
2872 #endif /* 0 (unused) */
2873
2874 static char *
2875 unpack_string (char *src, char *dest, int length)
2876 {
2877   while (length--)
2878     *dest++ = *src++;
2879   *dest = '\0';
2880   return src;
2881 }
2882
2883 static char *
2884 pack_threadid (char *pkt, threadref *id)
2885 {
2886   char *limit;
2887   unsigned char *altid;
2888
2889   altid = (unsigned char *) id;
2890   limit = pkt + BUF_THREAD_ID_SIZE;
2891   while (pkt < limit)
2892     pkt = pack_hex_byte (pkt, *altid++);
2893   return pkt;
2894 }
2895
2896
2897 static char *
2898 unpack_threadid (char *inbuf, threadref *id)
2899 {
2900   char *altref;
2901   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2902   int x, y;
2903
2904   altref = (char *) id;
2905
2906   while (inbuf < limit)
2907     {
2908       x = stubhex (*inbuf++);
2909       y = stubhex (*inbuf++);
2910       *altref++ = (x << 4) | y;
2911     }
2912   return inbuf;
2913 }
2914
2915 /* Externally, threadrefs are 64 bits but internally, they are still
2916    ints.  This is due to a mismatch of specifications.  We would like
2917    to use 64bit thread references internally.  This is an adapter
2918    function.  */
2919
2920 void
2921 int_to_threadref (threadref *id, int value)
2922 {
2923   unsigned char *scan;
2924
2925   scan = (unsigned char *) id;
2926   {
2927     int i = 4;
2928     while (i--)
2929       *scan++ = 0;
2930   }
2931   *scan++ = (value >> 24) & 0xff;
2932   *scan++ = (value >> 16) & 0xff;
2933   *scan++ = (value >> 8) & 0xff;
2934   *scan++ = (value & 0xff);
2935 }
2936
2937 static int
2938 threadref_to_int (threadref *ref)
2939 {
2940   int i, value = 0;
2941   unsigned char *scan;
2942
2943   scan = *ref;
2944   scan += 4;
2945   i = 4;
2946   while (i-- > 0)
2947     value = (value << 8) | ((*scan++) & 0xff);
2948   return value;
2949 }
2950
2951 static void
2952 copy_threadref (threadref *dest, threadref *src)
2953 {
2954   int i;
2955   unsigned char *csrc, *cdest;
2956
2957   csrc = (unsigned char *) src;
2958   cdest = (unsigned char *) dest;
2959   i = 8;
2960   while (i--)
2961     *cdest++ = *csrc++;
2962 }
2963
2964 static int
2965 threadmatch (threadref *dest, threadref *src)
2966 {
2967   /* Things are broken right now, so just assume we got a match.  */
2968 #if 0
2969   unsigned char *srcp, *destp;
2970   int i, result;
2971   srcp = (char *) src;
2972   destp = (char *) dest;
2973
2974   result = 1;
2975   while (i-- > 0)
2976     result &= (*srcp++ == *destp++) ? 1 : 0;
2977   return result;
2978 #endif
2979   return 1;
2980 }
2981
2982 /*
2983    threadid:1,        # always request threadid
2984    context_exists:2,
2985    display:4,
2986    unique_name:8,
2987    more_display:16
2988  */
2989
2990 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2991
2992 static char *
2993 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2994 {
2995   *pkt++ = 'q';                         /* Info Query */
2996   *pkt++ = 'P';                         /* process or thread info */
2997   pkt = pack_int (pkt, mode);           /* mode */
2998   pkt = pack_threadid (pkt, id);        /* threadid */
2999   *pkt = '\0';                          /* terminate */
3000   return pkt;
3001 }
3002
3003 /* These values tag the fields in a thread info response packet.  */
3004 /* Tagging the fields allows us to request specific fields and to
3005    add more fields as time goes by.  */
3006
3007 #define TAG_THREADID 1          /* Echo the thread identifier.  */
3008 #define TAG_EXISTS 2            /* Is this process defined enough to
3009                                    fetch registers and its stack?  */
3010 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
3011 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
3012 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
3013                                    the process.  */
3014
3015 static int
3016 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
3017                                     struct gdb_ext_thread_info *info)
3018 {
3019   struct remote_state *rs = get_remote_state ();
3020   int mask, length;
3021   int tag;
3022   threadref ref;
3023   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
3024   int retval = 1;
3025
3026   /* info->threadid = 0; FIXME: implement zero_threadref.  */
3027   info->active = 0;
3028   info->display[0] = '\0';
3029   info->shortname[0] = '\0';
3030   info->more_display[0] = '\0';
3031
3032   /* Assume the characters indicating the packet type have been
3033      stripped.  */
3034   pkt = unpack_int (pkt, &mask);        /* arg mask */
3035   pkt = unpack_threadid (pkt, &ref);
3036
3037   if (mask == 0)
3038     warning (_("Incomplete response to threadinfo request."));
3039   if (!threadmatch (&ref, expectedref))
3040     {                   /* This is an answer to a different request.  */
3041       warning (_("ERROR RMT Thread info mismatch."));
3042       return 0;
3043     }
3044   copy_threadref (&info->threadid, &ref);
3045
3046   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
3047
3048   /* Packets are terminated with nulls.  */
3049   while ((pkt < limit) && mask && *pkt)
3050     {
3051       pkt = unpack_int (pkt, &tag);     /* tag */
3052       pkt = unpack_byte (pkt, &length); /* length */
3053       if (!(tag & mask))                /* Tags out of synch with mask.  */
3054         {
3055           warning (_("ERROR RMT: threadinfo tag mismatch."));
3056           retval = 0;
3057           break;
3058         }
3059       if (tag == TAG_THREADID)
3060         {
3061           if (length != 16)
3062             {
3063               warning (_("ERROR RMT: length of threadid is not 16."));
3064               retval = 0;
3065               break;
3066             }
3067           pkt = unpack_threadid (pkt, &ref);
3068           mask = mask & ~TAG_THREADID;
3069           continue;
3070         }
3071       if (tag == TAG_EXISTS)
3072         {
3073           info->active = stub_unpack_int (pkt, length);
3074           pkt += length;
3075           mask = mask & ~(TAG_EXISTS);
3076           if (length > 8)
3077             {
3078               warning (_("ERROR RMT: 'exists' length too long."));
3079               retval = 0;
3080               break;
3081             }
3082           continue;
3083         }
3084       if (tag == TAG_THREADNAME)
3085         {
3086           pkt = unpack_string (pkt, &info->shortname[0], length);
3087           mask = mask & ~TAG_THREADNAME;
3088           continue;
3089         }
3090       if (tag == TAG_DISPLAY)
3091         {
3092           pkt = unpack_string (pkt, &info->display[0], length);
3093           mask = mask & ~TAG_DISPLAY;
3094           continue;
3095         }
3096       if (tag == TAG_MOREDISPLAY)
3097         {
3098           pkt = unpack_string (pkt, &info->more_display[0], length);
3099           mask = mask & ~TAG_MOREDISPLAY;
3100           continue;
3101         }
3102       warning (_("ERROR RMT: unknown thread info tag."));
3103       break;                    /* Not a tag we know about.  */
3104     }
3105   return retval;
3106 }
3107
3108 static int
3109 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
3110                        struct gdb_ext_thread_info *info)
3111 {
3112   struct remote_state *rs = get_remote_state ();
3113   int result;
3114
3115   pack_threadinfo_request (rs->buf, fieldset, threadid);
3116   putpkt (rs->buf);
3117   getpkt (&rs->buf, &rs->buf_size, 0);
3118
3119   if (rs->buf[0] == '\0')
3120     return 0;
3121
3122   result = remote_unpack_thread_info_response (rs->buf + 2,
3123                                                threadid, info);
3124   return result;
3125 }
3126
3127 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
3128
3129 static char *
3130 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3131                          threadref *nextthread)
3132 {
3133   *pkt++ = 'q';                 /* info query packet */
3134   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
3135   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
3136   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
3137   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
3138   *pkt = '\0';
3139   return pkt;
3140 }
3141
3142 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3143
3144 static int
3145 parse_threadlist_response (char *pkt, int result_limit,
3146                            threadref *original_echo, threadref *resultlist,
3147                            int *doneflag)
3148 {
3149   struct remote_state *rs = get_remote_state ();
3150   char *limit;
3151   int count, resultcount, done;
3152
3153   resultcount = 0;
3154   /* Assume the 'q' and 'M chars have been stripped.  */
3155   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3156   /* done parse past here */
3157   pkt = unpack_byte (pkt, &count);      /* count field */
3158   pkt = unpack_nibble (pkt, &done);
3159   /* The first threadid is the argument threadid.  */
3160   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
3161   while ((count-- > 0) && (pkt < limit))
3162     {
3163       pkt = unpack_threadid (pkt, resultlist++);
3164       if (resultcount++ >= result_limit)
3165         break;
3166     }
3167   if (doneflag)
3168     *doneflag = done;
3169   return resultcount;
3170 }
3171
3172 /* Fetch the next batch of threads from the remote.  Returns -1 if the
3173    qL packet is not supported, 0 on error and 1 on success.  */
3174
3175 static int
3176 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
3177                        int *done, int *result_count, threadref *threadlist)
3178 {
3179   struct remote_state *rs = get_remote_state ();
3180   int result = 1;
3181
3182   /* Trancate result limit to be smaller than the packet size.  */
3183   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3184       >= get_remote_packet_size ())
3185     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3186
3187   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3188   putpkt (rs->buf);
3189   getpkt (&rs->buf, &rs->buf_size, 0);
3190   if (*rs->buf == '\0')
3191     {
3192       /* Packet not supported.  */
3193       return -1;
3194     }
3195
3196   *result_count =
3197     parse_threadlist_response (rs->buf + 2, result_limit,
3198                                &rs->echo_nextthread, threadlist, done);
3199
3200   if (!threadmatch (&rs->echo_nextthread, nextthread))
3201     {
3202       /* FIXME: This is a good reason to drop the packet.  */
3203       /* Possably, there is a duplicate response.  */
3204       /* Possabilities :
3205          retransmit immediatly - race conditions
3206          retransmit after timeout - yes
3207          exit
3208          wait for packet, then exit
3209        */
3210       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3211       return 0;                 /* I choose simply exiting.  */
3212     }
3213   if (*result_count <= 0)
3214     {
3215       if (*done != 1)
3216         {
3217           warning (_("RMT ERROR : failed to get remote thread list."));
3218           result = 0;
3219         }
3220       return result;            /* break; */
3221     }
3222   if (*result_count > result_limit)
3223     {
3224       *result_count = 0;
3225       warning (_("RMT ERROR: threadlist response longer than requested."));
3226       return 0;
3227     }
3228   return result;
3229 }
3230
3231 /* Fetch the list of remote threads, with the qL packet, and call
3232    STEPFUNCTION for each thread found.  Stops iterating and returns 1
3233    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
3234    STEPFUNCTION returns false.  If the packet is not supported,
3235    returns -1.  */
3236
3237 static int
3238 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
3239                             int looplimit)
3240 {
3241   struct remote_state *rs = get_remote_state ();
3242   int done, i, result_count;
3243   int startflag = 1;
3244   int result = 1;
3245   int loopcount = 0;
3246
3247   done = 0;
3248   while (!done)
3249     {
3250       if (loopcount++ > looplimit)
3251         {
3252           result = 0;
3253           warning (_("Remote fetch threadlist -infinite loop-."));
3254           break;
3255         }
3256       result = remote_get_threadlist (startflag, &rs->nextthread,
3257                                       MAXTHREADLISTRESULTS,
3258                                       &done, &result_count,
3259                                       rs->resultthreadlist);
3260       if (result <= 0)
3261         break;
3262       /* Clear for later iterations.  */
3263       startflag = 0;
3264       /* Setup to resume next batch of thread references, set nextthread.  */
3265       if (result_count >= 1)
3266         copy_threadref (&rs->nextthread,
3267                         &rs->resultthreadlist[result_count - 1]);
3268       i = 0;
3269       while (result_count--)
3270         {
3271           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3272             {
3273               result = 0;
3274               break;
3275             }
3276         }
3277     }
3278   return result;
3279 }
3280
3281 /* A thread found on the remote target.  */
3282
3283 struct thread_item
3284 {
3285   explicit thread_item (ptid_t ptid_)
3286   : ptid (ptid_)
3287   {}
3288
3289   thread_item (thread_item &&other) = default;
3290   thread_item &operator= (thread_item &&other) = default;
3291
3292   DISABLE_COPY_AND_ASSIGN (thread_item);
3293
3294   /* The thread's PTID.  */
3295   ptid_t ptid;
3296
3297   /* The thread's extra info.  */
3298   std::string extra;
3299
3300   /* The thread's name.  */
3301   std::string name;
3302
3303   /* The core the thread was running on.  -1 if not known.  */
3304   int core = -1;
3305
3306   /* The thread handle associated with the thread.  */
3307   gdb::byte_vector thread_handle;
3308 };
3309
3310 /* Context passed around to the various methods listing remote
3311    threads.  As new threads are found, they're added to the ITEMS
3312    vector.  */
3313
3314 struct threads_listing_context
3315 {
3316   /* Return true if this object contains an entry for a thread with ptid
3317      PTID.  */
3318
3319   bool contains_thread (ptid_t ptid) const
3320   {
3321     auto match_ptid = [&] (const thread_item &item)
3322       {
3323         return item.ptid == ptid;
3324       };
3325
3326     auto it = std::find_if (this->items.begin (),
3327                             this->items.end (),
3328                             match_ptid);
3329
3330     return it != this->items.end ();
3331   }
3332
3333   /* Remove the thread with ptid PTID.  */
3334
3335   void remove_thread (ptid_t ptid)
3336   {
3337     auto match_ptid = [&] (const thread_item &item)
3338       {
3339         return item.ptid == ptid;
3340       };
3341
3342     auto it = std::remove_if (this->items.begin (),
3343                               this->items.end (),
3344                               match_ptid);
3345
3346     if (it != this->items.end ())
3347       this->items.erase (it);
3348   }
3349
3350   /* The threads found on the remote target.  */
3351   std::vector<thread_item> items;
3352 };
3353
3354 static int
3355 remote_newthread_step (threadref *ref, void *data)
3356 {
3357   struct threads_listing_context *context
3358     = (struct threads_listing_context *) data;
3359   int pid = inferior_ptid.pid ();
3360   int lwp = threadref_to_int (ref);
3361   ptid_t ptid (pid, lwp);
3362
3363   context->items.emplace_back (ptid);
3364
3365   return 1;                     /* continue iterator */
3366 }
3367
3368 #define CRAZY_MAX_THREADS 1000
3369
3370 static ptid_t
3371 remote_current_thread (ptid_t oldpid)
3372 {
3373   struct remote_state *rs = get_remote_state ();
3374
3375   putpkt ("qC");
3376   getpkt (&rs->buf, &rs->buf_size, 0);
3377   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3378     {
3379       const char *obuf;
3380       ptid_t result;
3381
3382       result = read_ptid (&rs->buf[2], &obuf);
3383       if (*obuf != '\0' && remote_debug)
3384         fprintf_unfiltered (gdb_stdlog,
3385                             "warning: garbage in qC reply\n");
3386
3387       return result;
3388     }
3389   else
3390     return oldpid;
3391 }
3392
3393 /* List remote threads using the deprecated qL packet.  */
3394
3395 static int
3396 remote_get_threads_with_ql (struct target_ops *ops,
3397                             struct threads_listing_context *context)
3398 {
3399   if (remote_threadlist_iterator (remote_newthread_step, context,
3400                                   CRAZY_MAX_THREADS) >= 0)
3401     return 1;
3402
3403   return 0;
3404 }
3405
3406 #if defined(HAVE_LIBEXPAT)
3407
3408 static void
3409 start_thread (struct gdb_xml_parser *parser,
3410               const struct gdb_xml_element *element,
3411               void *user_data,
3412               std::vector<gdb_xml_value> &attributes)
3413 {
3414   struct threads_listing_context *data
3415     = (struct threads_listing_context *) user_data;
3416   struct gdb_xml_value *attr;
3417
3418   char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3419   ptid_t ptid = read_ptid (id, NULL);
3420
3421   data->items.emplace_back (ptid);
3422   thread_item &item = data->items.back ();
3423
3424   attr = xml_find_attribute (attributes, "core");
3425   if (attr != NULL)
3426     item.core = *(ULONGEST *) attr->value.get ();
3427
3428   attr = xml_find_attribute (attributes, "name");
3429   if (attr != NULL)
3430     item.name = (const char *) attr->value.get ();
3431
3432   attr = xml_find_attribute (attributes, "handle");
3433   if (attr != NULL)
3434     item.thread_handle = hex2bin ((const char *) attr->value.get ());
3435 }
3436
3437 static void
3438 end_thread (struct gdb_xml_parser *parser,
3439             const struct gdb_xml_element *element,
3440             void *user_data, const char *body_text)
3441 {
3442   struct threads_listing_context *data
3443     = (struct threads_listing_context *) user_data;
3444
3445   if (body_text != NULL && *body_text != '\0')
3446     data->items.back ().extra = body_text;
3447 }
3448
3449 const struct gdb_xml_attribute thread_attributes[] = {
3450   { "id", GDB_XML_AF_NONE, NULL, NULL },
3451   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3452   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3453   { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3454   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3455 };
3456
3457 const struct gdb_xml_element thread_children[] = {
3458   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3459 };
3460
3461 const struct gdb_xml_element threads_children[] = {
3462   { "thread", thread_attributes, thread_children,
3463     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3464     start_thread, end_thread },
3465   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3466 };
3467
3468 const struct gdb_xml_element threads_elements[] = {
3469   { "threads", NULL, threads_children,
3470     GDB_XML_EF_NONE, NULL, NULL },
3471   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3472 };
3473
3474 #endif
3475
3476 /* List remote threads using qXfer:threads:read.  */
3477
3478 static int
3479 remote_get_threads_with_qxfer (struct target_ops *ops,
3480                                struct threads_listing_context *context)
3481 {
3482 #if defined(HAVE_LIBEXPAT)
3483   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3484     {
3485       gdb::optional<gdb::char_vector> xml
3486         = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3487
3488       if (xml && (*xml)[0] != '\0')
3489         {
3490           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3491                                threads_elements, xml->data (), context);
3492         }
3493
3494       return 1;
3495     }
3496 #endif
3497
3498   return 0;
3499 }
3500
3501 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3502
3503 static int
3504 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3505                                      struct threads_listing_context *context)
3506 {
3507   struct remote_state *rs = get_remote_state ();
3508
3509   if (rs->use_threadinfo_query)
3510     {
3511       const char *bufp;
3512
3513       putpkt ("qfThreadInfo");
3514       getpkt (&rs->buf, &rs->buf_size, 0);
3515       bufp = rs->buf;
3516       if (bufp[0] != '\0')              /* q packet recognized */
3517         {
3518           while (*bufp++ == 'm')        /* reply contains one or more TID */
3519             {
3520               do
3521                 {
3522                   ptid_t ptid = read_ptid (bufp, &bufp);
3523                   context->items.emplace_back (ptid);
3524                 }
3525               while (*bufp++ == ',');   /* comma-separated list */
3526               putpkt ("qsThreadInfo");
3527               getpkt (&rs->buf, &rs->buf_size, 0);
3528               bufp = rs->buf;
3529             }
3530           return 1;
3531         }
3532       else
3533         {
3534           /* Packet not recognized.  */
3535           rs->use_threadinfo_query = 0;
3536         }
3537     }
3538
3539   return 0;
3540 }
3541
3542 /* Implement the to_update_thread_list function for the remote
3543    targets.  */
3544
3545 void
3546 remote_target::update_thread_list ()
3547 {
3548   struct threads_listing_context context;
3549   int got_list = 0;
3550
3551   /* We have a few different mechanisms to fetch the thread list.  Try
3552      them all, starting with the most preferred one first, falling
3553      back to older methods.  */
3554   if (remote_get_threads_with_qxfer (this, &context)
3555       || remote_get_threads_with_qthreadinfo (this, &context)
3556       || remote_get_threads_with_ql (this, &context))
3557     {
3558       struct thread_info *tp, *tmp;
3559
3560       got_list = 1;
3561
3562       if (context.items.empty ()
3563           && remote_thread_always_alive (inferior_ptid))
3564         {
3565           /* Some targets don't really support threads, but still
3566              reply an (empty) thread list in response to the thread
3567              listing packets, instead of replying "packet not
3568              supported".  Exit early so we don't delete the main
3569              thread.  */
3570           return;
3571         }
3572
3573       /* CONTEXT now holds the current thread list on the remote
3574          target end.  Delete GDB-side threads no longer found on the
3575          target.  */
3576       ALL_THREADS_SAFE (tp, tmp)
3577         {
3578           if (!context.contains_thread (tp->ptid))
3579             {
3580               /* Not found.  */
3581               delete_thread (tp->ptid);
3582             }
3583         }
3584
3585       /* Remove any unreported fork child threads from CONTEXT so
3586          that we don't interfere with follow fork, which is where
3587          creation of such threads is handled.  */
3588       remove_new_fork_children (&context);
3589
3590       /* And now add threads we don't know about yet to our list.  */
3591       for (thread_item &item : context.items)
3592         {
3593           if (item.ptid != null_ptid)
3594             {
3595               /* In non-stop mode, we assume new found threads are
3596                  executing until proven otherwise with a stop reply.
3597                  In all-stop, we can only get here if all threads are
3598                  stopped.  */
3599               int executing = target_is_non_stop_p () ? 1 : 0;
3600
3601               remote_notice_new_inferior (item.ptid, executing);
3602
3603               remote_thread_info *info = get_remote_thread_info (item.ptid);
3604               info->core = item.core;
3605               info->extra = std::move (item.extra);
3606               info->name = std::move (item.name);
3607               info->thread_handle = std::move (item.thread_handle);
3608             }
3609         }
3610     }
3611
3612   if (!got_list)
3613     {
3614       /* If no thread listing method is supported, then query whether
3615          each known thread is alive, one by one, with the T packet.
3616          If the target doesn't support threads at all, then this is a
3617          no-op.  See remote_thread_alive.  */
3618       prune_threads ();
3619     }
3620 }
3621
3622 /*
3623  * Collect a descriptive string about the given thread.
3624  * The target may say anything it wants to about the thread
3625  * (typically info about its blocked / runnable state, name, etc.).
3626  * This string will appear in the info threads display.
3627  *
3628  * Optional: targets are not required to implement this function.
3629  */
3630
3631 const char *
3632 remote_target::extra_thread_info (thread_info *tp)
3633 {
3634   struct remote_state *rs = get_remote_state ();
3635   int result;
3636   int set;
3637   threadref id;
3638   struct gdb_ext_thread_info threadinfo;
3639   static char display_buf[100]; /* arbitrary...  */
3640   int n = 0;                    /* position in display_buf */
3641
3642   if (rs->remote_desc == 0)             /* paranoia */
3643     internal_error (__FILE__, __LINE__,
3644                     _("remote_threads_extra_info"));
3645
3646   if (ptid_equal (tp->ptid, magic_null_ptid)
3647       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3648     /* This is the main thread which was added by GDB.  The remote
3649        server doesn't know about it.  */
3650     return NULL;
3651
3652   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3653     {
3654       struct thread_info *info = find_thread_ptid (tp->ptid);
3655
3656       if (info != NULL && info->priv != NULL)
3657         {
3658           const std::string &extra = get_remote_thread_info (info)->extra;
3659           return !extra.empty () ? extra.c_str () : NULL;
3660         }
3661       else
3662         return NULL;
3663     }
3664
3665   if (rs->use_threadextra_query)
3666     {
3667       char *b = rs->buf;
3668       char *endb = rs->buf + get_remote_packet_size ();
3669
3670       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3671       b += strlen (b);
3672       write_ptid (b, endb, tp->ptid);
3673
3674       putpkt (rs->buf);
3675       getpkt (&rs->buf, &rs->buf_size, 0);
3676       if (rs->buf[0] != 0)
3677         {
3678           n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3679           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3680           display_buf [result] = '\0';
3681           return display_buf;
3682         }
3683     }
3684
3685   /* If the above query fails, fall back to the old method.  */
3686   rs->use_threadextra_query = 0;
3687   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3688     | TAG_MOREDISPLAY | TAG_DISPLAY;
3689   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3690   if (remote_get_threadinfo (&id, set, &threadinfo))
3691     if (threadinfo.active)
3692       {
3693         if (*threadinfo.shortname)
3694           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3695                           " Name: %s,", threadinfo.shortname);
3696         if (*threadinfo.display)
3697           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3698                           " State: %s,", threadinfo.display);
3699         if (*threadinfo.more_display)
3700           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3701                           " Priority: %s", threadinfo.more_display);
3702
3703         if (n > 0)
3704           {
3705             /* For purely cosmetic reasons, clear up trailing commas.  */
3706             if (',' == display_buf[n-1])
3707               display_buf[n-1] = ' ';
3708             return display_buf;
3709           }
3710       }
3711   return NULL;
3712 }
3713 \f
3714
3715 bool
3716 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3717                                             struct static_tracepoint_marker *marker)
3718 {
3719   struct remote_state *rs = get_remote_state ();
3720   char *p = rs->buf;
3721
3722   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3723   p += strlen (p);
3724   p += hexnumstr (p, addr);
3725   putpkt (rs->buf);
3726   getpkt (&rs->buf, &rs->buf_size, 0);
3727   p = rs->buf;
3728
3729   if (*p == 'E')
3730     error (_("Remote failure reply: %s"), p);
3731
3732   if (*p++ == 'm')
3733     {
3734       parse_static_tracepoint_marker_definition (p, NULL, marker);
3735       return true;
3736     }
3737
3738   return false;
3739 }
3740
3741 std::vector<static_tracepoint_marker>
3742 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3743 {
3744   struct remote_state *rs = get_remote_state ();
3745   std::vector<static_tracepoint_marker> markers;
3746   const char *p;
3747   static_tracepoint_marker marker;
3748
3749   /* Ask for a first packet of static tracepoint marker
3750      definition.  */
3751   putpkt ("qTfSTM");
3752   getpkt (&rs->buf, &rs->buf_size, 0);
3753   p = rs->buf;
3754   if (*p == 'E')
3755     error (_("Remote failure reply: %s"), p);
3756
3757   while (*p++ == 'm')
3758     {
3759       do
3760         {
3761           parse_static_tracepoint_marker_definition (p, &p, &marker);
3762
3763           if (strid == NULL || marker.str_id == strid)
3764             markers.push_back (std::move (marker));
3765         }
3766       while (*p++ == ',');      /* comma-separated list */
3767       /* Ask for another packet of static tracepoint definition.  */
3768       putpkt ("qTsSTM");
3769       getpkt (&rs->buf, &rs->buf_size, 0);
3770       p = rs->buf;
3771     }
3772
3773   return markers;
3774 }
3775
3776 \f
3777 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3778
3779 ptid_t
3780 remote_target::get_ada_task_ptid (long lwp, long thread)
3781 {
3782   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3783 }
3784 \f
3785
3786 /* Restart the remote side; this is an extended protocol operation.  */
3787
3788 static void
3789 extended_remote_restart (void)
3790 {
3791   struct remote_state *rs = get_remote_state ();
3792
3793   /* Send the restart command; for reasons I don't understand the
3794      remote side really expects a number after the "R".  */
3795   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3796   putpkt (rs->buf);
3797
3798   remote_fileio_reset ();
3799 }
3800 \f
3801 /* Clean up connection to a remote debugger.  */
3802
3803 void
3804 remote_target::close ()
3805 {
3806   struct remote_state *rs = get_remote_state ();
3807
3808   if (rs->remote_desc == NULL)
3809     return; /* already closed */
3810
3811   /* Make sure we leave stdin registered in the event loop.  */
3812   terminal_ours ();
3813
3814   serial_close (rs->remote_desc);
3815   rs->remote_desc = NULL;
3816
3817   /* We don't have a connection to the remote stub anymore.  Get rid
3818      of all the inferiors and their threads we were controlling.
3819      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3820      will be unable to find the thread corresponding to (pid, 0, 0).  */
3821   inferior_ptid = null_ptid;
3822   discard_all_inferiors ();
3823
3824   /* We are closing the remote target, so we should discard
3825      everything of this target.  */
3826   discard_pending_stop_replies_in_queue (rs);
3827
3828   if (remote_async_inferior_event_token)
3829     delete_async_event_handler (&remote_async_inferior_event_token);
3830
3831   remote_notif_state_xfree (rs->notif_state);
3832
3833   trace_reset_local_state ();
3834 }
3835
3836 /* Query the remote side for the text, data and bss offsets.  */
3837
3838 static void
3839 get_offsets (void)
3840 {
3841   struct remote_state *rs = get_remote_state ();
3842   char *buf;
3843   char *ptr;
3844   int lose, num_segments = 0, do_sections, do_segments;
3845   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3846   struct section_offsets *offs;
3847   struct symfile_segment_data *data;
3848
3849   if (symfile_objfile == NULL)
3850     return;
3851
3852   putpkt ("qOffsets");
3853   getpkt (&rs->buf, &rs->buf_size, 0);
3854   buf = rs->buf;
3855
3856   if (buf[0] == '\000')
3857     return;                     /* Return silently.  Stub doesn't support
3858                                    this command.  */
3859   if (buf[0] == 'E')
3860     {
3861       warning (_("Remote failure reply: %s"), buf);
3862       return;
3863     }
3864
3865   /* Pick up each field in turn.  This used to be done with scanf, but
3866      scanf will make trouble if CORE_ADDR size doesn't match
3867      conversion directives correctly.  The following code will work
3868      with any size of CORE_ADDR.  */
3869   text_addr = data_addr = bss_addr = 0;
3870   ptr = buf;
3871   lose = 0;
3872
3873   if (startswith (ptr, "Text="))
3874     {
3875       ptr += 5;
3876       /* Don't use strtol, could lose on big values.  */
3877       while (*ptr && *ptr != ';')
3878         text_addr = (text_addr << 4) + fromhex (*ptr++);
3879
3880       if (startswith (ptr, ";Data="))
3881         {
3882           ptr += 6;
3883           while (*ptr && *ptr != ';')
3884             data_addr = (data_addr << 4) + fromhex (*ptr++);
3885         }
3886       else
3887         lose = 1;
3888
3889       if (!lose && startswith (ptr, ";Bss="))
3890         {
3891           ptr += 5;
3892           while (*ptr && *ptr != ';')
3893             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3894
3895           if (bss_addr != data_addr)
3896             warning (_("Target reported unsupported offsets: %s"), buf);
3897         }
3898       else
3899         lose = 1;
3900     }
3901   else if (startswith (ptr, "TextSeg="))
3902     {
3903       ptr += 8;
3904       /* Don't use strtol, could lose on big values.  */
3905       while (*ptr && *ptr != ';')
3906         text_addr = (text_addr << 4) + fromhex (*ptr++);
3907       num_segments = 1;
3908
3909       if (startswith (ptr, ";DataSeg="))
3910         {
3911           ptr += 9;
3912           while (*ptr && *ptr != ';')
3913             data_addr = (data_addr << 4) + fromhex (*ptr++);
3914           num_segments++;
3915         }
3916     }
3917   else
3918     lose = 1;
3919
3920   if (lose)
3921     error (_("Malformed response to offset query, %s"), buf);
3922   else if (*ptr != '\0')
3923     warning (_("Target reported unsupported offsets: %s"), buf);
3924
3925   offs = ((struct section_offsets *)
3926           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3927   memcpy (offs, symfile_objfile->section_offsets,
3928           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3929
3930   data = get_symfile_segment_data (symfile_objfile->obfd);
3931   do_segments = (data != NULL);
3932   do_sections = num_segments == 0;
3933
3934   if (num_segments > 0)
3935     {
3936       segments[0] = text_addr;
3937       segments[1] = data_addr;
3938     }
3939   /* If we have two segments, we can still try to relocate everything
3940      by assuming that the .text and .data offsets apply to the whole
3941      text and data segments.  Convert the offsets given in the packet
3942      to base addresses for symfile_map_offsets_to_segments.  */
3943   else if (data && data->num_segments == 2)
3944     {
3945       segments[0] = data->segment_bases[0] + text_addr;
3946       segments[1] = data->segment_bases[1] + data_addr;
3947       num_segments = 2;
3948     }
3949   /* If the object file has only one segment, assume that it is text
3950      rather than data; main programs with no writable data are rare,
3951      but programs with no code are useless.  Of course the code might
3952      have ended up in the data segment... to detect that we would need
3953      the permissions here.  */
3954   else if (data && data->num_segments == 1)
3955     {
3956       segments[0] = data->segment_bases[0] + text_addr;
3957       num_segments = 1;
3958     }
3959   /* There's no way to relocate by segment.  */
3960   else
3961     do_segments = 0;
3962
3963   if (do_segments)
3964     {
3965       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3966                                                  offs, num_segments, segments);
3967
3968       if (ret == 0 && !do_sections)
3969         error (_("Can not handle qOffsets TextSeg "
3970                  "response with this symbol file"));
3971
3972       if (ret > 0)
3973         do_sections = 0;
3974     }
3975
3976   if (data)
3977     free_symfile_segment_data (data);
3978
3979   if (do_sections)
3980     {
3981       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3982
3983       /* This is a temporary kludge to force data and bss to use the
3984          same offsets because that's what nlmconv does now.  The real
3985          solution requires changes to the stub and remote.c that I
3986          don't have time to do right now.  */
3987
3988       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3989       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3990     }
3991
3992   objfile_relocate (symfile_objfile, offs);
3993 }
3994
3995 /* Send interrupt_sequence to remote target.  */
3996 static void
3997 send_interrupt_sequence (void)
3998 {
3999   struct remote_state *rs = get_remote_state ();
4000
4001   if (interrupt_sequence_mode == interrupt_sequence_control_c)
4002     remote_serial_write ("\x03", 1);
4003   else if (interrupt_sequence_mode == interrupt_sequence_break)
4004     serial_send_break (rs->remote_desc);
4005   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4006     {
4007       serial_send_break (rs->remote_desc);
4008       remote_serial_write ("g", 1);
4009     }
4010   else
4011     internal_error (__FILE__, __LINE__,
4012                     _("Invalid value for interrupt_sequence_mode: %s."),
4013                     interrupt_sequence_mode);
4014 }
4015
4016
4017 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4018    and extract the PTID.  Returns NULL_PTID if not found.  */
4019
4020 static ptid_t
4021 stop_reply_extract_thread (char *stop_reply)
4022 {
4023   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4024     {
4025       const char *p;
4026
4027       /* Txx r:val ; r:val (...)  */
4028       p = &stop_reply[3];
4029
4030       /* Look for "register" named "thread".  */
4031       while (*p != '\0')
4032         {
4033           const char *p1;
4034
4035           p1 = strchr (p, ':');
4036           if (p1 == NULL)
4037             return null_ptid;
4038
4039           if (strncmp (p, "thread", p1 - p) == 0)
4040             return read_ptid (++p1, &p);
4041
4042           p1 = strchr (p, ';');
4043           if (p1 == NULL)
4044             return null_ptid;
4045           p1++;
4046
4047           p = p1;
4048         }
4049     }
4050
4051   return null_ptid;
4052 }
4053
4054 /* Determine the remote side's current thread.  If we have a stop
4055    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4056    "thread" register we can extract the current thread from.  If not,
4057    ask the remote which is the current thread with qC.  The former
4058    method avoids a roundtrip.  */
4059
4060 static ptid_t
4061 get_current_thread (char *wait_status)
4062 {
4063   ptid_t ptid = null_ptid;
4064
4065   /* Note we don't use remote_parse_stop_reply as that makes use of
4066      the target architecture, which we haven't yet fully determined at
4067      this point.  */
4068   if (wait_status != NULL)
4069     ptid = stop_reply_extract_thread (wait_status);
4070   if (ptid_equal (ptid, null_ptid))
4071     ptid = remote_current_thread (inferior_ptid);
4072
4073   return ptid;
4074 }
4075
4076 /* Query the remote target for which is the current thread/process,
4077    add it to our tables, and update INFERIOR_PTID.  The caller is
4078    responsible for setting the state such that the remote end is ready
4079    to return the current thread.
4080
4081    This function is called after handling the '?' or 'vRun' packets,
4082    whose response is a stop reply from which we can also try
4083    extracting the thread.  If the target doesn't support the explicit
4084    qC query, we infer the current thread from that stop reply, passed
4085    in in WAIT_STATUS, which may be NULL.  */
4086
4087 static void
4088 add_current_inferior_and_thread (char *wait_status)
4089 {
4090   struct remote_state *rs = get_remote_state ();
4091   int fake_pid_p = 0;
4092
4093   inferior_ptid = null_ptid;
4094
4095   /* Now, if we have thread information, update inferior_ptid.  */
4096   ptid_t curr_ptid = get_current_thread (wait_status);
4097
4098   if (curr_ptid != null_ptid)
4099     {
4100       if (!remote_multi_process_p (rs))
4101         fake_pid_p = 1;
4102     }
4103   else
4104     {
4105       /* Without this, some commands which require an active target
4106          (such as kill) won't work.  This variable serves (at least)
4107          double duty as both the pid of the target process (if it has
4108          such), and as a flag indicating that a target is active.  */
4109       curr_ptid = magic_null_ptid;
4110       fake_pid_p = 1;
4111     }
4112
4113   remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
4114
4115   /* Add the main thread and switch to it.  Don't try reading
4116      registers yet, since we haven't fetched the target description
4117      yet.  */
4118   thread_info *tp = add_thread_silent (curr_ptid);
4119   switch_to_thread_no_regs (tp);
4120 }
4121
4122 /* Print info about a thread that was found already stopped on
4123    connection.  */
4124
4125 static void
4126 print_one_stopped_thread (struct thread_info *thread)
4127 {
4128   struct target_waitstatus *ws = &thread->suspend.waitstatus;
4129
4130   switch_to_thread (thread->ptid);
4131   stop_pc = get_frame_pc (get_current_frame ());
4132   set_current_sal_from_frame (get_current_frame ());
4133
4134   thread->suspend.waitstatus_pending_p = 0;
4135
4136   if (ws->kind == TARGET_WAITKIND_STOPPED)
4137     {
4138       enum gdb_signal sig = ws->value.sig;
4139
4140       if (signal_print_state (sig))
4141         gdb::observers::signal_received.notify (sig);
4142     }
4143   gdb::observers::normal_stop.notify (NULL, 1);
4144 }
4145
4146 /* Process all initial stop replies the remote side sent in response
4147    to the ? packet.  These indicate threads that were already stopped
4148    on initial connection.  We mark these threads as stopped and print
4149    their current frame before giving the user the prompt.  */
4150
4151 static void
4152 process_initial_stop_replies (int from_tty)
4153 {
4154   int pending_stop_replies = stop_reply_queue_length ();
4155   struct inferior *inf;
4156   struct thread_info *thread;
4157   struct thread_info *selected = NULL;
4158   struct thread_info *lowest_stopped = NULL;
4159   struct thread_info *first = NULL;
4160
4161   /* Consume the initial pending events.  */
4162   while (pending_stop_replies-- > 0)
4163     {
4164       ptid_t waiton_ptid = minus_one_ptid;
4165       ptid_t event_ptid;
4166       struct target_waitstatus ws;
4167       int ignore_event = 0;
4168       struct thread_info *thread;
4169
4170       memset (&ws, 0, sizeof (ws));
4171       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4172       if (remote_debug)
4173         print_target_wait_results (waiton_ptid, event_ptid, &ws);
4174
4175       switch (ws.kind)
4176         {
4177         case TARGET_WAITKIND_IGNORE:
4178         case TARGET_WAITKIND_NO_RESUMED:
4179         case TARGET_WAITKIND_SIGNALLED:
4180         case TARGET_WAITKIND_EXITED:
4181           /* We shouldn't see these, but if we do, just ignore.  */
4182           if (remote_debug)
4183             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4184           ignore_event = 1;
4185           break;
4186
4187         case TARGET_WAITKIND_EXECD:
4188           xfree (ws.value.execd_pathname);
4189           break;
4190         default:
4191           break;
4192         }
4193
4194       if (ignore_event)
4195         continue;
4196
4197       thread = find_thread_ptid (event_ptid);
4198
4199       if (ws.kind == TARGET_WAITKIND_STOPPED)
4200         {
4201           enum gdb_signal sig = ws.value.sig;
4202
4203           /* Stubs traditionally report SIGTRAP as initial signal,
4204              instead of signal 0.  Suppress it.  */
4205           if (sig == GDB_SIGNAL_TRAP)
4206             sig = GDB_SIGNAL_0;
4207           thread->suspend.stop_signal = sig;
4208           ws.value.sig = sig;
4209         }
4210
4211       thread->suspend.waitstatus = ws;
4212
4213       if (ws.kind != TARGET_WAITKIND_STOPPED
4214           || ws.value.sig != GDB_SIGNAL_0)
4215         thread->suspend.waitstatus_pending_p = 1;
4216
4217       set_executing (event_ptid, 0);
4218       set_running (event_ptid, 0);
4219       get_remote_thread_info (thread)->vcont_resumed = 0;
4220     }
4221
4222   /* "Notice" the new inferiors before anything related to
4223      registers/memory.  */
4224   ALL_INFERIORS (inf)
4225     {
4226       if (inf->pid == 0)
4227         continue;
4228
4229       inf->needs_setup = 1;
4230
4231       if (non_stop)
4232         {
4233           thread = any_live_thread_of_process (inf->pid);
4234           notice_new_inferior (thread->ptid,
4235                                thread->state == THREAD_RUNNING,
4236                                from_tty);
4237         }
4238     }
4239
4240   /* If all-stop on top of non-stop, pause all threads.  Note this
4241      records the threads' stop pc, so must be done after "noticing"
4242      the inferiors.  */
4243   if (!non_stop)
4244     {
4245       stop_all_threads ();
4246
4247       /* If all threads of an inferior were already stopped, we
4248          haven't setup the inferior yet.  */
4249       ALL_INFERIORS (inf)
4250         {
4251           if (inf->pid == 0)
4252             continue;
4253
4254           if (inf->needs_setup)
4255             {
4256               thread = any_live_thread_of_process (inf->pid);
4257               switch_to_thread_no_regs (thread);
4258               setup_inferior (0);
4259             }
4260         }
4261     }
4262
4263   /* Now go over all threads that are stopped, and print their current
4264      frame.  If all-stop, then if there's a signalled thread, pick
4265      that as current.  */
4266   ALL_NON_EXITED_THREADS (thread)
4267     {
4268       if (first == NULL)
4269         first = thread;
4270
4271       if (!non_stop)
4272         set_running (thread->ptid, 0);
4273       else if (thread->state != THREAD_STOPPED)
4274         continue;
4275
4276       if (selected == NULL
4277           && thread->suspend.waitstatus_pending_p)
4278         selected = thread;
4279
4280       if (lowest_stopped == NULL
4281           || thread->inf->num < lowest_stopped->inf->num
4282           || thread->per_inf_num < lowest_stopped->per_inf_num)
4283         lowest_stopped = thread;
4284
4285       if (non_stop)
4286         print_one_stopped_thread (thread);
4287     }
4288
4289   /* In all-stop, we only print the status of one thread, and leave
4290      others with their status pending.  */
4291   if (!non_stop)
4292     {
4293       thread = selected;
4294       if (thread == NULL)
4295         thread = lowest_stopped;
4296       if (thread == NULL)
4297         thread = first;
4298
4299       print_one_stopped_thread (thread);
4300     }
4301
4302   /* For "info program".  */
4303   thread = inferior_thread ();
4304   if (thread->state == THREAD_STOPPED)
4305     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4306 }
4307
4308 /* Start the remote connection and sync state.  */
4309
4310 void
4311 remote_target::start_remote (int from_tty, int extended_p)
4312 {
4313   struct remote_state *rs = get_remote_state ();
4314   struct packet_config *noack_config;
4315   char *wait_status = NULL;
4316
4317   /* Signal other parts that we're going through the initial setup,
4318      and so things may not be stable yet.  E.g., we don't try to
4319      install tracepoints until we've relocated symbols.  Also, a
4320      Ctrl-C before we're connected and synced up can't interrupt the
4321      target.  Instead, it offers to drop the (potentially wedged)
4322      connection.  */
4323   rs->starting_up = 1;
4324
4325   QUIT;
4326
4327   if (interrupt_on_connect)
4328     send_interrupt_sequence ();
4329
4330   /* Ack any packet which the remote side has already sent.  */
4331   remote_serial_write ("+", 1);
4332
4333   /* The first packet we send to the target is the optional "supported
4334      packets" request.  If the target can answer this, it will tell us
4335      which later probes to skip.  */
4336   remote_query_supported ();
4337
4338   /* If the stub wants to get a QAllow, compose one and send it.  */
4339   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4340     set_permissions ();
4341
4342   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4343      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
4344      as a reply to known packet.  For packet "vFile:setfs:" it is an
4345      invalid reply and GDB would return error in
4346      remote_hostio_set_filesystem, making remote files access impossible.
4347      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
4348      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
4349   {
4350     const char v_mustreplyempty[] = "vMustReplyEmpty";
4351
4352     putpkt (v_mustreplyempty);
4353     getpkt (&rs->buf, &rs->buf_size, 0);
4354     if (strcmp (rs->buf, "OK") == 0)
4355       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4356     else if (strcmp (rs->buf, "") != 0)
4357       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4358              rs->buf);
4359   }
4360
4361   /* Next, we possibly activate noack mode.
4362
4363      If the QStartNoAckMode packet configuration is set to AUTO,
4364      enable noack mode if the stub reported a wish for it with
4365      qSupported.
4366
4367      If set to TRUE, then enable noack mode even if the stub didn't
4368      report it in qSupported.  If the stub doesn't reply OK, the
4369      session ends with an error.
4370
4371      If FALSE, then don't activate noack mode, regardless of what the
4372      stub claimed should be the default with qSupported.  */
4373
4374   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4375   if (packet_config_support (noack_config) != PACKET_DISABLE)
4376     {
4377       putpkt ("QStartNoAckMode");
4378       getpkt (&rs->buf, &rs->buf_size, 0);
4379       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4380         rs->noack_mode = 1;
4381     }
4382
4383   if (extended_p)
4384     {
4385       /* Tell the remote that we are using the extended protocol.  */
4386       putpkt ("!");
4387       getpkt (&rs->buf, &rs->buf_size, 0);
4388     }
4389
4390   /* Let the target know which signals it is allowed to pass down to
4391      the program.  */
4392   update_signals_program_target ();
4393
4394   /* Next, if the target can specify a description, read it.  We do
4395      this before anything involving memory or registers.  */
4396   target_find_description ();
4397
4398   /* Next, now that we know something about the target, update the
4399      address spaces in the program spaces.  */
4400   update_address_spaces ();
4401
4402   /* On OSs where the list of libraries is global to all
4403      processes, we fetch them early.  */
4404   if (gdbarch_has_global_solist (target_gdbarch ()))
4405     solib_add (NULL, from_tty, auto_solib_add);
4406
4407   if (target_is_non_stop_p ())
4408     {
4409       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4410         error (_("Non-stop mode requested, but remote "
4411                  "does not support non-stop"));
4412
4413       putpkt ("QNonStop:1");
4414       getpkt (&rs->buf, &rs->buf_size, 0);
4415
4416       if (strcmp (rs->buf, "OK") != 0)
4417         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4418
4419       /* Find about threads and processes the stub is already
4420          controlling.  We default to adding them in the running state.
4421          The '?' query below will then tell us about which threads are
4422          stopped.  */
4423       this->update_thread_list ();
4424     }
4425   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4426     {
4427       /* Don't assume that the stub can operate in all-stop mode.
4428          Request it explicitly.  */
4429       putpkt ("QNonStop:0");
4430       getpkt (&rs->buf, &rs->buf_size, 0);
4431
4432       if (strcmp (rs->buf, "OK") != 0)
4433         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4434     }
4435
4436   /* Upload TSVs regardless of whether the target is running or not.  The
4437      remote stub, such as GDBserver, may have some predefined or builtin
4438      TSVs, even if the target is not running.  */
4439   if (get_trace_status (current_trace_status ()) != -1)
4440     {
4441       struct uploaded_tsv *uploaded_tsvs = NULL;
4442
4443       upload_trace_state_variables (&uploaded_tsvs);
4444       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4445     }
4446
4447   /* Check whether the target is running now.  */
4448   putpkt ("?");
4449   getpkt (&rs->buf, &rs->buf_size, 0);
4450
4451   if (!target_is_non_stop_p ())
4452     {
4453       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4454         {
4455           if (!extended_p)
4456             error (_("The target is not running (try extended-remote?)"));
4457
4458           /* We're connected, but not running.  Drop out before we
4459              call start_remote.  */
4460           rs->starting_up = 0;
4461           return;
4462         }
4463       else
4464         {
4465           /* Save the reply for later.  */
4466           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4467           strcpy (wait_status, rs->buf);
4468         }
4469
4470       /* Fetch thread list.  */
4471       target_update_thread_list ();
4472
4473       /* Let the stub know that we want it to return the thread.  */
4474       set_continue_thread (minus_one_ptid);
4475
4476       if (thread_count () == 0)
4477         {
4478           /* Target has no concept of threads at all.  GDB treats
4479              non-threaded target as single-threaded; add a main
4480              thread.  */
4481           add_current_inferior_and_thread (wait_status);
4482         }
4483       else
4484         {
4485           /* We have thread information; select the thread the target
4486              says should be current.  If we're reconnecting to a
4487              multi-threaded program, this will ideally be the thread
4488              that last reported an event before GDB disconnected.  */
4489           inferior_ptid = get_current_thread (wait_status);
4490           if (ptid_equal (inferior_ptid, null_ptid))
4491             {
4492               /* Odd... The target was able to list threads, but not
4493                  tell us which thread was current (no "thread"
4494                  register in T stop reply?).  Just pick the first
4495                  thread in the thread list then.  */
4496               
4497               if (remote_debug)
4498                 fprintf_unfiltered (gdb_stdlog,
4499                                     "warning: couldn't determine remote "
4500                                     "current thread; picking first in list.\n");
4501
4502               inferior_ptid = thread_list->ptid;
4503             }
4504         }
4505
4506       /* init_wait_for_inferior should be called before get_offsets in order
4507          to manage `inserted' flag in bp loc in a correct state.
4508          breakpoint_init_inferior, called from init_wait_for_inferior, set
4509          `inserted' flag to 0, while before breakpoint_re_set, called from
4510          start_remote, set `inserted' flag to 1.  In the initialization of
4511          inferior, breakpoint_init_inferior should be called first, and then
4512          breakpoint_re_set can be called.  If this order is broken, state of
4513          `inserted' flag is wrong, and cause some problems on breakpoint
4514          manipulation.  */
4515       init_wait_for_inferior ();
4516
4517       get_offsets ();           /* Get text, data & bss offsets.  */
4518
4519       /* If we could not find a description using qXfer, and we know
4520          how to do it some other way, try again.  This is not
4521          supported for non-stop; it could be, but it is tricky if
4522          there are no stopped threads when we connect.  */
4523       if (remote_read_description_p (this)
4524           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4525         {
4526           target_clear_description ();
4527           target_find_description ();
4528         }
4529
4530       /* Use the previously fetched status.  */
4531       gdb_assert (wait_status != NULL);
4532       strcpy (rs->buf, wait_status);
4533       rs->cached_wait_status = 1;
4534
4535       ::start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4536     }
4537   else
4538     {
4539       /* Clear WFI global state.  Do this before finding about new
4540          threads and inferiors, and setting the current inferior.
4541          Otherwise we would clear the proceed status of the current
4542          inferior when we want its stop_soon state to be preserved
4543          (see notice_new_inferior).  */
4544       init_wait_for_inferior ();
4545
4546       /* In non-stop, we will either get an "OK", meaning that there
4547          are no stopped threads at this time; or, a regular stop
4548          reply.  In the latter case, there may be more than one thread
4549          stopped --- we pull them all out using the vStopped
4550          mechanism.  */
4551       if (strcmp (rs->buf, "OK") != 0)
4552         {
4553           struct notif_client *notif = &notif_client_stop;
4554
4555           /* remote_notif_get_pending_replies acks this one, and gets
4556              the rest out.  */
4557           rs->notif_state->pending_event[notif_client_stop.id]
4558             = remote_notif_parse (notif, rs->buf);
4559           remote_notif_get_pending_events (notif);
4560         }
4561
4562       if (thread_count () == 0)
4563         {
4564           if (!extended_p)
4565             error (_("The target is not running (try extended-remote?)"));
4566
4567           /* We're connected, but not running.  Drop out before we
4568              call start_remote.  */
4569           rs->starting_up = 0;
4570           return;
4571         }
4572
4573       /* In non-stop mode, any cached wait status will be stored in
4574          the stop reply queue.  */
4575       gdb_assert (wait_status == NULL);
4576
4577       /* Report all signals during attach/startup.  */
4578       pass_signals (0, NULL);
4579
4580       /* If there are already stopped threads, mark them stopped and
4581          report their stops before giving the prompt to the user.  */
4582       process_initial_stop_replies (from_tty);
4583
4584       if (target_can_async_p ())
4585         target_async (1);
4586     }
4587
4588   /* If we connected to a live target, do some additional setup.  */
4589   if (target_has_execution)
4590     {
4591       if (symfile_objfile)      /* No use without a symbol-file.  */
4592         remote_check_symbols ();
4593     }
4594
4595   /* Possibly the target has been engaged in a trace run started
4596      previously; find out where things are at.  */
4597   if (get_trace_status (current_trace_status ()) != -1)
4598     {
4599       struct uploaded_tp *uploaded_tps = NULL;
4600
4601       if (current_trace_status ()->running)
4602         printf_filtered (_("Trace is already running on the target.\n"));
4603
4604       upload_tracepoints (&uploaded_tps);
4605
4606       merge_uploaded_tracepoints (&uploaded_tps);
4607     }
4608
4609   /* Possibly the target has been engaged in a btrace record started
4610      previously; find out where things are at.  */
4611   remote_btrace_maybe_reopen ();
4612
4613   /* The thread and inferior lists are now synchronized with the
4614      target, our symbols have been relocated, and we're merged the
4615      target's tracepoints with ours.  We're done with basic start
4616      up.  */
4617   rs->starting_up = 0;
4618
4619   /* Maybe breakpoints are global and need to be inserted now.  */
4620   if (breakpoints_should_be_inserted_now ())
4621     insert_breakpoints ();
4622 }
4623
4624 /* Open a connection to a remote debugger.
4625    NAME is the filename used for communication.  */
4626
4627 void
4628 remote_target::open (const char *name, int from_tty)
4629 {
4630   open_1 (name, from_tty, 0);
4631 }
4632
4633 /* Open a connection to a remote debugger using the extended
4634    remote gdb protocol.  NAME is the filename used for communication.  */
4635
4636 void
4637 extended_remote_target::open (const char *name, int from_tty)
4638 {
4639   open_1 (name, from_tty, 1 /*extended_p */);
4640 }
4641
4642 /* Reset all packets back to "unknown support".  Called when opening a
4643    new connection to a remote target.  */
4644
4645 static void
4646 reset_all_packet_configs_support (void)
4647 {
4648   int i;
4649
4650   for (i = 0; i < PACKET_MAX; i++)
4651     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4652 }
4653
4654 /* Initialize all packet configs.  */
4655
4656 static void
4657 init_all_packet_configs (void)
4658 {
4659   int i;
4660
4661   for (i = 0; i < PACKET_MAX; i++)
4662     {
4663       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4664       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4665     }
4666 }
4667
4668 /* Symbol look-up.  */
4669
4670 static void
4671 remote_check_symbols (void)
4672 {
4673   char *msg, *reply, *tmp;
4674   int end;
4675   long reply_size;
4676   struct cleanup *old_chain;
4677
4678   /* The remote side has no concept of inferiors that aren't running
4679      yet, it only knows about running processes.  If we're connected
4680      but our current inferior is not running, we should not invite the
4681      remote target to request symbol lookups related to its
4682      (unrelated) current process.  */
4683   if (!target_has_execution)
4684     return;
4685
4686   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4687     return;
4688
4689   /* Make sure the remote is pointing at the right process.  Note
4690      there's no way to select "no process".  */
4691   set_general_process ();
4692
4693   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4694      because we need both at the same time.  */
4695   msg = (char *) xmalloc (get_remote_packet_size ());
4696   old_chain = make_cleanup (xfree, msg);
4697   reply = (char *) xmalloc (get_remote_packet_size ());
4698   make_cleanup (free_current_contents, &reply);
4699   reply_size = get_remote_packet_size ();
4700
4701   /* Invite target to request symbol lookups.  */
4702
4703   putpkt ("qSymbol::");
4704   getpkt (&reply, &reply_size, 0);
4705   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4706
4707   while (startswith (reply, "qSymbol:"))
4708     {
4709       struct bound_minimal_symbol sym;
4710
4711       tmp = &reply[8];
4712       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4713       msg[end] = '\0';
4714       sym = lookup_minimal_symbol (msg, NULL, NULL);
4715       if (sym.minsym == NULL)
4716         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4717       else
4718         {
4719           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4720           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4721
4722           /* If this is a function address, return the start of code
4723              instead of any data function descriptor.  */
4724           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4725                                                          sym_addr,
4726                                                          target_stack);
4727
4728           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4729                      phex_nz (sym_addr, addr_size), &reply[8]);
4730         }
4731   
4732       putpkt (msg);
4733       getpkt (&reply, &reply_size, 0);
4734     }
4735
4736   do_cleanups (old_chain);
4737 }
4738
4739 static struct serial *
4740 remote_serial_open (const char *name)
4741 {
4742   static int udp_warning = 0;
4743
4744   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4745      of in ser-tcp.c, because it is the remote protocol assuming that the
4746      serial connection is reliable and not the serial connection promising
4747      to be.  */
4748   if (!udp_warning && startswith (name, "udp:"))
4749     {
4750       warning (_("The remote protocol may be unreliable over UDP.\n"
4751                  "Some events may be lost, rendering further debugging "
4752                  "impossible."));
4753       udp_warning = 1;
4754     }
4755
4756   return serial_open (name);
4757 }
4758
4759 /* Inform the target of our permission settings.  The permission flags
4760    work without this, but if the target knows the settings, it can do
4761    a couple things.  First, it can add its own check, to catch cases
4762    that somehow manage to get by the permissions checks in target
4763    methods.  Second, if the target is wired to disallow particular
4764    settings (for instance, a system in the field that is not set up to
4765    be able to stop at a breakpoint), it can object to any unavailable
4766    permissions.  */
4767
4768 void
4769 remote_target::set_permissions ()
4770 {
4771   struct remote_state *rs = get_remote_state ();
4772
4773   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4774              "WriteReg:%x;WriteMem:%x;"
4775              "InsertBreak:%x;InsertTrace:%x;"
4776              "InsertFastTrace:%x;Stop:%x",
4777              may_write_registers, may_write_memory,
4778              may_insert_breakpoints, may_insert_tracepoints,
4779              may_insert_fast_tracepoints, may_stop);
4780   putpkt (rs->buf);
4781   getpkt (&rs->buf, &rs->buf_size, 0);
4782
4783   /* If the target didn't like the packet, warn the user.  Do not try
4784      to undo the user's settings, that would just be maddening.  */
4785   if (strcmp (rs->buf, "OK") != 0)
4786     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4787 }
4788
4789 /* This type describes each known response to the qSupported
4790    packet.  */
4791 struct protocol_feature
4792 {
4793   /* The name of this protocol feature.  */
4794   const char *name;
4795
4796   /* The default for this protocol feature.  */
4797   enum packet_support default_support;
4798
4799   /* The function to call when this feature is reported, or after
4800      qSupported processing if the feature is not supported.
4801      The first argument points to this structure.  The second
4802      argument indicates whether the packet requested support be
4803      enabled, disabled, or probed (or the default, if this function
4804      is being called at the end of processing and this feature was
4805      not reported).  The third argument may be NULL; if not NULL, it
4806      is a NUL-terminated string taken from the packet following
4807      this feature's name and an equals sign.  */
4808   void (*func) (const struct protocol_feature *, enum packet_support,
4809                 const char *);
4810
4811   /* The corresponding packet for this feature.  Only used if
4812      FUNC is remote_supported_packet.  */
4813   int packet;
4814 };
4815
4816 static void
4817 remote_supported_packet (const struct protocol_feature *feature,
4818                          enum packet_support support,
4819                          const char *argument)
4820 {
4821   if (argument)
4822     {
4823       warning (_("Remote qSupported response supplied an unexpected value for"
4824                  " \"%s\"."), feature->name);
4825       return;
4826     }
4827
4828   remote_protocol_packets[feature->packet].support = support;
4829 }
4830
4831 static void
4832 remote_packet_size (const struct protocol_feature *feature,
4833                     enum packet_support support, const char *value)
4834 {
4835   struct remote_state *rs = get_remote_state ();
4836
4837   int packet_size;
4838   char *value_end;
4839
4840   if (support != PACKET_ENABLE)
4841     return;
4842
4843   if (value == NULL || *value == '\0')
4844     {
4845       warning (_("Remote target reported \"%s\" without a size."),
4846                feature->name);
4847       return;
4848     }
4849
4850   errno = 0;
4851   packet_size = strtol (value, &value_end, 16);
4852   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4853     {
4854       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4855                feature->name, value);
4856       return;
4857     }
4858
4859   /* Record the new maximum packet size.  */
4860   rs->explicit_packet_size = packet_size;
4861 }
4862
4863 static const struct protocol_feature remote_protocol_features[] = {
4864   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4865   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4866     PACKET_qXfer_auxv },
4867   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4868     PACKET_qXfer_exec_file },
4869   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4870     PACKET_qXfer_features },
4871   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4872     PACKET_qXfer_libraries },
4873   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4874     PACKET_qXfer_libraries_svr4 },
4875   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4876     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4877   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4878     PACKET_qXfer_memory_map },
4879   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4880     PACKET_qXfer_spu_read },
4881   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4882     PACKET_qXfer_spu_write },
4883   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4884     PACKET_qXfer_osdata },
4885   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4886     PACKET_qXfer_threads },
4887   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4888     PACKET_qXfer_traceframe_info },
4889   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4890     PACKET_QPassSignals },
4891   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4892     PACKET_QCatchSyscalls },
4893   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4894     PACKET_QProgramSignals },
4895   { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4896     PACKET_QSetWorkingDir },
4897   { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4898     PACKET_QStartupWithShell },
4899   { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4900     PACKET_QEnvironmentHexEncoded },
4901   { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4902     PACKET_QEnvironmentReset },
4903   { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4904     PACKET_QEnvironmentUnset },
4905   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4906     PACKET_QStartNoAckMode },
4907   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4908     PACKET_multiprocess_feature },
4909   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4910   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4911     PACKET_qXfer_siginfo_read },
4912   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4913     PACKET_qXfer_siginfo_write },
4914   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4915     PACKET_ConditionalTracepoints },
4916   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4917     PACKET_ConditionalBreakpoints },
4918   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4919     PACKET_BreakpointCommands },
4920   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4921     PACKET_FastTracepoints },
4922   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4923     PACKET_StaticTracepoints },
4924   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4925    PACKET_InstallInTrace},
4926   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4927     PACKET_DisconnectedTracing_feature },
4928   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4929     PACKET_bc },
4930   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4931     PACKET_bs },
4932   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4933     PACKET_TracepointSource },
4934   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4935     PACKET_QAllow },
4936   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4937     PACKET_EnableDisableTracepoints_feature },
4938   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4939     PACKET_qXfer_fdpic },
4940   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4941     PACKET_qXfer_uib },
4942   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4943     PACKET_QDisableRandomization },
4944   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4945   { "QTBuffer:size", PACKET_DISABLE,
4946     remote_supported_packet, PACKET_QTBuffer_size},
4947   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4948   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4949   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4950   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4951   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4952     PACKET_qXfer_btrace },
4953   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4954     PACKET_qXfer_btrace_conf },
4955   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4956     PACKET_Qbtrace_conf_bts_size },
4957   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4958   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4959   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4960     PACKET_fork_event_feature },
4961   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4962     PACKET_vfork_event_feature },
4963   { "exec-events", PACKET_DISABLE, remote_supported_packet,
4964     PACKET_exec_event_feature },
4965   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4966     PACKET_Qbtrace_conf_pt_size },
4967   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4968   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4969   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4970 };
4971
4972 static char *remote_support_xml;
4973
4974 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4975
4976 void
4977 register_remote_support_xml (const char *xml)
4978 {
4979 #if defined(HAVE_LIBEXPAT)
4980   if (remote_support_xml == NULL)
4981     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4982   else
4983     {
4984       char *copy = xstrdup (remote_support_xml + 13);
4985       char *p = strtok (copy, ",");
4986
4987       do
4988         {
4989           if (strcmp (p, xml) == 0)
4990             {
4991               /* already there */
4992               xfree (copy);
4993               return;
4994             }
4995         }
4996       while ((p = strtok (NULL, ",")) != NULL);
4997       xfree (copy);
4998
4999       remote_support_xml = reconcat (remote_support_xml,
5000                                      remote_support_xml, ",", xml,
5001                                      (char *) NULL);
5002     }
5003 #endif
5004 }
5005
5006 static void
5007 remote_query_supported_append (std::string *msg, const char *append)
5008 {
5009   if (!msg->empty ())
5010     msg->append (";");
5011   msg->append (append);
5012 }
5013
5014 static void
5015 remote_query_supported (void)
5016 {
5017   struct remote_state *rs = get_remote_state ();
5018   char *next;
5019   int i;
5020   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5021
5022   /* The packet support flags are handled differently for this packet
5023      than for most others.  We treat an error, a disabled packet, and
5024      an empty response identically: any features which must be reported
5025      to be used will be automatically disabled.  An empty buffer
5026      accomplishes this, since that is also the representation for a list
5027      containing no features.  */
5028
5029   rs->buf[0] = 0;
5030   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5031     {
5032       std::string q;
5033
5034       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5035         remote_query_supported_append (&q, "multiprocess+");
5036
5037       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5038         remote_query_supported_append (&q, "swbreak+");
5039       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5040         remote_query_supported_append (&q, "hwbreak+");
5041
5042       remote_query_supported_append (&q, "qRelocInsn+");
5043
5044       if (packet_set_cmd_state (PACKET_fork_event_feature)
5045           != AUTO_BOOLEAN_FALSE)
5046         remote_query_supported_append (&q, "fork-events+");
5047       if (packet_set_cmd_state (PACKET_vfork_event_feature)
5048           != AUTO_BOOLEAN_FALSE)
5049         remote_query_supported_append (&q, "vfork-events+");
5050       if (packet_set_cmd_state (PACKET_exec_event_feature)
5051           != AUTO_BOOLEAN_FALSE)
5052         remote_query_supported_append (&q, "exec-events+");
5053
5054       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5055         remote_query_supported_append (&q, "vContSupported+");
5056
5057       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5058         remote_query_supported_append (&q, "QThreadEvents+");
5059
5060       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5061         remote_query_supported_append (&q, "no-resumed+");
5062
5063       /* Keep this one last to work around a gdbserver <= 7.10 bug in
5064          the qSupported:xmlRegisters=i386 handling.  */
5065       if (remote_support_xml != NULL
5066           && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5067         remote_query_supported_append (&q, remote_support_xml);
5068
5069       q = "qSupported:" + q;
5070       putpkt (q.c_str ());
5071
5072       getpkt (&rs->buf, &rs->buf_size, 0);
5073
5074       /* If an error occured, warn, but do not return - just reset the
5075          buffer to empty and go on to disable features.  */
5076       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5077           == PACKET_ERROR)
5078         {
5079           warning (_("Remote failure reply: %s"), rs->buf);
5080           rs->buf[0] = 0;
5081         }
5082     }
5083
5084   memset (seen, 0, sizeof (seen));
5085
5086   next = rs->buf;
5087   while (*next)
5088     {
5089       enum packet_support is_supported;
5090       char *p, *end, *name_end, *value;
5091
5092       /* First separate out this item from the rest of the packet.  If
5093          there's another item after this, we overwrite the separator
5094          (terminated strings are much easier to work with).  */
5095       p = next;
5096       end = strchr (p, ';');
5097       if (end == NULL)
5098         {
5099           end = p + strlen (p);
5100           next = end;
5101         }
5102       else
5103         {
5104           *end = '\0';
5105           next = end + 1;
5106
5107           if (end == p)
5108             {
5109               warning (_("empty item in \"qSupported\" response"));
5110               continue;
5111             }
5112         }
5113
5114       name_end = strchr (p, '=');
5115       if (name_end)
5116         {
5117           /* This is a name=value entry.  */
5118           is_supported = PACKET_ENABLE;
5119           value = name_end + 1;
5120           *name_end = '\0';
5121         }
5122       else
5123         {
5124           value = NULL;
5125           switch (end[-1])
5126             {
5127             case '+':
5128               is_supported = PACKET_ENABLE;
5129               break;
5130
5131             case '-':
5132               is_supported = PACKET_DISABLE;
5133               break;
5134
5135             case '?':
5136               is_supported = PACKET_SUPPORT_UNKNOWN;
5137               break;
5138
5139             default:
5140               warning (_("unrecognized item \"%s\" "
5141                          "in \"qSupported\" response"), p);
5142               continue;
5143             }
5144           end[-1] = '\0';
5145         }
5146
5147       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5148         if (strcmp (remote_protocol_features[i].name, p) == 0)
5149           {
5150             const struct protocol_feature *feature;
5151
5152             seen[i] = 1;
5153             feature = &remote_protocol_features[i];
5154             feature->func (feature, is_supported, value);
5155             break;
5156           }
5157     }
5158
5159   /* If we increased the packet size, make sure to increase the global
5160      buffer size also.  We delay this until after parsing the entire
5161      qSupported packet, because this is the same buffer we were
5162      parsing.  */
5163   if (rs->buf_size < rs->explicit_packet_size)
5164     {
5165       rs->buf_size = rs->explicit_packet_size;
5166       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5167     }
5168
5169   /* Handle the defaults for unmentioned features.  */
5170   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5171     if (!seen[i])
5172       {
5173         const struct protocol_feature *feature;
5174
5175         feature = &remote_protocol_features[i];
5176         feature->func (feature, feature->default_support, NULL);
5177       }
5178 }
5179
5180 /* Serial QUIT handler for the remote serial descriptor.
5181
5182    Defers handling a Ctrl-C until we're done with the current
5183    command/response packet sequence, unless:
5184
5185    - We're setting up the connection.  Don't send a remote interrupt
5186      request, as we're not fully synced yet.  Quit immediately
5187      instead.
5188
5189    - The target has been resumed in the foreground
5190      (target_terminal::is_ours is false) with a synchronous resume
5191      packet, and we're blocked waiting for the stop reply, thus a
5192      Ctrl-C should be immediately sent to the target.
5193
5194    - We get a second Ctrl-C while still within the same serial read or
5195      write.  In that case the serial is seemingly wedged --- offer to
5196      quit/disconnect.
5197
5198    - We see a second Ctrl-C without target response, after having
5199      previously interrupted the target.  In that case the target/stub
5200      is probably wedged --- offer to quit/disconnect.
5201 */
5202
5203 static void
5204 remote_serial_quit_handler (void)
5205 {
5206   struct remote_state *rs = get_remote_state ();
5207
5208   if (check_quit_flag ())
5209     {
5210       /* If we're starting up, we're not fully synced yet.  Quit
5211          immediately.  */
5212       if (rs->starting_up)
5213         quit ();
5214       else if (rs->got_ctrlc_during_io)
5215         {
5216           if (query (_("The target is not responding to GDB commands.\n"
5217                        "Stop debugging it? ")))
5218             remote_unpush_and_throw ();
5219         }
5220       /* If ^C has already been sent once, offer to disconnect.  */
5221       else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5222         interrupt_query ();
5223       /* All-stop protocol, and blocked waiting for stop reply.  Send
5224          an interrupt request.  */
5225       else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5226         target_interrupt ();
5227       else
5228         rs->got_ctrlc_during_io = 1;
5229     }
5230 }
5231
5232 /* Remove any of the remote.c targets from target stack.  Upper targets depend
5233    on it so remove them first.  */
5234
5235 static void
5236 remote_unpush_target (void)
5237 {
5238   pop_all_targets_at_and_above (process_stratum);
5239 }
5240
5241 static void
5242 remote_unpush_and_throw (void)
5243 {
5244   remote_unpush_target ();
5245   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5246 }
5247
5248 void
5249 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5250 {
5251   struct remote_state *rs = get_remote_state ();
5252
5253   if (name == 0)
5254     error (_("To open a remote debug connection, you need to specify what\n"
5255            "serial device is attached to the remote system\n"
5256            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5257
5258   /* See FIXME above.  */
5259   if (!target_async_permitted)
5260     wait_forever_enabled_p = 1;
5261
5262   /* If we're connected to a running target, target_preopen will kill it.
5263      Ask this question first, before target_preopen has a chance to kill
5264      anything.  */
5265   if (rs->remote_desc != NULL && !have_inferiors ())
5266     {
5267       if (from_tty
5268           && !query (_("Already connected to a remote target.  Disconnect? ")))
5269         error (_("Still connected."));
5270     }
5271
5272   /* Here the possibly existing remote target gets unpushed.  */
5273   target_preopen (from_tty);
5274
5275   /* Make sure we send the passed signals list the next time we resume.  */
5276   xfree (rs->last_pass_packet);
5277   rs->last_pass_packet = NULL;
5278
5279   /* Make sure we send the program signals list the next time we
5280      resume.  */
5281   xfree (rs->last_program_signals_packet);
5282   rs->last_program_signals_packet = NULL;
5283
5284   remote_fileio_reset ();
5285   reopen_exec_file ();
5286   reread_symbols ();
5287
5288   rs->remote_desc = remote_serial_open (name);
5289   if (!rs->remote_desc)
5290     perror_with_name (name);
5291
5292   if (baud_rate != -1)
5293     {
5294       if (serial_setbaudrate (rs->remote_desc, baud_rate))
5295         {
5296           /* The requested speed could not be set.  Error out to
5297              top level after closing remote_desc.  Take care to
5298              set remote_desc to NULL to avoid closing remote_desc
5299              more than once.  */
5300           serial_close (rs->remote_desc);
5301           rs->remote_desc = NULL;
5302           perror_with_name (name);
5303         }
5304     }
5305
5306   serial_setparity (rs->remote_desc, serial_parity);
5307   serial_raw (rs->remote_desc);
5308
5309   /* If there is something sitting in the buffer we might take it as a
5310      response to a command, which would be bad.  */
5311   serial_flush_input (rs->remote_desc);
5312
5313   if (from_tty)
5314     {
5315       puts_filtered ("Remote debugging using ");
5316       puts_filtered (name);
5317       puts_filtered ("\n");
5318     }
5319
5320   remote_target *target
5321     = extended_p ? &extended_remote_ops : &remote_ops;
5322   push_target (target);         /* Switch to using remote target now.  */
5323
5324   /* Register extra event sources in the event loop.  */
5325   remote_async_inferior_event_token
5326     = create_async_event_handler (remote_async_inferior_event_handler,
5327                                   NULL);
5328   rs->notif_state = remote_notif_state_allocate ();
5329
5330   /* Reset the target state; these things will be queried either by
5331      remote_query_supported or as they are needed.  */
5332   reset_all_packet_configs_support ();
5333   rs->cached_wait_status = 0;
5334   rs->explicit_packet_size = 0;
5335   rs->noack_mode = 0;
5336   rs->extended = extended_p;
5337   rs->waiting_for_stop_reply = 0;
5338   rs->ctrlc_pending_p = 0;
5339   rs->got_ctrlc_during_io = 0;
5340
5341   rs->general_thread = not_sent_ptid;
5342   rs->continue_thread = not_sent_ptid;
5343   rs->remote_traceframe_number = -1;
5344
5345   rs->last_resume_exec_dir = EXEC_FORWARD;
5346
5347   /* Probe for ability to use "ThreadInfo" query, as required.  */
5348   rs->use_threadinfo_query = 1;
5349   rs->use_threadextra_query = 1;
5350
5351   rs->readahead_cache.invalidate ();
5352
5353   if (target_async_permitted)
5354     {
5355       /* FIXME: cagney/1999-09-23: During the initial connection it is
5356          assumed that the target is already ready and able to respond to
5357          requests.  Unfortunately remote_start_remote() eventually calls
5358          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
5359          around this.  Eventually a mechanism that allows
5360          wait_for_inferior() to expect/get timeouts will be
5361          implemented.  */
5362       wait_forever_enabled_p = 0;
5363     }
5364
5365   /* First delete any symbols previously loaded from shared libraries.  */
5366   no_shared_libraries (NULL, 0);
5367
5368   /* Start afresh.  */
5369   init_thread_list ();
5370
5371   /* Start the remote connection.  If error() or QUIT, discard this
5372      target (we'd otherwise be in an inconsistent state) and then
5373      propogate the error on up the exception chain.  This ensures that
5374      the caller doesn't stumble along blindly assuming that the
5375      function succeeded.  The CLI doesn't have this problem but other
5376      UI's, such as MI do.
5377
5378      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5379      this function should return an error indication letting the
5380      caller restore the previous state.  Unfortunately the command
5381      ``target remote'' is directly wired to this function making that
5382      impossible.  On a positive note, the CLI side of this problem has
5383      been fixed - the function set_cmd_context() makes it possible for
5384      all the ``target ....'' commands to share a common callback
5385      function.  See cli-dump.c.  */
5386   {
5387
5388     TRY
5389       {
5390         target->start_remote (from_tty, extended_p);
5391       }
5392     CATCH (ex, RETURN_MASK_ALL)
5393       {
5394         /* Pop the partially set up target - unless something else did
5395            already before throwing the exception.  */
5396         if (rs->remote_desc != NULL)
5397           remote_unpush_target ();
5398         if (target_async_permitted)
5399           wait_forever_enabled_p = 1;
5400         throw_exception (ex);
5401       }
5402     END_CATCH
5403   }
5404
5405   remote_btrace_reset ();
5406
5407   if (target_async_permitted)
5408     wait_forever_enabled_p = 1;
5409 }
5410
5411 /* Detach the specified process.  */
5412
5413 static void
5414 remote_detach_pid (int pid)
5415 {
5416   struct remote_state *rs = get_remote_state ();
5417
5418   if (remote_multi_process_p (rs))
5419     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5420   else
5421     strcpy (rs->buf, "D");
5422
5423   putpkt (rs->buf);
5424   getpkt (&rs->buf, &rs->buf_size, 0);
5425
5426   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5427     ;
5428   else if (rs->buf[0] == '\0')
5429     error (_("Remote doesn't know how to detach"));
5430   else
5431     error (_("Can't detach process."));
5432 }
5433
5434 /* This detaches a program to which we previously attached, using
5435    inferior_ptid to identify the process.  After this is done, GDB
5436    can be used to debug some other program.  We better not have left
5437    any breakpoints in the target program or it'll die when it hits
5438    one.  */
5439
5440 static void
5441 remote_detach_1 (int from_tty, inferior *inf)
5442 {
5443   int pid = ptid_get_pid (inferior_ptid);
5444   struct remote_state *rs = get_remote_state ();
5445   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5446   int is_fork_parent;
5447
5448   if (!target_has_execution)
5449     error (_("No process to detach from."));
5450
5451   target_announce_detach (from_tty);
5452
5453   /* Tell the remote target to detach.  */
5454   remote_detach_pid (pid);
5455
5456   /* Exit only if this is the only active inferior.  */
5457   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5458     puts_filtered (_("Ending remote debugging.\n"));
5459
5460   /* Check to see if we are detaching a fork parent.  Note that if we
5461      are detaching a fork child, tp == NULL.  */
5462   is_fork_parent = (tp != NULL
5463                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5464
5465   /* If doing detach-on-fork, we don't mourn, because that will delete
5466      breakpoints that should be available for the followed inferior.  */
5467   if (!is_fork_parent)
5468     {
5469       /* Save the pid as a string before mourning, since that will
5470          unpush the remote target, and we need the string after.  */
5471       std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5472
5473       target_mourn_inferior (inferior_ptid);
5474       if (print_inferior_events)
5475         printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5476                            inf->num, infpid.c_str ());
5477     }
5478   else
5479     {
5480       inferior_ptid = null_ptid;
5481       detach_inferior (pid);
5482     }
5483 }
5484
5485 void
5486 remote_target::detach (inferior *inf, int from_tty)
5487 {
5488   remote_detach_1 (from_tty, inf);
5489 }
5490
5491 void
5492 extended_remote_target::detach (inferior *inf, int from_tty)
5493 {
5494   remote_detach_1 (from_tty, inf);
5495 }
5496
5497 /* Target follow-fork function for remote targets.  On entry, and
5498    at return, the current inferior is the fork parent.
5499
5500    Note that although this is currently only used for extended-remote,
5501    it is named remote_follow_fork in anticipation of using it for the
5502    remote target as well.  */
5503
5504 int
5505 remote_target::follow_fork (int follow_child, int detach_fork)
5506 {
5507   struct remote_state *rs = get_remote_state ();
5508   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5509
5510   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5511       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5512     {
5513       /* When following the parent and detaching the child, we detach
5514          the child here.  For the case of following the child and
5515          detaching the parent, the detach is done in the target-
5516          independent follow fork code in infrun.c.  We can't use
5517          target_detach when detaching an unfollowed child because
5518          the client side doesn't know anything about the child.  */
5519       if (detach_fork && !follow_child)
5520         {
5521           /* Detach the fork child.  */
5522           ptid_t child_ptid;
5523           pid_t child_pid;
5524
5525           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5526           child_pid = ptid_get_pid (child_ptid);
5527
5528           remote_detach_pid (child_pid);
5529         }
5530     }
5531   return 0;
5532 }
5533
5534 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5535    in the program space of the new inferior.  On entry and at return the
5536    current inferior is the exec'ing inferior.  INF is the new exec'd
5537    inferior, which may be the same as the exec'ing inferior unless
5538    follow-exec-mode is "new".  */
5539
5540 void
5541 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5542 {
5543   /* We know that this is a target file name, so if it has the "target:"
5544      prefix we strip it off before saving it in the program space.  */
5545   if (is_target_filename (execd_pathname))
5546     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5547
5548   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5549 }
5550
5551 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5552
5553 void
5554 remote_target::disconnect (const char *args, int from_tty)
5555 {
5556   if (args)
5557     error (_("Argument given to \"disconnect\" when remotely debugging."));
5558
5559   /* Make sure we unpush even the extended remote targets.  Calling
5560      target_mourn_inferior won't unpush, and remote_mourn won't
5561      unpush if there is more than one inferior left.  */
5562   unpush_target (this);
5563   generic_mourn_inferior ();
5564
5565   if (from_tty)
5566     puts_filtered ("Ending remote debugging.\n");
5567 }
5568
5569 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5570    be chatty about it.  */
5571
5572 void
5573 extended_remote_target::attach (const char *args, int from_tty)
5574 {
5575   struct remote_state *rs = get_remote_state ();
5576   int pid;
5577   char *wait_status = NULL;
5578
5579   pid = parse_pid_to_attach (args);
5580
5581   /* Remote PID can be freely equal to getpid, do not check it here the same
5582      way as in other targets.  */
5583
5584   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5585     error (_("This target does not support attaching to a process"));
5586
5587   if (from_tty)
5588     {
5589       char *exec_file = get_exec_file (0);
5590
5591       if (exec_file)
5592         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5593                            target_pid_to_str (pid_to_ptid (pid)));
5594       else
5595         printf_unfiltered (_("Attaching to %s\n"),
5596                            target_pid_to_str (pid_to_ptid (pid)));
5597
5598       gdb_flush (gdb_stdout);
5599     }
5600
5601   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5602   putpkt (rs->buf);
5603   getpkt (&rs->buf, &rs->buf_size, 0);
5604
5605   switch (packet_ok (rs->buf,
5606                      &remote_protocol_packets[PACKET_vAttach]))
5607     {
5608     case PACKET_OK:
5609       if (!target_is_non_stop_p ())
5610         {
5611           /* Save the reply for later.  */
5612           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5613           strcpy (wait_status, rs->buf);
5614         }
5615       else if (strcmp (rs->buf, "OK") != 0)
5616         error (_("Attaching to %s failed with: %s"),
5617                target_pid_to_str (pid_to_ptid (pid)),
5618                rs->buf);
5619       break;
5620     case PACKET_UNKNOWN:
5621       error (_("This target does not support attaching to a process"));
5622     default:
5623       error (_("Attaching to %s failed"),
5624              target_pid_to_str (pid_to_ptid (pid)));
5625     }
5626
5627   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5628
5629   inferior_ptid = pid_to_ptid (pid);
5630
5631   if (target_is_non_stop_p ())
5632     {
5633       struct thread_info *thread;
5634
5635       /* Get list of threads.  */
5636       update_thread_list ();
5637
5638       thread = first_thread_of_process (pid);
5639       if (thread)
5640         inferior_ptid = thread->ptid;
5641       else
5642         inferior_ptid = pid_to_ptid (pid);
5643
5644       /* Invalidate our notion of the remote current thread.  */
5645       record_currthread (rs, minus_one_ptid);
5646     }
5647   else
5648     {
5649       /* Now, if we have thread information, update inferior_ptid.  */
5650       inferior_ptid = remote_current_thread (inferior_ptid);
5651
5652       /* Add the main thread to the thread list.  */
5653       thread_info *thr = add_thread_silent (inferior_ptid);
5654       /* Don't consider the thread stopped until we've processed the
5655          saved stop reply.  */
5656       set_executing (thr->ptid, true);
5657     }
5658
5659   /* Next, if the target can specify a description, read it.  We do
5660      this before anything involving memory or registers.  */
5661   target_find_description ();
5662
5663   if (!target_is_non_stop_p ())
5664     {
5665       /* Use the previously fetched status.  */
5666       gdb_assert (wait_status != NULL);
5667
5668       if (target_can_async_p ())
5669         {
5670           struct notif_event *reply
5671             =  remote_notif_parse (&notif_client_stop, wait_status);
5672
5673           push_stop_reply ((struct stop_reply *) reply);
5674
5675           target_async (1);
5676         }
5677       else
5678         {
5679           gdb_assert (wait_status != NULL);
5680           strcpy (rs->buf, wait_status);
5681           rs->cached_wait_status = 1;
5682         }
5683     }
5684   else
5685     gdb_assert (wait_status == NULL);
5686 }
5687
5688 /* Implementation of the to_post_attach method.  */
5689
5690 void
5691 extended_remote_target::post_attach (int pid)
5692 {
5693   /* Get text, data & bss offsets.  */
5694   get_offsets ();
5695
5696   /* In certain cases GDB might not have had the chance to start
5697      symbol lookup up until now.  This could happen if the debugged
5698      binary is not using shared libraries, the vsyscall page is not
5699      present (on Linux) and the binary itself hadn't changed since the
5700      debugging process was started.  */
5701   if (symfile_objfile != NULL)
5702     remote_check_symbols();
5703 }
5704
5705 \f
5706 /* Check for the availability of vCont.  This function should also check
5707    the response.  */
5708
5709 static void
5710 remote_vcont_probe (struct remote_state *rs)
5711 {
5712   char *buf;
5713
5714   strcpy (rs->buf, "vCont?");
5715   putpkt (rs->buf);
5716   getpkt (&rs->buf, &rs->buf_size, 0);
5717   buf = rs->buf;
5718
5719   /* Make sure that the features we assume are supported.  */
5720   if (startswith (buf, "vCont"))
5721     {
5722       char *p = &buf[5];
5723       int support_c, support_C;
5724
5725       rs->supports_vCont.s = 0;
5726       rs->supports_vCont.S = 0;
5727       support_c = 0;
5728       support_C = 0;
5729       rs->supports_vCont.t = 0;
5730       rs->supports_vCont.r = 0;
5731       while (p && *p == ';')
5732         {
5733           p++;
5734           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5735             rs->supports_vCont.s = 1;
5736           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5737             rs->supports_vCont.S = 1;
5738           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5739             support_c = 1;
5740           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5741             support_C = 1;
5742           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5743             rs->supports_vCont.t = 1;
5744           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5745             rs->supports_vCont.r = 1;
5746
5747           p = strchr (p, ';');
5748         }
5749
5750       /* If c, and C are not all supported, we can't use vCont.  Clearing
5751          BUF will make packet_ok disable the packet.  */
5752       if (!support_c || !support_C)
5753         buf[0] = 0;
5754     }
5755
5756   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5757 }
5758
5759 /* Helper function for building "vCont" resumptions.  Write a
5760    resumption to P.  ENDP points to one-passed-the-end of the buffer
5761    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5762    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5763    resumed thread should be single-stepped and/or signalled.  If PTID
5764    equals minus_one_ptid, then all threads are resumed; if PTID
5765    represents a process, then all threads of the process are resumed;
5766    the thread to be stepped and/or signalled is given in the global
5767    INFERIOR_PTID.  */
5768
5769 static char *
5770 append_resumption (char *p, char *endp,
5771                    ptid_t ptid, int step, enum gdb_signal siggnal)
5772 {
5773   struct remote_state *rs = get_remote_state ();
5774
5775   if (step && siggnal != GDB_SIGNAL_0)
5776     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5777   else if (step
5778            /* GDB is willing to range step.  */
5779            && use_range_stepping
5780            /* Target supports range stepping.  */
5781            && rs->supports_vCont.r
5782            /* We don't currently support range stepping multiple
5783               threads with a wildcard (though the protocol allows it,
5784               so stubs shouldn't make an active effort to forbid
5785               it).  */
5786            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5787     {
5788       struct thread_info *tp;
5789
5790       if (ptid_equal (ptid, minus_one_ptid))
5791         {
5792           /* If we don't know about the target thread's tid, then
5793              we're resuming magic_null_ptid (see caller).  */
5794           tp = find_thread_ptid (magic_null_ptid);
5795         }
5796       else
5797         tp = find_thread_ptid (ptid);
5798       gdb_assert (tp != NULL);
5799
5800       if (tp->control.may_range_step)
5801         {
5802           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5803
5804           p += xsnprintf (p, endp - p, ";r%s,%s",
5805                           phex_nz (tp->control.step_range_start,
5806                                    addr_size),
5807                           phex_nz (tp->control.step_range_end,
5808                                    addr_size));
5809         }
5810       else
5811         p += xsnprintf (p, endp - p, ";s");
5812     }
5813   else if (step)
5814     p += xsnprintf (p, endp - p, ";s");
5815   else if (siggnal != GDB_SIGNAL_0)
5816     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5817   else
5818     p += xsnprintf (p, endp - p, ";c");
5819
5820   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5821     {
5822       ptid_t nptid;
5823
5824       /* All (-1) threads of process.  */
5825       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5826
5827       p += xsnprintf (p, endp - p, ":");
5828       p = write_ptid (p, endp, nptid);
5829     }
5830   else if (!ptid_equal (ptid, minus_one_ptid))
5831     {
5832       p += xsnprintf (p, endp - p, ":");
5833       p = write_ptid (p, endp, ptid);
5834     }
5835
5836   return p;
5837 }
5838
5839 /* Clear the thread's private info on resume.  */
5840
5841 static void
5842 resume_clear_thread_private_info (struct thread_info *thread)
5843 {
5844   if (thread->priv != NULL)
5845     {
5846       remote_thread_info *priv = get_remote_thread_info (thread);
5847
5848       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5849       priv->watch_data_address = 0;
5850     }
5851 }
5852
5853 /* Append a vCont continue-with-signal action for threads that have a
5854    non-zero stop signal.  */
5855
5856 static char *
5857 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5858 {
5859   struct thread_info *thread;
5860
5861   ALL_NON_EXITED_THREADS (thread)
5862     if (ptid_match (thread->ptid, ptid)
5863         && !ptid_equal (inferior_ptid, thread->ptid)
5864         && thread->suspend.stop_signal != GDB_SIGNAL_0)
5865       {
5866         p = append_resumption (p, endp, thread->ptid,
5867                                0, thread->suspend.stop_signal);
5868         thread->suspend.stop_signal = GDB_SIGNAL_0;
5869         resume_clear_thread_private_info (thread);
5870       }
5871
5872   return p;
5873 }
5874
5875 /* Set the target running, using the packets that use Hc
5876    (c/s/C/S).  */
5877
5878 static void
5879 remote_resume_with_hc (struct target_ops *ops,
5880                        ptid_t ptid, int step, enum gdb_signal siggnal)
5881 {
5882   struct remote_state *rs = get_remote_state ();
5883   struct thread_info *thread;
5884   char *buf;
5885
5886   rs->last_sent_signal = siggnal;
5887   rs->last_sent_step = step;
5888
5889   /* The c/s/C/S resume packets use Hc, so set the continue
5890      thread.  */
5891   if (ptid_equal (ptid, minus_one_ptid))
5892     set_continue_thread (any_thread_ptid);
5893   else
5894     set_continue_thread (ptid);
5895
5896   ALL_NON_EXITED_THREADS (thread)
5897     resume_clear_thread_private_info (thread);
5898
5899   buf = rs->buf;
5900   if (execution_direction == EXEC_REVERSE)
5901     {
5902       /* We don't pass signals to the target in reverse exec mode.  */
5903       if (info_verbose && siggnal != GDB_SIGNAL_0)
5904         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5905                  siggnal);
5906
5907       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5908         error (_("Remote reverse-step not supported."));
5909       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5910         error (_("Remote reverse-continue not supported."));
5911
5912       strcpy (buf, step ? "bs" : "bc");
5913     }
5914   else if (siggnal != GDB_SIGNAL_0)
5915     {
5916       buf[0] = step ? 'S' : 'C';
5917       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5918       buf[2] = tohex (((int) siggnal) & 0xf);
5919       buf[3] = '\0';
5920     }
5921   else
5922     strcpy (buf, step ? "s" : "c");
5923
5924   putpkt (buf);
5925 }
5926
5927 /* Resume the remote inferior by using a "vCont" packet.  The thread
5928    to be resumed is PTID; STEP and SIGGNAL indicate whether the
5929    resumed thread should be single-stepped and/or signalled.  If PTID
5930    equals minus_one_ptid, then all threads are resumed; the thread to
5931    be stepped and/or signalled is given in the global INFERIOR_PTID.
5932    This function returns non-zero iff it resumes the inferior.
5933
5934    This function issues a strict subset of all possible vCont commands
5935    at the moment.  */
5936
5937 static int
5938 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5939 {
5940   struct remote_state *rs = get_remote_state ();
5941   char *p;
5942   char *endp;
5943
5944   /* No reverse execution actions defined for vCont.  */
5945   if (execution_direction == EXEC_REVERSE)
5946     return 0;
5947
5948   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5949     remote_vcont_probe (rs);
5950
5951   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5952     return 0;
5953
5954   p = rs->buf;
5955   endp = rs->buf + get_remote_packet_size ();
5956
5957   /* If we could generate a wider range of packets, we'd have to worry
5958      about overflowing BUF.  Should there be a generic
5959      "multi-part-packet" packet?  */
5960
5961   p += xsnprintf (p, endp - p, "vCont");
5962
5963   if (ptid_equal (ptid, magic_null_ptid))
5964     {
5965       /* MAGIC_NULL_PTID means that we don't have any active threads,
5966          so we don't have any TID numbers the inferior will
5967          understand.  Make sure to only send forms that do not specify
5968          a TID.  */
5969       append_resumption (p, endp, minus_one_ptid, step, siggnal);
5970     }
5971   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5972     {
5973       /* Resume all threads (of all processes, or of a single
5974          process), with preference for INFERIOR_PTID.  This assumes
5975          inferior_ptid belongs to the set of all threads we are about
5976          to resume.  */
5977       if (step || siggnal != GDB_SIGNAL_0)
5978         {
5979           /* Step inferior_ptid, with or without signal.  */
5980           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5981         }
5982
5983       /* Also pass down any pending signaled resumption for other
5984          threads not the current.  */
5985       p = append_pending_thread_resumptions (p, endp, ptid);
5986
5987       /* And continue others without a signal.  */
5988       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5989     }
5990   else
5991     {
5992       /* Scheduler locking; resume only PTID.  */
5993       append_resumption (p, endp, ptid, step, siggnal);
5994     }
5995
5996   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5997   putpkt (rs->buf);
5998
5999   if (target_is_non_stop_p ())
6000     {
6001       /* In non-stop, the stub replies to vCont with "OK".  The stop
6002          reply will be reported asynchronously by means of a `%Stop'
6003          notification.  */
6004       getpkt (&rs->buf, &rs->buf_size, 0);
6005       if (strcmp (rs->buf, "OK") != 0)
6006         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6007     }
6008
6009   return 1;
6010 }
6011
6012 /* Tell the remote machine to resume.  */
6013
6014 void
6015 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6016 {
6017   struct remote_state *rs = get_remote_state ();
6018
6019   /* When connected in non-stop mode, the core resumes threads
6020      individually.  Resuming remote threads directly in target_resume
6021      would thus result in sending one packet per thread.  Instead, to
6022      minimize roundtrip latency, here we just store the resume
6023      request; the actual remote resumption will be done in
6024      target_commit_resume / remote_commit_resume, where we'll be able
6025      to do vCont action coalescing.  */
6026   if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6027     {
6028       remote_thread_info *remote_thr;
6029
6030       if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
6031         remote_thr = get_remote_thread_info (inferior_ptid);
6032       else
6033         remote_thr = get_remote_thread_info (ptid);
6034
6035       remote_thr->last_resume_step = step;
6036       remote_thr->last_resume_sig = siggnal;
6037       return;
6038     }
6039
6040   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6041      (explained in remote-notif.c:handle_notification) so
6042      remote_notif_process is not called.  We need find a place where
6043      it is safe to start a 'vNotif' sequence.  It is good to do it
6044      before resuming inferior, because inferior was stopped and no RSP
6045      traffic at that moment.  */
6046   if (!target_is_non_stop_p ())
6047     remote_notif_process (rs->notif_state, &notif_client_stop);
6048
6049   rs->last_resume_exec_dir = ::execution_direction;
6050
6051   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
6052   if (!remote_resume_with_vcont (ptid, step, siggnal))
6053     remote_resume_with_hc (this, ptid, step, siggnal);
6054
6055   /* We are about to start executing the inferior, let's register it
6056      with the event loop.  NOTE: this is the one place where all the
6057      execution commands end up.  We could alternatively do this in each
6058      of the execution commands in infcmd.c.  */
6059   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6060      into infcmd.c in order to allow inferior function calls to work
6061      NOT asynchronously.  */
6062   if (target_can_async_p ())
6063     target_async (1);
6064
6065   /* We've just told the target to resume.  The remote server will
6066      wait for the inferior to stop, and then send a stop reply.  In
6067      the mean time, we can't start another command/query ourselves
6068      because the stub wouldn't be ready to process it.  This applies
6069      only to the base all-stop protocol, however.  In non-stop (which
6070      only supports vCont), the stub replies with an "OK", and is
6071      immediate able to process further serial input.  */
6072   if (!target_is_non_stop_p ())
6073     rs->waiting_for_stop_reply = 1;
6074 }
6075
6076 static void check_pending_events_prevent_wildcard_vcont
6077   (int *may_global_wildcard_vcont);
6078 static int is_pending_fork_parent_thread (struct thread_info *thread);
6079
6080 /* Private per-inferior info for target remote processes.  */
6081
6082 struct remote_inferior : public private_inferior
6083 {
6084   /* Whether we can send a wildcard vCont for this process.  */
6085   bool may_wildcard_vcont = true;
6086 };
6087
6088 /* Get the remote private inferior data associated to INF.  */
6089
6090 static remote_inferior *
6091 get_remote_inferior (inferior *inf)
6092 {
6093   if (inf->priv == NULL)
6094     inf->priv.reset (new remote_inferior);
6095
6096   return static_cast<remote_inferior *> (inf->priv.get ());
6097 }
6098
6099 /* Structure used to track the construction of a vCont packet in the
6100    outgoing packet buffer.  This is used to send multiple vCont
6101    packets if we have more actions than would fit a single packet.  */
6102
6103 struct vcont_builder
6104 {
6105   /* Pointer to the first action.  P points here if no action has been
6106      appended yet.  */
6107   char *first_action;
6108
6109   /* Where the next action will be appended.  */
6110   char *p;
6111
6112   /* The end of the buffer.  Must never write past this.  */
6113   char *endp;
6114 };
6115
6116 /* Prepare the outgoing buffer for a new vCont packet.  */
6117
6118 static void
6119 vcont_builder_restart (struct vcont_builder *builder)
6120 {
6121   struct remote_state *rs = get_remote_state ();
6122
6123   builder->p = rs->buf;
6124   builder->endp = rs->buf + get_remote_packet_size ();
6125   builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
6126   builder->first_action = builder->p;
6127 }
6128
6129 /* If the vCont packet being built has any action, send it to the
6130    remote end.  */
6131
6132 static void
6133 vcont_builder_flush (struct vcont_builder *builder)
6134 {
6135   struct remote_state *rs;
6136
6137   if (builder->p == builder->first_action)
6138     return;
6139
6140   rs = get_remote_state ();
6141   putpkt (rs->buf);
6142   getpkt (&rs->buf, &rs->buf_size, 0);
6143   if (strcmp (rs->buf, "OK") != 0)
6144     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6145 }
6146
6147 /* The largest action is range-stepping, with its two addresses.  This
6148    is more than sufficient.  If a new, bigger action is created, it'll
6149    quickly trigger a failed assertion in append_resumption (and we'll
6150    just bump this).  */
6151 #define MAX_ACTION_SIZE 200
6152
6153 /* Append a new vCont action in the outgoing packet being built.  If
6154    the action doesn't fit the packet along with previous actions, push
6155    what we've got so far to the remote end and start over a new vCont
6156    packet (with the new action).  */
6157
6158 static void
6159 vcont_builder_push_action (struct vcont_builder *builder,
6160                            ptid_t ptid, int step, enum gdb_signal siggnal)
6161 {
6162   char buf[MAX_ACTION_SIZE + 1];
6163   char *endp;
6164   size_t rsize;
6165
6166   endp = append_resumption (buf, buf + sizeof (buf),
6167                             ptid, step, siggnal);
6168
6169   /* Check whether this new action would fit in the vCont packet along
6170      with previous actions.  If not, send what we've got so far and
6171      start a new vCont packet.  */
6172   rsize = endp - buf;
6173   if (rsize > builder->endp - builder->p)
6174     {
6175       vcont_builder_flush (builder);
6176       vcont_builder_restart (builder);
6177
6178       /* Should now fit.  */
6179       gdb_assert (rsize <= builder->endp - builder->p);
6180     }
6181
6182   memcpy (builder->p, buf, rsize);
6183   builder->p += rsize;
6184   *builder->p = '\0';
6185 }
6186
6187 /* to_commit_resume implementation.  */
6188
6189 void
6190 remote_target::commit_resume ()
6191 {
6192   struct inferior *inf;
6193   struct thread_info *tp;
6194   int any_process_wildcard;
6195   int may_global_wildcard_vcont;
6196   struct vcont_builder vcont_builder;
6197
6198   /* If connected in all-stop mode, we'd send the remote resume
6199      request directly from remote_resume.  Likewise if
6200      reverse-debugging, as there are no defined vCont actions for
6201      reverse execution.  */
6202   if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6203     return;
6204
6205   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6206      instead of resuming all threads of each process individually.
6207      However, if any thread of a process must remain halted, we can't
6208      send wildcard resumes and must send one action per thread.
6209
6210      Care must be taken to not resume threads/processes the server
6211      side already told us are stopped, but the core doesn't know about
6212      yet, because the events are still in the vStopped notification
6213      queue.  For example:
6214
6215        #1 => vCont s:p1.1;c
6216        #2 <= OK
6217        #3 <= %Stopped T05 p1.1
6218        #4 => vStopped
6219        #5 <= T05 p1.2
6220        #6 => vStopped
6221        #7 <= OK
6222        #8 (infrun handles the stop for p1.1 and continues stepping)
6223        #9 => vCont s:p1.1;c
6224
6225      The last vCont above would resume thread p1.2 by mistake, because
6226      the server has no idea that the event for p1.2 had not been
6227      handled yet.
6228
6229      The server side must similarly ignore resume actions for the
6230      thread that has a pending %Stopped notification (and any other
6231      threads with events pending), until GDB acks the notification
6232      with vStopped.  Otherwise, e.g., the following case is
6233      mishandled:
6234
6235        #1 => g  (or any other packet)
6236        #2 <= [registers]
6237        #3 <= %Stopped T05 p1.2
6238        #4 => vCont s:p1.1;c
6239        #5 <= OK
6240
6241      Above, the server must not resume thread p1.2.  GDB can't know
6242      that p1.2 stopped until it acks the %Stopped notification, and
6243      since from GDB's perspective all threads should be running, it
6244      sends a "c" action.
6245
6246      Finally, special care must also be given to handling fork/vfork
6247      events.  A (v)fork event actually tells us that two processes
6248      stopped -- the parent and the child.  Until we follow the fork,
6249      we must not resume the child.  Therefore, if we have a pending
6250      fork follow, we must not send a global wildcard resume action
6251      (vCont;c).  We can still send process-wide wildcards though.  */
6252
6253   /* Start by assuming a global wildcard (vCont;c) is possible.  */
6254   may_global_wildcard_vcont = 1;
6255
6256   /* And assume every process is individually wildcard-able too.  */
6257   ALL_NON_EXITED_INFERIORS (inf)
6258     {
6259       remote_inferior *priv = get_remote_inferior (inf);
6260
6261       priv->may_wildcard_vcont = true;
6262     }
6263
6264   /* Check for any pending events (not reported or processed yet) and
6265      disable process and global wildcard resumes appropriately.  */
6266   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6267
6268   ALL_NON_EXITED_THREADS (tp)
6269     {
6270       /* If a thread of a process is not meant to be resumed, then we
6271          can't wildcard that process.  */
6272       if (!tp->executing)
6273         {
6274           get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6275
6276           /* And if we can't wildcard a process, we can't wildcard
6277              everything either.  */
6278           may_global_wildcard_vcont = 0;
6279           continue;
6280         }
6281
6282       /* If a thread is the parent of an unfollowed fork, then we
6283          can't do a global wildcard, as that would resume the fork
6284          child.  */
6285       if (is_pending_fork_parent_thread (tp))
6286         may_global_wildcard_vcont = 0;
6287     }
6288
6289   /* Now let's build the vCont packet(s).  Actions must be appended
6290      from narrower to wider scopes (thread -> process -> global).  If
6291      we end up with too many actions for a single packet vcont_builder
6292      flushes the current vCont packet to the remote side and starts a
6293      new one.  */
6294   vcont_builder_restart (&vcont_builder);
6295
6296   /* Threads first.  */
6297   ALL_NON_EXITED_THREADS (tp)
6298     {
6299       remote_thread_info *remote_thr = get_remote_thread_info (tp);
6300
6301       if (!tp->executing || remote_thr->vcont_resumed)
6302         continue;
6303
6304       gdb_assert (!thread_is_in_step_over_chain (tp));
6305
6306       if (!remote_thr->last_resume_step
6307           && remote_thr->last_resume_sig == GDB_SIGNAL_0
6308           && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6309         {
6310           /* We'll send a wildcard resume instead.  */
6311           remote_thr->vcont_resumed = 1;
6312           continue;
6313         }
6314
6315       vcont_builder_push_action (&vcont_builder, tp->ptid,
6316                                  remote_thr->last_resume_step,
6317                                  remote_thr->last_resume_sig);
6318       remote_thr->vcont_resumed = 1;
6319     }
6320
6321   /* Now check whether we can send any process-wide wildcard.  This is
6322      to avoid sending a global wildcard in the case nothing is
6323      supposed to be resumed.  */
6324   any_process_wildcard = 0;
6325
6326   ALL_NON_EXITED_INFERIORS (inf)
6327     {
6328       if (get_remote_inferior (inf)->may_wildcard_vcont)
6329         {
6330           any_process_wildcard = 1;
6331           break;
6332         }
6333     }
6334
6335   if (any_process_wildcard)
6336     {
6337       /* If all processes are wildcard-able, then send a single "c"
6338          action, otherwise, send an "all (-1) threads of process"
6339          continue action for each running process, if any.  */
6340       if (may_global_wildcard_vcont)
6341         {
6342           vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6343                                      0, GDB_SIGNAL_0);
6344         }
6345       else
6346         {
6347           ALL_NON_EXITED_INFERIORS (inf)
6348             {
6349               if (get_remote_inferior (inf)->may_wildcard_vcont)
6350                 {
6351                   vcont_builder_push_action (&vcont_builder,
6352                                              pid_to_ptid (inf->pid),
6353                                              0, GDB_SIGNAL_0);
6354                 }
6355             }
6356         }
6357     }
6358
6359   vcont_builder_flush (&vcont_builder);
6360 }
6361
6362 \f
6363
6364 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
6365    thread, all threads of a remote process, or all threads of all
6366    processes.  */
6367
6368 static void
6369 remote_stop_ns (ptid_t ptid)
6370 {
6371   struct remote_state *rs = get_remote_state ();
6372   char *p = rs->buf;
6373   char *endp = rs->buf + get_remote_packet_size ();
6374
6375   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6376     remote_vcont_probe (rs);
6377
6378   if (!rs->supports_vCont.t)
6379     error (_("Remote server does not support stopping threads"));
6380
6381   if (ptid_equal (ptid, minus_one_ptid)
6382       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6383     p += xsnprintf (p, endp - p, "vCont;t");
6384   else
6385     {
6386       ptid_t nptid;
6387
6388       p += xsnprintf (p, endp - p, "vCont;t:");
6389
6390       if (ptid_is_pid (ptid))
6391           /* All (-1) threads of process.  */
6392         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6393       else
6394         {
6395           /* Small optimization: if we already have a stop reply for
6396              this thread, no use in telling the stub we want this
6397              stopped.  */
6398           if (peek_stop_reply (ptid))
6399             return;
6400
6401           nptid = ptid;
6402         }
6403
6404       write_ptid (p, endp, nptid);
6405     }
6406
6407   /* In non-stop, we get an immediate OK reply.  The stop reply will
6408      come in asynchronously by notification.  */
6409   putpkt (rs->buf);
6410   getpkt (&rs->buf, &rs->buf_size, 0);
6411   if (strcmp (rs->buf, "OK") != 0)
6412     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6413 }
6414
6415 /* All-stop version of target_interrupt.  Sends a break or a ^C to
6416    interrupt the remote target.  It is undefined which thread of which
6417    process reports the interrupt.  */
6418
6419 static void
6420 remote_interrupt_as (void)
6421 {
6422   struct remote_state *rs = get_remote_state ();
6423
6424   rs->ctrlc_pending_p = 1;
6425
6426   /* If the inferior is stopped already, but the core didn't know
6427      about it yet, just ignore the request.  The cached wait status
6428      will be collected in remote_wait.  */
6429   if (rs->cached_wait_status)
6430     return;
6431
6432   /* Send interrupt_sequence to remote target.  */
6433   send_interrupt_sequence ();
6434 }
6435
6436 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
6437    the remote target.  It is undefined which thread of which process
6438    reports the interrupt.  Throws an error if the packet is not
6439    supported by the server.  */
6440
6441 static void
6442 remote_interrupt_ns (void)
6443 {
6444   struct remote_state *rs = get_remote_state ();
6445   char *p = rs->buf;
6446   char *endp = rs->buf + get_remote_packet_size ();
6447
6448   xsnprintf (p, endp - p, "vCtrlC");
6449
6450   /* In non-stop, we get an immediate OK reply.  The stop reply will
6451      come in asynchronously by notification.  */
6452   putpkt (rs->buf);
6453   getpkt (&rs->buf, &rs->buf_size, 0);
6454
6455   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6456     {
6457     case PACKET_OK:
6458       break;
6459     case PACKET_UNKNOWN:
6460       error (_("No support for interrupting the remote target."));
6461     case PACKET_ERROR:
6462       error (_("Interrupting target failed: %s"), rs->buf);
6463     }
6464 }
6465
6466 /* Implement the to_stop function for the remote targets.  */
6467
6468 void
6469 remote_target::stop (ptid_t ptid)
6470 {
6471   if (remote_debug)
6472     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6473
6474   if (target_is_non_stop_p ())
6475     remote_stop_ns (ptid);
6476   else
6477     {
6478       /* We don't currently have a way to transparently pause the
6479          remote target in all-stop mode.  Interrupt it instead.  */
6480       remote_interrupt_as ();
6481     }
6482 }
6483
6484 /* Implement the to_interrupt function for the remote targets.  */
6485
6486 void
6487 remote_target::interrupt ()
6488 {
6489   if (remote_debug)
6490     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6491
6492   if (target_is_non_stop_p ())
6493     remote_interrupt_ns ();
6494   else
6495     remote_interrupt_as ();
6496 }
6497
6498 /* Implement the to_pass_ctrlc function for the remote targets.  */
6499
6500 void
6501 remote_target::pass_ctrlc ()
6502 {
6503   struct remote_state *rs = get_remote_state ();
6504
6505   if (remote_debug)
6506     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6507
6508   /* If we're starting up, we're not fully synced yet.  Quit
6509      immediately.  */
6510   if (rs->starting_up)
6511     quit ();
6512   /* If ^C has already been sent once, offer to disconnect.  */
6513   else if (rs->ctrlc_pending_p)
6514     interrupt_query ();
6515   else
6516     target_interrupt ();
6517 }
6518
6519 /* Ask the user what to do when an interrupt is received.  */
6520
6521 static void
6522 interrupt_query (void)
6523 {
6524   struct remote_state *rs = get_remote_state ();
6525
6526   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6527     {
6528       if (query (_("The target is not responding to interrupt requests.\n"
6529                    "Stop debugging it? ")))
6530         {
6531           remote_unpush_target ();
6532           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6533         }
6534     }
6535   else
6536     {
6537       if (query (_("Interrupted while waiting for the program.\n"
6538                    "Give up waiting? ")))
6539         quit ();
6540     }
6541 }
6542
6543 /* Enable/disable target terminal ownership.  Most targets can use
6544    terminal groups to control terminal ownership.  Remote targets are
6545    different in that explicit transfer of ownership to/from GDB/target
6546    is required.  */
6547
6548 void
6549 remote_target::terminal_inferior ()
6550 {
6551   /* NOTE: At this point we could also register our selves as the
6552      recipient of all input.  Any characters typed could then be
6553      passed on down to the target.  */
6554 }
6555
6556 void
6557 remote_target::terminal_ours ()
6558 {
6559 }
6560
6561 static void
6562 remote_console_output (char *msg)
6563 {
6564   char *p;
6565
6566   for (p = msg; p[0] && p[1]; p += 2)
6567     {
6568       char tb[2];
6569       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6570
6571       tb[0] = c;
6572       tb[1] = 0;
6573       fputs_unfiltered (tb, gdb_stdtarg);
6574     }
6575   gdb_flush (gdb_stdtarg);
6576 }
6577
6578 DEF_VEC_O(cached_reg_t);
6579
6580 typedef struct stop_reply
6581 {
6582   struct notif_event base;
6583
6584   /* The identifier of the thread about this event  */
6585   ptid_t ptid;
6586
6587   /* The remote state this event is associated with.  When the remote
6588      connection, represented by a remote_state object, is closed,
6589      all the associated stop_reply events should be released.  */
6590   struct remote_state *rs;
6591
6592   struct target_waitstatus ws;
6593
6594   /* The architecture associated with the expedited registers.  */
6595   gdbarch *arch;
6596
6597   /* Expedited registers.  This makes remote debugging a bit more
6598      efficient for those targets that provide critical registers as
6599      part of their normal status mechanism (as another roundtrip to
6600      fetch them is avoided).  */
6601   VEC(cached_reg_t) *regcache;
6602
6603   enum target_stop_reason stop_reason;
6604
6605   CORE_ADDR watch_data_address;
6606
6607   int core;
6608 } *stop_reply_p;
6609
6610 DECLARE_QUEUE_P (stop_reply_p);
6611 DEFINE_QUEUE_P (stop_reply_p);
6612 /* The list of already fetched and acknowledged stop events.  This
6613    queue is used for notification Stop, and other notifications
6614    don't need queue for their events, because the notification events
6615    of Stop can't be consumed immediately, so that events should be
6616    queued first, and be consumed by remote_wait_{ns,as} one per
6617    time.  Other notifications can consume their events immediately,
6618    so queue is not needed for them.  */
6619 static QUEUE (stop_reply_p) *stop_reply_queue;
6620
6621 static void
6622 stop_reply_xfree (struct stop_reply *r)
6623 {
6624   notif_event_xfree ((struct notif_event *) r);
6625 }
6626
6627 /* Return the length of the stop reply queue.  */
6628
6629 static int
6630 stop_reply_queue_length (void)
6631 {
6632   return QUEUE_length (stop_reply_p, stop_reply_queue);
6633 }
6634
6635 static void
6636 remote_notif_stop_parse (struct notif_client *self, char *buf,
6637                          struct notif_event *event)
6638 {
6639   remote_parse_stop_reply (buf, (struct stop_reply *) event);
6640 }
6641
6642 static void
6643 remote_notif_stop_ack (struct notif_client *self, char *buf,
6644                        struct notif_event *event)
6645 {
6646   struct stop_reply *stop_reply = (struct stop_reply *) event;
6647
6648   /* acknowledge */
6649   putpkt (self->ack_command);
6650
6651   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6652       /* We got an unknown stop reply.  */
6653       error (_("Unknown stop reply"));
6654
6655   push_stop_reply (stop_reply);
6656 }
6657
6658 static int
6659 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6660 {
6661   /* We can't get pending events in remote_notif_process for
6662      notification stop, and we have to do this in remote_wait_ns
6663      instead.  If we fetch all queued events from stub, remote stub
6664      may exit and we have no chance to process them back in
6665      remote_wait_ns.  */
6666   mark_async_event_handler (remote_async_inferior_event_token);
6667   return 0;
6668 }
6669
6670 static void
6671 stop_reply_dtr (struct notif_event *event)
6672 {
6673   struct stop_reply *r = (struct stop_reply *) event;
6674   cached_reg_t *reg;
6675   int ix;
6676
6677   for (ix = 0;
6678        VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6679        ix++)
6680     xfree (reg->data);
6681
6682   VEC_free (cached_reg_t, r->regcache);
6683 }
6684
6685 static struct notif_event *
6686 remote_notif_stop_alloc_reply (void)
6687 {
6688   /* We cast to a pointer to the "base class".  */
6689   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6690
6691   r->dtr = stop_reply_dtr;
6692
6693   return r;
6694 }
6695
6696 /* A client of notification Stop.  */
6697
6698 struct notif_client notif_client_stop =
6699 {
6700   "Stop",
6701   "vStopped",
6702   remote_notif_stop_parse,
6703   remote_notif_stop_ack,
6704   remote_notif_stop_can_get_pending_events,
6705   remote_notif_stop_alloc_reply,
6706   REMOTE_NOTIF_STOP,
6707 };
6708
6709 /* A parameter to pass data in and out.  */
6710
6711 struct queue_iter_param
6712 {
6713   void *input;
6714   struct stop_reply *output;
6715 };
6716
6717 /* Determine if THREAD_PTID is a pending fork parent thread.  ARG contains
6718    the pid of the process that owns the threads we want to check, or
6719    -1 if we want to check all threads.  */
6720
6721 static int
6722 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6723                         ptid_t thread_ptid)
6724 {
6725   if (ws->kind == TARGET_WAITKIND_FORKED
6726       || ws->kind == TARGET_WAITKIND_VFORKED)
6727     {
6728       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6729         return 1;
6730     }
6731
6732   return 0;
6733 }
6734
6735 /* Return the thread's pending status used to determine whether the
6736    thread is a fork parent stopped at a fork event.  */
6737
6738 static struct target_waitstatus *
6739 thread_pending_fork_status (struct thread_info *thread)
6740 {
6741   if (thread->suspend.waitstatus_pending_p)
6742     return &thread->suspend.waitstatus;
6743   else
6744     return &thread->pending_follow;
6745 }
6746
6747 /* Determine if THREAD is a pending fork parent thread.  */
6748
6749 static int
6750 is_pending_fork_parent_thread (struct thread_info *thread)
6751 {
6752   struct target_waitstatus *ws = thread_pending_fork_status (thread);
6753   int pid = -1;
6754
6755   return is_pending_fork_parent (ws, pid, thread->ptid);
6756 }
6757
6758 /* Check whether EVENT is a fork event, and if it is, remove the
6759    fork child from the context list passed in DATA.  */
6760
6761 static int
6762 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6763                               QUEUE_ITER (stop_reply_p) *iter,
6764                               stop_reply_p event,
6765                               void *data)
6766 {
6767   struct queue_iter_param *param = (struct queue_iter_param *) data;
6768   struct threads_listing_context *context
6769     = (struct threads_listing_context *) param->input;
6770
6771   if (event->ws.kind == TARGET_WAITKIND_FORKED
6772       || event->ws.kind == TARGET_WAITKIND_VFORKED
6773       || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6774     context->remove_thread (event->ws.value.related_pid);
6775
6776   return 1;
6777 }
6778
6779 /* If CONTEXT contains any fork child threads that have not been
6780    reported yet, remove them from the CONTEXT list.  If such a
6781    thread exists it is because we are stopped at a fork catchpoint
6782    and have not yet called follow_fork, which will set up the
6783    host-side data structures for the new process.  */
6784
6785 static void
6786 remove_new_fork_children (struct threads_listing_context *context)
6787 {
6788   struct thread_info * thread;
6789   int pid = -1;
6790   struct notif_client *notif = &notif_client_stop;
6791   struct queue_iter_param param;
6792
6793   /* For any threads stopped at a fork event, remove the corresponding
6794      fork child threads from the CONTEXT list.  */
6795   ALL_NON_EXITED_THREADS (thread)
6796     {
6797       struct target_waitstatus *ws = thread_pending_fork_status (thread);
6798
6799       if (is_pending_fork_parent (ws, pid, thread->ptid))
6800         context->remove_thread (ws->value.related_pid);
6801     }
6802
6803   /* Check for any pending fork events (not reported or processed yet)
6804      in process PID and remove those fork child threads from the
6805      CONTEXT list as well.  */
6806   remote_notif_get_pending_events (notif);
6807   param.input = context;
6808   param.output = NULL;
6809   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6810                  remove_child_of_pending_fork, &param);
6811 }
6812
6813 /* Check whether EVENT would prevent a global or process wildcard
6814    vCont action.  */
6815
6816 static int
6817 check_pending_event_prevents_wildcard_vcont_callback
6818   (QUEUE (stop_reply_p) *q,
6819    QUEUE_ITER (stop_reply_p) *iter,
6820    stop_reply_p event,
6821    void *data)
6822 {
6823   struct inferior *inf;
6824   int *may_global_wildcard_vcont = (int *) data;
6825
6826   if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6827       || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6828     return 1;
6829
6830   if (event->ws.kind == TARGET_WAITKIND_FORKED
6831       || event->ws.kind == TARGET_WAITKIND_VFORKED)
6832     *may_global_wildcard_vcont = 0;
6833
6834   inf = find_inferior_ptid (event->ptid);
6835
6836   /* This may be the first time we heard about this process.
6837      Regardless, we must not do a global wildcard resume, otherwise
6838      we'd resume this process too.  */
6839   *may_global_wildcard_vcont = 0;
6840   if (inf != NULL)
6841     get_remote_inferior (inf)->may_wildcard_vcont = false;
6842
6843   return 1;
6844 }
6845
6846 /* Check whether any event pending in the vStopped queue would prevent
6847    a global or process wildcard vCont action.  Clear
6848    *may_global_wildcard if we can't do a global wildcard (vCont;c),
6849    and clear the event inferior's may_wildcard_vcont flag if we can't
6850    do a process-wide wildcard resume (vCont;c:pPID.-1).  */
6851
6852 static void
6853 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6854 {
6855   struct notif_client *notif = &notif_client_stop;
6856
6857   remote_notif_get_pending_events (notif);
6858   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6859                  check_pending_event_prevents_wildcard_vcont_callback,
6860                  may_global_wildcard);
6861 }
6862
6863 /* Remove stop replies in the queue if its pid is equal to the given
6864    inferior's pid.  */
6865
6866 static int
6867 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6868                                 QUEUE_ITER (stop_reply_p) *iter,
6869                                 stop_reply_p event,
6870                                 void *data)
6871 {
6872   struct queue_iter_param *param = (struct queue_iter_param *) data;
6873   struct inferior *inf = (struct inferior *) param->input;
6874
6875   if (ptid_get_pid (event->ptid) == inf->pid)
6876     {
6877       stop_reply_xfree (event);
6878       QUEUE_remove_elem (stop_reply_p, q, iter);
6879     }
6880
6881   return 1;
6882 }
6883
6884 /* Discard all pending stop replies of inferior INF.  */
6885
6886 static void
6887 discard_pending_stop_replies (struct inferior *inf)
6888 {
6889   struct queue_iter_param param;
6890   struct stop_reply *reply;
6891   struct remote_state *rs = get_remote_state ();
6892   struct remote_notif_state *rns = rs->notif_state;
6893
6894   /* This function can be notified when an inferior exists.  When the
6895      target is not remote, the notification state is NULL.  */
6896   if (rs->remote_desc == NULL)
6897     return;
6898
6899   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6900
6901   /* Discard the in-flight notification.  */
6902   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6903     {
6904       stop_reply_xfree (reply);
6905       rns->pending_event[notif_client_stop.id] = NULL;
6906     }
6907
6908   param.input = inf;
6909   param.output = NULL;
6910   /* Discard the stop replies we have already pulled with
6911      vStopped.  */
6912   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6913                  remove_stop_reply_for_inferior, &param);
6914 }
6915
6916 /* If its remote state is equal to the given remote state,
6917    remove EVENT from the stop reply queue.  */
6918
6919 static int
6920 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6921                                    QUEUE_ITER (stop_reply_p) *iter,
6922                                    stop_reply_p event,
6923                                    void *data)
6924 {
6925   struct queue_iter_param *param = (struct queue_iter_param *) data;
6926   struct remote_state *rs = (struct remote_state *) param->input;
6927
6928   if (event->rs == rs)
6929     {
6930       stop_reply_xfree (event);
6931       QUEUE_remove_elem (stop_reply_p, q, iter);
6932     }
6933
6934   return 1;
6935 }
6936
6937 /* Discard the stop replies for RS in stop_reply_queue.  */
6938
6939 static void
6940 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6941 {
6942   struct queue_iter_param param;
6943
6944   param.input = rs;
6945   param.output = NULL;
6946   /* Discard the stop replies we have already pulled with
6947      vStopped.  */
6948   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6949                  remove_stop_reply_of_remote_state, &param);
6950 }
6951
6952 /* A parameter to pass data in and out.  */
6953
6954 static int
6955 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6956                                    QUEUE_ITER (stop_reply_p) *iter,
6957                                    stop_reply_p event,
6958                                    void *data)
6959 {
6960   struct queue_iter_param *param = (struct queue_iter_param *) data;
6961   ptid_t *ptid = (ptid_t *) param->input;
6962
6963   if (ptid_match (event->ptid, *ptid))
6964     {
6965       param->output = event;
6966       QUEUE_remove_elem (stop_reply_p, q, iter);
6967       return 0;
6968     }
6969
6970   return 1;
6971 }
6972
6973 /* Remove the first reply in 'stop_reply_queue' which matches
6974    PTID.  */
6975
6976 static struct stop_reply *
6977 remote_notif_remove_queued_reply (ptid_t ptid)
6978 {
6979   struct queue_iter_param param;
6980
6981   param.input = &ptid;
6982   param.output = NULL;
6983
6984   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6985                  remote_notif_remove_once_on_match, &param);
6986   if (notif_debug)
6987     fprintf_unfiltered (gdb_stdlog,
6988                         "notif: discard queued event: 'Stop' in %s\n",
6989                         target_pid_to_str (ptid));
6990
6991   return param.output;
6992 }
6993
6994 /* Look for a queued stop reply belonging to PTID.  If one is found,
6995    remove it from the queue, and return it.  Returns NULL if none is
6996    found.  If there are still queued events left to process, tell the
6997    event loop to get back to target_wait soon.  */
6998
6999 static struct stop_reply *
7000 queued_stop_reply (ptid_t ptid)
7001 {
7002   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7003
7004   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7005     /* There's still at least an event left.  */
7006     mark_async_event_handler (remote_async_inferior_event_token);
7007
7008   return r;
7009 }
7010
7011 /* Push a fully parsed stop reply in the stop reply queue.  Since we
7012    know that we now have at least one queued event left to pass to the
7013    core side, tell the event loop to get back to target_wait soon.  */
7014
7015 static void
7016 push_stop_reply (struct stop_reply *new_event)
7017 {
7018   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
7019
7020   if (notif_debug)
7021     fprintf_unfiltered (gdb_stdlog,
7022                         "notif: push 'Stop' %s to queue %d\n",
7023                         target_pid_to_str (new_event->ptid),
7024                         QUEUE_length (stop_reply_p,
7025                                       stop_reply_queue));
7026
7027   mark_async_event_handler (remote_async_inferior_event_token);
7028 }
7029
7030 static int
7031 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
7032                               QUEUE_ITER (stop_reply_p) *iter,
7033                               struct stop_reply *event,
7034                               void *data)
7035 {
7036   ptid_t *ptid = (ptid_t *) data;
7037
7038   return !(ptid_equal (*ptid, event->ptid)
7039            && event->ws.kind == TARGET_WAITKIND_STOPPED);
7040 }
7041
7042 /* Returns true if we have a stop reply for PTID.  */
7043
7044 static int
7045 peek_stop_reply (ptid_t ptid)
7046 {
7047   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
7048                          stop_reply_match_ptid_and_ws, &ptid);
7049 }
7050
7051 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
7052    starting with P and ending with PEND matches PREFIX.  */
7053
7054 static int
7055 strprefix (const char *p, const char *pend, const char *prefix)
7056 {
7057   for ( ; p < pend; p++, prefix++)
7058     if (*p != *prefix)
7059       return 0;
7060   return *prefix == '\0';
7061 }
7062
7063 /* Parse the stop reply in BUF.  Either the function succeeds, and the
7064    result is stored in EVENT, or throws an error.  */
7065
7066 static void
7067 remote_parse_stop_reply (char *buf, struct stop_reply *event)
7068 {
7069   remote_arch_state *rsa = NULL;
7070   ULONGEST addr;
7071   const char *p;
7072   int skipregs = 0;
7073
7074   event->ptid = null_ptid;
7075   event->rs = get_remote_state ();
7076   event->ws.kind = TARGET_WAITKIND_IGNORE;
7077   event->ws.value.integer = 0;
7078   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7079   event->regcache = NULL;
7080   event->core = -1;
7081
7082   switch (buf[0])
7083     {
7084     case 'T':           /* Status with PC, SP, FP, ...  */
7085       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
7086       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
7087             ss = signal number
7088             n... = register number
7089             r... = register contents
7090       */
7091
7092       p = &buf[3];      /* after Txx */
7093       while (*p)
7094         {
7095           const char *p1;
7096           int fieldsize;
7097
7098           p1 = strchr (p, ':');
7099           if (p1 == NULL)
7100             error (_("Malformed packet(a) (missing colon): %s\n\
7101 Packet: '%s'\n"),
7102                    p, buf);
7103           if (p == p1)
7104             error (_("Malformed packet(a) (missing register number): %s\n\
7105 Packet: '%s'\n"),
7106                    p, buf);
7107
7108           /* Some "registers" are actually extended stop information.
7109              Note if you're adding a new entry here: GDB 7.9 and
7110              earlier assume that all register "numbers" that start
7111              with an hex digit are real register numbers.  Make sure
7112              the server only sends such a packet if it knows the
7113              client understands it.  */
7114
7115           if (strprefix (p, p1, "thread"))
7116             event->ptid = read_ptid (++p1, &p);
7117           else if (strprefix (p, p1, "syscall_entry"))
7118             {
7119               ULONGEST sysno;
7120
7121               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7122               p = unpack_varlen_hex (++p1, &sysno);
7123               event->ws.value.syscall_number = (int) sysno;
7124             }
7125           else if (strprefix (p, p1, "syscall_return"))
7126             {
7127               ULONGEST sysno;
7128
7129               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7130               p = unpack_varlen_hex (++p1, &sysno);
7131               event->ws.value.syscall_number = (int) sysno;
7132             }
7133           else if (strprefix (p, p1, "watch")
7134                    || strprefix (p, p1, "rwatch")
7135                    || strprefix (p, p1, "awatch"))
7136             {
7137               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7138               p = unpack_varlen_hex (++p1, &addr);
7139               event->watch_data_address = (CORE_ADDR) addr;
7140             }
7141           else if (strprefix (p, p1, "swbreak"))
7142             {
7143               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7144
7145               /* Make sure the stub doesn't forget to indicate support
7146                  with qSupported.  */
7147               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7148                 error (_("Unexpected swbreak stop reason"));
7149
7150               /* The value part is documented as "must be empty",
7151                  though we ignore it, in case we ever decide to make
7152                  use of it in a backward compatible way.  */
7153               p = strchrnul (p1 + 1, ';');
7154             }
7155           else if (strprefix (p, p1, "hwbreak"))
7156             {
7157               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7158
7159               /* Make sure the stub doesn't forget to indicate support
7160                  with qSupported.  */
7161               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7162                 error (_("Unexpected hwbreak stop reason"));
7163
7164               /* See above.  */
7165               p = strchrnul (p1 + 1, ';');
7166             }
7167           else if (strprefix (p, p1, "library"))
7168             {
7169               event->ws.kind = TARGET_WAITKIND_LOADED;
7170               p = strchrnul (p1 + 1, ';');
7171             }
7172           else if (strprefix (p, p1, "replaylog"))
7173             {
7174               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7175               /* p1 will indicate "begin" or "end", but it makes
7176                  no difference for now, so ignore it.  */
7177               p = strchrnul (p1 + 1, ';');
7178             }
7179           else if (strprefix (p, p1, "core"))
7180             {
7181               ULONGEST c;
7182
7183               p = unpack_varlen_hex (++p1, &c);
7184               event->core = c;
7185             }
7186           else if (strprefix (p, p1, "fork"))
7187             {
7188               event->ws.value.related_pid = read_ptid (++p1, &p);
7189               event->ws.kind = TARGET_WAITKIND_FORKED;
7190             }
7191           else if (strprefix (p, p1, "vfork"))
7192             {
7193               event->ws.value.related_pid = read_ptid (++p1, &p);
7194               event->ws.kind = TARGET_WAITKIND_VFORKED;
7195             }
7196           else if (strprefix (p, p1, "vforkdone"))
7197             {
7198               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7199               p = strchrnul (p1 + 1, ';');
7200             }
7201           else if (strprefix (p, p1, "exec"))
7202             {
7203               ULONGEST ignored;
7204               char pathname[PATH_MAX];
7205               int pathlen;
7206
7207               /* Determine the length of the execd pathname.  */
7208               p = unpack_varlen_hex (++p1, &ignored);
7209               pathlen = (p - p1) / 2;
7210
7211               /* Save the pathname for event reporting and for
7212                  the next run command.  */
7213               hex2bin (p1, (gdb_byte *) pathname, pathlen);
7214               pathname[pathlen] = '\0';
7215
7216               /* This is freed during event handling.  */
7217               event->ws.value.execd_pathname = xstrdup (pathname);
7218               event->ws.kind = TARGET_WAITKIND_EXECD;
7219
7220               /* Skip the registers included in this packet, since
7221                  they may be for an architecture different from the
7222                  one used by the original program.  */
7223               skipregs = 1;
7224             }
7225           else if (strprefix (p, p1, "create"))
7226             {
7227               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7228               p = strchrnul (p1 + 1, ';');
7229             }
7230           else
7231             {
7232               ULONGEST pnum;
7233               const char *p_temp;
7234
7235               if (skipregs)
7236                 {
7237                   p = strchrnul (p1 + 1, ';');
7238                   p++;
7239                   continue;
7240                 }
7241
7242               /* Maybe a real ``P'' register number.  */
7243               p_temp = unpack_varlen_hex (p, &pnum);
7244               /* If the first invalid character is the colon, we got a
7245                  register number.  Otherwise, it's an unknown stop
7246                  reason.  */
7247               if (p_temp == p1)
7248                 {
7249                   /* If we haven't parsed the event's thread yet, find
7250                      it now, in order to find the architecture of the
7251                      reported expedited registers.  */
7252                   if (event->ptid == null_ptid)
7253                     {
7254                       const char *thr = strstr (p1 + 1, ";thread:");
7255                       if (thr != NULL)
7256                         event->ptid = read_ptid (thr + strlen (";thread:"),
7257                                                  NULL);
7258                       else
7259                         {
7260                           /* Either the current thread hasn't changed,
7261                              or the inferior is not multi-threaded.
7262                              The event must be for the thread we last
7263                              set as (or learned as being) current.  */
7264                           event->ptid = event->rs->general_thread;
7265                         }
7266                     }
7267
7268                   if (rsa == NULL)
7269                     {
7270                       inferior *inf = (event->ptid == null_ptid
7271                                        ? NULL
7272                                        : find_inferior_ptid (event->ptid));
7273                       /* If this is the first time we learn anything
7274                          about this process, skip the registers
7275                          included in this packet, since we don't yet
7276                          know which architecture to use to parse them.
7277                          We'll determine the architecture later when
7278                          we process the stop reply and retrieve the
7279                          target description, via
7280                          remote_notice_new_inferior ->
7281                          post_create_inferior.  */
7282                       if (inf == NULL)
7283                         {
7284                           p = strchrnul (p1 + 1, ';');
7285                           p++;
7286                           continue;
7287                         }
7288
7289                       event->arch = inf->gdbarch;
7290                       rsa = event->rs->get_remote_arch_state (event->arch);
7291                     }
7292
7293                   packet_reg *reg
7294                     = packet_reg_from_pnum (event->arch, rsa, pnum);
7295                   cached_reg_t cached_reg;
7296
7297                   if (reg == NULL)
7298                     error (_("Remote sent bad register number %s: %s\n\
7299 Packet: '%s'\n"),
7300                            hex_string (pnum), p, buf);
7301
7302                   cached_reg.num = reg->regnum;
7303                   cached_reg.data = (gdb_byte *)
7304                     xmalloc (register_size (event->arch, reg->regnum));
7305
7306                   p = p1 + 1;
7307                   fieldsize = hex2bin (p, cached_reg.data,
7308                                        register_size (event->arch, reg->regnum));
7309                   p += 2 * fieldsize;
7310                   if (fieldsize < register_size (event->arch, reg->regnum))
7311                     warning (_("Remote reply is too short: %s"), buf);
7312
7313                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7314                 }
7315               else
7316                 {
7317                   /* Not a number.  Silently skip unknown optional
7318                      info.  */
7319                   p = strchrnul (p1 + 1, ';');
7320                 }
7321             }
7322
7323           if (*p != ';')
7324             error (_("Remote register badly formatted: %s\nhere: %s"),
7325                    buf, p);
7326           ++p;
7327         }
7328
7329       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7330         break;
7331
7332       /* fall through */
7333     case 'S':           /* Old style status, just signal only.  */
7334       {
7335         int sig;
7336
7337         event->ws.kind = TARGET_WAITKIND_STOPPED;
7338         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7339         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7340           event->ws.value.sig = (enum gdb_signal) sig;
7341         else
7342           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7343       }
7344       break;
7345     case 'w':           /* Thread exited.  */
7346       {
7347         const char *p;
7348         ULONGEST value;
7349
7350         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7351         p = unpack_varlen_hex (&buf[1], &value);
7352         event->ws.value.integer = value;
7353         if (*p != ';')
7354           error (_("stop reply packet badly formatted: %s"), buf);
7355         event->ptid = read_ptid (++p, NULL);
7356         break;
7357       }
7358     case 'W':           /* Target exited.  */
7359     case 'X':
7360       {
7361         const char *p;
7362         int pid;
7363         ULONGEST value;
7364
7365         /* GDB used to accept only 2 hex chars here.  Stubs should
7366            only send more if they detect GDB supports multi-process
7367            support.  */
7368         p = unpack_varlen_hex (&buf[1], &value);
7369
7370         if (buf[0] == 'W')
7371           {
7372             /* The remote process exited.  */
7373             event->ws.kind = TARGET_WAITKIND_EXITED;
7374             event->ws.value.integer = value;
7375           }
7376         else
7377           {
7378             /* The remote process exited with a signal.  */
7379             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7380             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7381               event->ws.value.sig = (enum gdb_signal) value;
7382             else
7383               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7384           }
7385
7386         /* If no process is specified, assume inferior_ptid.  */
7387         pid = ptid_get_pid (inferior_ptid);
7388         if (*p == '\0')
7389           ;
7390         else if (*p == ';')
7391           {
7392             p++;
7393
7394             if (*p == '\0')
7395               ;
7396             else if (startswith (p, "process:"))
7397               {
7398                 ULONGEST upid;
7399
7400                 p += sizeof ("process:") - 1;
7401                 unpack_varlen_hex (p, &upid);
7402                 pid = upid;
7403               }
7404             else
7405               error (_("unknown stop reply packet: %s"), buf);
7406           }
7407         else
7408           error (_("unknown stop reply packet: %s"), buf);
7409         event->ptid = pid_to_ptid (pid);
7410       }
7411       break;
7412     case 'N':
7413       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7414       event->ptid = minus_one_ptid;
7415       break;
7416     }
7417
7418   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7419     error (_("No process or thread specified in stop reply: %s"), buf);
7420 }
7421
7422 /* When the stub wants to tell GDB about a new notification reply, it
7423    sends a notification (%Stop, for example).  Those can come it at
7424    any time, hence, we have to make sure that any pending
7425    putpkt/getpkt sequence we're making is finished, before querying
7426    the stub for more events with the corresponding ack command
7427    (vStopped, for example).  E.g., if we started a vStopped sequence
7428    immediately upon receiving the notification, something like this
7429    could happen:
7430
7431     1.1) --> Hg 1
7432     1.2) <-- OK
7433     1.3) --> g
7434     1.4) <-- %Stop
7435     1.5) --> vStopped
7436     1.6) <-- (registers reply to step #1.3)
7437
7438    Obviously, the reply in step #1.6 would be unexpected to a vStopped
7439    query.
7440
7441    To solve this, whenever we parse a %Stop notification successfully,
7442    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7443    doing whatever we were doing:
7444
7445     2.1) --> Hg 1
7446     2.2) <-- OK
7447     2.3) --> g
7448     2.4) <-- %Stop
7449       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7450     2.5) <-- (registers reply to step #2.3)
7451
7452    Eventualy after step #2.5, we return to the event loop, which
7453    notices there's an event on the
7454    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7455    associated callback --- the function below.  At this point, we're
7456    always safe to start a vStopped sequence. :
7457
7458     2.6) --> vStopped
7459     2.7) <-- T05 thread:2
7460     2.8) --> vStopped
7461     2.9) --> OK
7462 */
7463
7464 void
7465 remote_notif_get_pending_events (struct notif_client *nc)
7466 {
7467   struct remote_state *rs = get_remote_state ();
7468
7469   if (rs->notif_state->pending_event[nc->id] != NULL)
7470     {
7471       if (notif_debug)
7472         fprintf_unfiltered (gdb_stdlog,
7473                             "notif: process: '%s' ack pending event\n",
7474                             nc->name);
7475
7476       /* acknowledge */
7477       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7478       rs->notif_state->pending_event[nc->id] = NULL;
7479
7480       while (1)
7481         {
7482           getpkt (&rs->buf, &rs->buf_size, 0);
7483           if (strcmp (rs->buf, "OK") == 0)
7484             break;
7485           else
7486             remote_notif_ack (nc, rs->buf);
7487         }
7488     }
7489   else
7490     {
7491       if (notif_debug)
7492         fprintf_unfiltered (gdb_stdlog,
7493                             "notif: process: '%s' no pending reply\n",
7494                             nc->name);
7495     }
7496 }
7497
7498 /* Called when it is decided that STOP_REPLY holds the info of the
7499    event that is to be returned to the core.  This function always
7500    destroys STOP_REPLY.  */
7501
7502 static ptid_t
7503 process_stop_reply (struct stop_reply *stop_reply,
7504                     struct target_waitstatus *status)
7505 {
7506   ptid_t ptid;
7507
7508   *status = stop_reply->ws;
7509   ptid = stop_reply->ptid;
7510
7511   /* If no thread/process was reported by the stub, assume the current
7512      inferior.  */
7513   if (ptid_equal (ptid, null_ptid))
7514     ptid = inferior_ptid;
7515
7516   if (status->kind != TARGET_WAITKIND_EXITED
7517       && status->kind != TARGET_WAITKIND_SIGNALLED
7518       && status->kind != TARGET_WAITKIND_NO_RESUMED)
7519     {
7520       /* Expedited registers.  */
7521       if (stop_reply->regcache)
7522         {
7523           struct regcache *regcache
7524             = get_thread_arch_regcache (ptid, stop_reply->arch);
7525           cached_reg_t *reg;
7526           int ix;
7527
7528           for (ix = 0;
7529                VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7530                ix++)
7531           {
7532             regcache_raw_supply (regcache, reg->num, reg->data);
7533             xfree (reg->data);
7534           }
7535
7536           VEC_free (cached_reg_t, stop_reply->regcache);
7537         }
7538
7539       remote_notice_new_inferior (ptid, 0);
7540       remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7541       remote_thr->core = stop_reply->core;
7542       remote_thr->stop_reason = stop_reply->stop_reason;
7543       remote_thr->watch_data_address = stop_reply->watch_data_address;
7544       remote_thr->vcont_resumed = 0;
7545     }
7546
7547   stop_reply_xfree (stop_reply);
7548   return ptid;
7549 }
7550
7551 /* The non-stop mode version of target_wait.  */
7552
7553 static ptid_t
7554 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7555 {
7556   struct remote_state *rs = get_remote_state ();
7557   struct stop_reply *stop_reply;
7558   int ret;
7559   int is_notif = 0;
7560
7561   /* If in non-stop mode, get out of getpkt even if a
7562      notification is received.  */
7563
7564   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7565                               0 /* forever */, &is_notif);
7566   while (1)
7567     {
7568       if (ret != -1 && !is_notif)
7569         switch (rs->buf[0])
7570           {
7571           case 'E':             /* Error of some sort.  */
7572             /* We're out of sync with the target now.  Did it continue
7573                or not?  We can't tell which thread it was in non-stop,
7574                so just ignore this.  */
7575             warning (_("Remote failure reply: %s"), rs->buf);
7576             break;
7577           case 'O':             /* Console output.  */
7578             remote_console_output (rs->buf + 1);
7579             break;
7580           default:
7581             warning (_("Invalid remote reply: %s"), rs->buf);
7582             break;
7583           }
7584
7585       /* Acknowledge a pending stop reply that may have arrived in the
7586          mean time.  */
7587       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7588         remote_notif_get_pending_events (&notif_client_stop);
7589
7590       /* If indeed we noticed a stop reply, we're done.  */
7591       stop_reply = queued_stop_reply (ptid);
7592       if (stop_reply != NULL)
7593         return process_stop_reply (stop_reply, status);
7594
7595       /* Still no event.  If we're just polling for an event, then
7596          return to the event loop.  */
7597       if (options & TARGET_WNOHANG)
7598         {
7599           status->kind = TARGET_WAITKIND_IGNORE;
7600           return minus_one_ptid;
7601         }
7602
7603       /* Otherwise do a blocking wait.  */
7604       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7605                                   1 /* forever */, &is_notif);
7606     }
7607 }
7608
7609 /* Wait until the remote machine stops, then return, storing status in
7610    STATUS just as `wait' would.  */
7611
7612 static ptid_t
7613 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7614 {
7615   struct remote_state *rs = get_remote_state ();
7616   ptid_t event_ptid = null_ptid;
7617   char *buf;
7618   struct stop_reply *stop_reply;
7619
7620  again:
7621
7622   status->kind = TARGET_WAITKIND_IGNORE;
7623   status->value.integer = 0;
7624
7625   stop_reply = queued_stop_reply (ptid);
7626   if (stop_reply != NULL)
7627     return process_stop_reply (stop_reply, status);
7628
7629   if (rs->cached_wait_status)
7630     /* Use the cached wait status, but only once.  */
7631     rs->cached_wait_status = 0;
7632   else
7633     {
7634       int ret;
7635       int is_notif;
7636       int forever = ((options & TARGET_WNOHANG) == 0
7637                      && wait_forever_enabled_p);
7638
7639       if (!rs->waiting_for_stop_reply)
7640         {
7641           status->kind = TARGET_WAITKIND_NO_RESUMED;
7642           return minus_one_ptid;
7643         }
7644
7645       /* FIXME: cagney/1999-09-27: If we're in async mode we should
7646          _never_ wait for ever -> test on target_is_async_p().
7647          However, before we do that we need to ensure that the caller
7648          knows how to take the target into/out of async mode.  */
7649       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7650                                   forever, &is_notif);
7651
7652       /* GDB gets a notification.  Return to core as this event is
7653          not interesting.  */
7654       if (ret != -1 && is_notif)
7655         return minus_one_ptid;
7656
7657       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7658         return minus_one_ptid;
7659     }
7660
7661   buf = rs->buf;
7662
7663   /* Assume that the target has acknowledged Ctrl-C unless we receive
7664      an 'F' or 'O' packet.  */
7665   if (buf[0] != 'F' && buf[0] != 'O')
7666     rs->ctrlc_pending_p = 0;
7667
7668   switch (buf[0])
7669     {
7670     case 'E':           /* Error of some sort.  */
7671       /* We're out of sync with the target now.  Did it continue or
7672          not?  Not is more likely, so report a stop.  */
7673       rs->waiting_for_stop_reply = 0;
7674
7675       warning (_("Remote failure reply: %s"), buf);
7676       status->kind = TARGET_WAITKIND_STOPPED;
7677       status->value.sig = GDB_SIGNAL_0;
7678       break;
7679     case 'F':           /* File-I/O request.  */
7680       /* GDB may access the inferior memory while handling the File-I/O
7681          request, but we don't want GDB accessing memory while waiting
7682          for a stop reply.  See the comments in putpkt_binary.  Set
7683          waiting_for_stop_reply to 0 temporarily.  */
7684       rs->waiting_for_stop_reply = 0;
7685       remote_fileio_request (buf, rs->ctrlc_pending_p);
7686       rs->ctrlc_pending_p = 0;
7687       /* GDB handled the File-I/O request, and the target is running
7688          again.  Keep waiting for events.  */
7689       rs->waiting_for_stop_reply = 1;
7690       break;
7691     case 'N': case 'T': case 'S': case 'X': case 'W':
7692       {
7693         struct stop_reply *stop_reply;
7694
7695         /* There is a stop reply to handle.  */
7696         rs->waiting_for_stop_reply = 0;
7697
7698         stop_reply
7699           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7700                                                       rs->buf);
7701
7702         event_ptid = process_stop_reply (stop_reply, status);
7703         break;
7704       }
7705     case 'O':           /* Console output.  */
7706       remote_console_output (buf + 1);
7707       break;
7708     case '\0':
7709       if (rs->last_sent_signal != GDB_SIGNAL_0)
7710         {
7711           /* Zero length reply means that we tried 'S' or 'C' and the
7712              remote system doesn't support it.  */
7713           target_terminal::ours_for_output ();
7714           printf_filtered
7715             ("Can't send signals to this remote system.  %s not sent.\n",
7716              gdb_signal_to_name (rs->last_sent_signal));
7717           rs->last_sent_signal = GDB_SIGNAL_0;
7718           target_terminal::inferior ();
7719
7720           strcpy (buf, rs->last_sent_step ? "s" : "c");
7721           putpkt (buf);
7722           break;
7723         }
7724       /* fallthrough */
7725     default:
7726       warning (_("Invalid remote reply: %s"), buf);
7727       break;
7728     }
7729
7730   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7731     return minus_one_ptid;
7732   else if (status->kind == TARGET_WAITKIND_IGNORE)
7733     {
7734       /* Nothing interesting happened.  If we're doing a non-blocking
7735          poll, we're done.  Otherwise, go back to waiting.  */
7736       if (options & TARGET_WNOHANG)
7737         return minus_one_ptid;
7738       else
7739         goto again;
7740     }
7741   else if (status->kind != TARGET_WAITKIND_EXITED
7742            && status->kind != TARGET_WAITKIND_SIGNALLED)
7743     {
7744       if (!ptid_equal (event_ptid, null_ptid))
7745         record_currthread (rs, event_ptid);
7746       else
7747         event_ptid = inferior_ptid;
7748     }
7749   else
7750     /* A process exit.  Invalidate our notion of current thread.  */
7751     record_currthread (rs, minus_one_ptid);
7752
7753   return event_ptid;
7754 }
7755
7756 /* Wait until the remote machine stops, then return, storing status in
7757    STATUS just as `wait' would.  */
7758
7759 ptid_t
7760 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7761 {
7762   ptid_t event_ptid;
7763
7764   if (target_is_non_stop_p ())
7765     event_ptid = remote_wait_ns (ptid, status, options);
7766   else
7767     event_ptid = remote_wait_as (ptid, status, options);
7768
7769   if (target_is_async_p ())
7770     {
7771       /* If there are are events left in the queue tell the event loop
7772          to return here.  */
7773       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7774         mark_async_event_handler (remote_async_inferior_event_token);
7775     }
7776
7777   return event_ptid;
7778 }
7779
7780 /* Fetch a single register using a 'p' packet.  */
7781
7782 static int
7783 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7784 {
7785   struct gdbarch *gdbarch = regcache->arch ();
7786   struct remote_state *rs = get_remote_state ();
7787   char *buf, *p;
7788   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7789   int i;
7790
7791   if (packet_support (PACKET_p) == PACKET_DISABLE)
7792     return 0;
7793
7794   if (reg->pnum == -1)
7795     return 0;
7796
7797   p = rs->buf;
7798   *p++ = 'p';
7799   p += hexnumstr (p, reg->pnum);
7800   *p++ = '\0';
7801   putpkt (rs->buf);
7802   getpkt (&rs->buf, &rs->buf_size, 0);
7803
7804   buf = rs->buf;
7805
7806   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7807     {
7808     case PACKET_OK:
7809       break;
7810     case PACKET_UNKNOWN:
7811       return 0;
7812     case PACKET_ERROR:
7813       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7814              gdbarch_register_name (regcache->arch (), 
7815                                     reg->regnum), 
7816              buf);
7817     }
7818
7819   /* If this register is unfetchable, tell the regcache.  */
7820   if (buf[0] == 'x')
7821     {
7822       regcache_raw_supply (regcache, reg->regnum, NULL);
7823       return 1;
7824     }
7825
7826   /* Otherwise, parse and supply the value.  */
7827   p = buf;
7828   i = 0;
7829   while (p[0] != 0)
7830     {
7831       if (p[1] == 0)
7832         error (_("fetch_register_using_p: early buf termination"));
7833
7834       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7835       p += 2;
7836     }
7837   regcache_raw_supply (regcache, reg->regnum, regp);
7838   return 1;
7839 }
7840
7841 /* Fetch the registers included in the target's 'g' packet.  */
7842
7843 static int
7844 send_g_packet (void)
7845 {
7846   struct remote_state *rs = get_remote_state ();
7847   int buf_len;
7848
7849   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7850   putpkt (rs->buf);
7851   getpkt (&rs->buf, &rs->buf_size, 0);
7852   if (packet_check_result (rs->buf) == PACKET_ERROR)
7853     error (_("Could not read registers; remote failure reply '%s'"),
7854            rs->buf);
7855
7856   /* We can get out of synch in various cases.  If the first character
7857      in the buffer is not a hex character, assume that has happened
7858      and try to fetch another packet to read.  */
7859   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7860          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7861          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7862          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
7863     {
7864       if (remote_debug)
7865         fprintf_unfiltered (gdb_stdlog,
7866                             "Bad register packet; fetching a new packet\n");
7867       getpkt (&rs->buf, &rs->buf_size, 0);
7868     }
7869
7870   buf_len = strlen (rs->buf);
7871
7872   /* Sanity check the received packet.  */
7873   if (buf_len % 2 != 0)
7874     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7875
7876   return buf_len / 2;
7877 }
7878
7879 static void
7880 process_g_packet (struct regcache *regcache)
7881 {
7882   struct gdbarch *gdbarch = regcache->arch ();
7883   struct remote_state *rs = get_remote_state ();
7884   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
7885   int i, buf_len;
7886   char *p;
7887   char *regs;
7888
7889   buf_len = strlen (rs->buf);
7890
7891   /* Further sanity checks, with knowledge of the architecture.  */
7892   if (buf_len > 2 * rsa->sizeof_g_packet)
7893     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7894              "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7895
7896   /* Save the size of the packet sent to us by the target.  It is used
7897      as a heuristic when determining the max size of packets that the
7898      target can safely receive.  */
7899   if (rsa->actual_register_packet_size == 0)
7900     rsa->actual_register_packet_size = buf_len;
7901
7902   /* If this is smaller than we guessed the 'g' packet would be,
7903      update our records.  A 'g' reply that doesn't include a register's
7904      value implies either that the register is not available, or that
7905      the 'p' packet must be used.  */
7906   if (buf_len < 2 * rsa->sizeof_g_packet)
7907     {
7908       long sizeof_g_packet = buf_len / 2;
7909
7910       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7911         {
7912           long offset = rsa->regs[i].offset;
7913           long reg_size = register_size (gdbarch, i);
7914
7915           if (rsa->regs[i].pnum == -1)
7916             continue;
7917
7918           if (offset >= sizeof_g_packet)
7919             rsa->regs[i].in_g_packet = 0;
7920           else if (offset + reg_size > sizeof_g_packet)
7921             error (_("Truncated register %d in remote 'g' packet"), i);
7922           else
7923             rsa->regs[i].in_g_packet = 1;
7924         }
7925
7926       /* Looks valid enough, we can assume this is the correct length
7927          for a 'g' packet.  It's important not to adjust
7928          rsa->sizeof_g_packet if we have truncated registers otherwise
7929          this "if" won't be run the next time the method is called
7930          with a packet of the same size and one of the internal errors
7931          below will trigger instead.  */
7932       rsa->sizeof_g_packet = sizeof_g_packet;
7933     }
7934
7935   regs = (char *) alloca (rsa->sizeof_g_packet);
7936
7937   /* Unimplemented registers read as all bits zero.  */
7938   memset (regs, 0, rsa->sizeof_g_packet);
7939
7940   /* Reply describes registers byte by byte, each byte encoded as two
7941      hex characters.  Suck them all up, then supply them to the
7942      register cacheing/storage mechanism.  */
7943
7944   p = rs->buf;
7945   for (i = 0; i < rsa->sizeof_g_packet; i++)
7946     {
7947       if (p[0] == 0 || p[1] == 0)
7948         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
7949         internal_error (__FILE__, __LINE__,
7950                         _("unexpected end of 'g' packet reply"));
7951
7952       if (p[0] == 'x' && p[1] == 'x')
7953         regs[i] = 0;            /* 'x' */
7954       else
7955         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7956       p += 2;
7957     }
7958
7959   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7960     {
7961       struct packet_reg *r = &rsa->regs[i];
7962       long reg_size = register_size (gdbarch, i);
7963
7964       if (r->in_g_packet)
7965         {
7966           if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7967             /* This shouldn't happen - we adjusted in_g_packet above.  */
7968             internal_error (__FILE__, __LINE__,
7969                             _("unexpected end of 'g' packet reply"));
7970           else if (rs->buf[r->offset * 2] == 'x')
7971             {
7972               gdb_assert (r->offset * 2 < strlen (rs->buf));
7973               /* The register isn't available, mark it as such (at
7974                  the same time setting the value to zero).  */
7975               regcache_raw_supply (regcache, r->regnum, NULL);
7976             }
7977           else
7978             regcache_raw_supply (regcache, r->regnum,
7979                                  regs + r->offset);
7980         }
7981     }
7982 }
7983
7984 static void
7985 fetch_registers_using_g (struct regcache *regcache)
7986 {
7987   send_g_packet ();
7988   process_g_packet (regcache);
7989 }
7990
7991 /* Make the remote selected traceframe match GDB's selected
7992    traceframe.  */
7993
7994 static void
7995 set_remote_traceframe (void)
7996 {
7997   int newnum;
7998   struct remote_state *rs = get_remote_state ();
7999
8000   if (rs->remote_traceframe_number == get_traceframe_number ())
8001     return;
8002
8003   /* Avoid recursion, remote_trace_find calls us again.  */
8004   rs->remote_traceframe_number = get_traceframe_number ();
8005
8006   newnum = target_trace_find (tfind_number,
8007                               get_traceframe_number (), 0, 0, NULL);
8008
8009   /* Should not happen.  If it does, all bets are off.  */
8010   if (newnum != get_traceframe_number ())
8011     warning (_("could not set remote traceframe"));
8012 }
8013
8014 void
8015 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8016 {
8017   struct gdbarch *gdbarch = regcache->arch ();
8018   struct remote_state *rs = get_remote_state ();
8019   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8020   int i;
8021
8022   set_remote_traceframe ();
8023   set_general_thread (regcache_get_ptid (regcache));
8024
8025   if (regnum >= 0)
8026     {
8027       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8028
8029       gdb_assert (reg != NULL);
8030
8031       /* If this register might be in the 'g' packet, try that first -
8032          we are likely to read more than one register.  If this is the
8033          first 'g' packet, we might be overly optimistic about its
8034          contents, so fall back to 'p'.  */
8035       if (reg->in_g_packet)
8036         {
8037           fetch_registers_using_g (regcache);
8038           if (reg->in_g_packet)
8039             return;
8040         }
8041
8042       if (fetch_register_using_p (regcache, reg))
8043         return;
8044
8045       /* This register is not available.  */
8046       regcache_raw_supply (regcache, reg->regnum, NULL);
8047
8048       return;
8049     }
8050
8051   fetch_registers_using_g (regcache);
8052
8053   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8054     if (!rsa->regs[i].in_g_packet)
8055       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8056         {
8057           /* This register is not available.  */
8058           regcache_raw_supply (regcache, i, NULL);
8059         }
8060 }
8061
8062 /* Prepare to store registers.  Since we may send them all (using a
8063    'G' request), we have to read out the ones we don't want to change
8064    first.  */
8065
8066 void
8067 remote_target::prepare_to_store (struct regcache *regcache)
8068 {
8069   struct remote_state *rs = get_remote_state ();
8070   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8071   int i;
8072
8073   /* Make sure the entire registers array is valid.  */
8074   switch (packet_support (PACKET_P))
8075     {
8076     case PACKET_DISABLE:
8077     case PACKET_SUPPORT_UNKNOWN:
8078       /* Make sure all the necessary registers are cached.  */
8079       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8080         if (rsa->regs[i].in_g_packet)
8081           regcache_raw_update (regcache, rsa->regs[i].regnum);
8082       break;
8083     case PACKET_ENABLE:
8084       break;
8085     }
8086 }
8087
8088 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
8089    packet was not recognized.  */
8090
8091 static int
8092 store_register_using_P (const struct regcache *regcache, 
8093                         struct packet_reg *reg)
8094 {
8095   struct gdbarch *gdbarch = regcache->arch ();
8096   struct remote_state *rs = get_remote_state ();
8097   /* Try storing a single register.  */
8098   char *buf = rs->buf;
8099   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8100   char *p;
8101
8102   if (packet_support (PACKET_P) == PACKET_DISABLE)
8103     return 0;
8104
8105   if (reg->pnum == -1)
8106     return 0;
8107
8108   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8109   p = buf + strlen (buf);
8110   regcache_raw_collect (regcache, reg->regnum, regp);
8111   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8112   putpkt (rs->buf);
8113   getpkt (&rs->buf, &rs->buf_size, 0);
8114
8115   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8116     {
8117     case PACKET_OK:
8118       return 1;
8119     case PACKET_ERROR:
8120       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8121              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8122     case PACKET_UNKNOWN:
8123       return 0;
8124     default:
8125       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8126     }
8127 }
8128
8129 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8130    contents of the register cache buffer.  FIXME: ignores errors.  */
8131
8132 static void
8133 store_registers_using_G (const struct regcache *regcache)
8134 {
8135   struct remote_state *rs = get_remote_state ();
8136   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8137   gdb_byte *regs;
8138   char *p;
8139
8140   /* Extract all the registers in the regcache copying them into a
8141      local buffer.  */
8142   {
8143     int i;
8144
8145     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8146     memset (regs, 0, rsa->sizeof_g_packet);
8147     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8148       {
8149         struct packet_reg *r = &rsa->regs[i];
8150
8151         if (r->in_g_packet)
8152           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
8153       }
8154   }
8155
8156   /* Command describes registers byte by byte,
8157      each byte encoded as two hex characters.  */
8158   p = rs->buf;
8159   *p++ = 'G';
8160   bin2hex (regs, p, rsa->sizeof_g_packet);
8161   putpkt (rs->buf);
8162   getpkt (&rs->buf, &rs->buf_size, 0);
8163   if (packet_check_result (rs->buf) == PACKET_ERROR)
8164     error (_("Could not write registers; remote failure reply '%s'"), 
8165            rs->buf);
8166 }
8167
8168 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8169    of the register cache buffer.  FIXME: ignores errors.  */
8170
8171 void
8172 remote_target::store_registers (struct regcache *regcache, int regnum)
8173 {
8174   struct gdbarch *gdbarch = regcache->arch ();
8175   struct remote_state *rs = get_remote_state ();
8176   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8177   int i;
8178
8179   set_remote_traceframe ();
8180   set_general_thread (regcache_get_ptid (regcache));
8181
8182   if (regnum >= 0)
8183     {
8184       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8185
8186       gdb_assert (reg != NULL);
8187
8188       /* Always prefer to store registers using the 'P' packet if
8189          possible; we often change only a small number of registers.
8190          Sometimes we change a larger number; we'd need help from a
8191          higher layer to know to use 'G'.  */
8192       if (store_register_using_P (regcache, reg))
8193         return;
8194
8195       /* For now, don't complain if we have no way to write the
8196          register.  GDB loses track of unavailable registers too
8197          easily.  Some day, this may be an error.  We don't have
8198          any way to read the register, either...  */
8199       if (!reg->in_g_packet)
8200         return;
8201
8202       store_registers_using_G (regcache);
8203       return;
8204     }
8205
8206   store_registers_using_G (regcache);
8207
8208   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8209     if (!rsa->regs[i].in_g_packet)
8210       if (!store_register_using_P (regcache, &rsa->regs[i]))
8211         /* See above for why we do not issue an error here.  */
8212         continue;
8213 }
8214 \f
8215
8216 /* Return the number of hex digits in num.  */
8217
8218 static int
8219 hexnumlen (ULONGEST num)
8220 {
8221   int i;
8222
8223   for (i = 0; num != 0; i++)
8224     num >>= 4;
8225
8226   return std::max (i, 1);
8227 }
8228
8229 /* Set BUF to the minimum number of hex digits representing NUM.  */
8230
8231 static int
8232 hexnumstr (char *buf, ULONGEST num)
8233 {
8234   int len = hexnumlen (num);
8235
8236   return hexnumnstr (buf, num, len);
8237 }
8238
8239
8240 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
8241
8242 static int
8243 hexnumnstr (char *buf, ULONGEST num, int width)
8244 {
8245   int i;
8246
8247   buf[width] = '\0';
8248
8249   for (i = width - 1; i >= 0; i--)
8250     {
8251       buf[i] = "0123456789abcdef"[(num & 0xf)];
8252       num >>= 4;
8253     }
8254
8255   return width;
8256 }
8257
8258 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
8259
8260 static CORE_ADDR
8261 remote_address_masked (CORE_ADDR addr)
8262 {
8263   unsigned int address_size = remote_address_size;
8264
8265   /* If "remoteaddresssize" was not set, default to target address size.  */
8266   if (!address_size)
8267     address_size = gdbarch_addr_bit (target_gdbarch ());
8268
8269   if (address_size > 0
8270       && address_size < (sizeof (ULONGEST) * 8))
8271     {
8272       /* Only create a mask when that mask can safely be constructed
8273          in a ULONGEST variable.  */
8274       ULONGEST mask = 1;
8275
8276       mask = (mask << address_size) - 1;
8277       addr &= mask;
8278     }
8279   return addr;
8280 }
8281
8282 /* Determine whether the remote target supports binary downloading.
8283    This is accomplished by sending a no-op memory write of zero length
8284    to the target at the specified address. It does not suffice to send
8285    the whole packet, since many stubs strip the eighth bit and
8286    subsequently compute a wrong checksum, which causes real havoc with
8287    remote_write_bytes.
8288
8289    NOTE: This can still lose if the serial line is not eight-bit
8290    clean.  In cases like this, the user should clear "remote
8291    X-packet".  */
8292
8293 static void
8294 check_binary_download (CORE_ADDR addr)
8295 {
8296   struct remote_state *rs = get_remote_state ();
8297
8298   switch (packet_support (PACKET_X))
8299     {
8300     case PACKET_DISABLE:
8301       break;
8302     case PACKET_ENABLE:
8303       break;
8304     case PACKET_SUPPORT_UNKNOWN:
8305       {
8306         char *p;
8307
8308         p = rs->buf;
8309         *p++ = 'X';
8310         p += hexnumstr (p, (ULONGEST) addr);
8311         *p++ = ',';
8312         p += hexnumstr (p, (ULONGEST) 0);
8313         *p++ = ':';
8314         *p = '\0';
8315
8316         putpkt_binary (rs->buf, (int) (p - rs->buf));
8317         getpkt (&rs->buf, &rs->buf_size, 0);
8318
8319         if (rs->buf[0] == '\0')
8320           {
8321             if (remote_debug)
8322               fprintf_unfiltered (gdb_stdlog,
8323                                   "binary downloading NOT "
8324                                   "supported by target\n");
8325             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8326           }
8327         else
8328           {
8329             if (remote_debug)
8330               fprintf_unfiltered (gdb_stdlog,
8331                                   "binary downloading supported by target\n");
8332             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8333           }
8334         break;
8335       }
8336     }
8337 }
8338
8339 /* Helper function to resize the payload in order to try to get a good
8340    alignment.  We try to write an amount of data such that the next write will
8341    start on an address aligned on REMOTE_ALIGN_WRITES.  */
8342
8343 static int
8344 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8345 {
8346   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8347 }
8348
8349 /* Write memory data directly to the remote machine.
8350    This does not inform the data cache; the data cache uses this.
8351    HEADER is the starting part of the packet.
8352    MEMADDR is the address in the remote memory space.
8353    MYADDR is the address of the buffer in our space.
8354    LEN_UNITS is the number of addressable units to write.
8355    UNIT_SIZE is the length in bytes of an addressable unit.
8356    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8357    should send data as binary ('X'), or hex-encoded ('M').
8358
8359    The function creates packet of the form
8360        <HEADER><ADDRESS>,<LENGTH>:<DATA>
8361
8362    where encoding of <DATA> is terminated by PACKET_FORMAT.
8363
8364    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8365    are omitted.
8366
8367    Return the transferred status, error or OK (an
8368    'enum target_xfer_status' value).  Save the number of addressable units
8369    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
8370
8371    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8372    exchange between gdb and the stub could look like (?? in place of the
8373    checksum):
8374
8375    -> $m1000,4#??
8376    <- aaaabbbbccccdddd
8377
8378    -> $M1000,3:eeeeffffeeee#??
8379    <- OK
8380
8381    -> $m1000,4#??
8382    <- eeeeffffeeeedddd  */
8383
8384 static enum target_xfer_status
8385 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8386                         const gdb_byte *myaddr, ULONGEST len_units,
8387                         int unit_size, ULONGEST *xfered_len_units,
8388                         char packet_format, int use_length)
8389 {
8390   struct remote_state *rs = get_remote_state ();
8391   char *p;
8392   char *plen = NULL;
8393   int plenlen = 0;
8394   int todo_units;
8395   int units_written;
8396   int payload_capacity_bytes;
8397   int payload_length_bytes;
8398
8399   if (packet_format != 'X' && packet_format != 'M')
8400     internal_error (__FILE__, __LINE__,
8401                     _("remote_write_bytes_aux: bad packet format"));
8402
8403   if (len_units == 0)
8404     return TARGET_XFER_EOF;
8405
8406   payload_capacity_bytes = get_memory_write_packet_size ();
8407
8408   /* The packet buffer will be large enough for the payload;
8409      get_memory_packet_size ensures this.  */
8410   rs->buf[0] = '\0';
8411
8412   /* Compute the size of the actual payload by subtracting out the
8413      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
8414
8415   payload_capacity_bytes -= strlen ("$,:#NN");
8416   if (!use_length)
8417     /* The comma won't be used.  */
8418     payload_capacity_bytes += 1;
8419   payload_capacity_bytes -= strlen (header);
8420   payload_capacity_bytes -= hexnumlen (memaddr);
8421
8422   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
8423
8424   strcat (rs->buf, header);
8425   p = rs->buf + strlen (header);
8426
8427   /* Compute a best guess of the number of bytes actually transfered.  */
8428   if (packet_format == 'X')
8429     {
8430       /* Best guess at number of bytes that will fit.  */
8431       todo_units = std::min (len_units,
8432                              (ULONGEST) payload_capacity_bytes / unit_size);
8433       if (use_length)
8434         payload_capacity_bytes -= hexnumlen (todo_units);
8435       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8436     }
8437   else
8438     {
8439       /* Number of bytes that will fit.  */
8440       todo_units
8441         = std::min (len_units,
8442                     (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8443       if (use_length)
8444         payload_capacity_bytes -= hexnumlen (todo_units);
8445       todo_units = std::min (todo_units,
8446                              (payload_capacity_bytes / unit_size) / 2);
8447     }
8448
8449   if (todo_units <= 0)
8450     internal_error (__FILE__, __LINE__,
8451                     _("minimum packet size too small to write data"));
8452
8453   /* If we already need another packet, then try to align the end
8454      of this packet to a useful boundary.  */
8455   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8456     todo_units = align_for_efficient_write (todo_units, memaddr);
8457
8458   /* Append "<memaddr>".  */
8459   memaddr = remote_address_masked (memaddr);
8460   p += hexnumstr (p, (ULONGEST) memaddr);
8461
8462   if (use_length)
8463     {
8464       /* Append ",".  */
8465       *p++ = ',';
8466
8467       /* Append the length and retain its location and size.  It may need to be
8468          adjusted once the packet body has been created.  */
8469       plen = p;
8470       plenlen = hexnumstr (p, (ULONGEST) todo_units);
8471       p += plenlen;
8472     }
8473
8474   /* Append ":".  */
8475   *p++ = ':';
8476   *p = '\0';
8477
8478   /* Append the packet body.  */
8479   if (packet_format == 'X')
8480     {
8481       /* Binary mode.  Send target system values byte by byte, in
8482          increasing byte addresses.  Only escape certain critical
8483          characters.  */
8484       payload_length_bytes =
8485           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8486                                 &units_written, payload_capacity_bytes);
8487
8488       /* If not all TODO units fit, then we'll need another packet.  Make
8489          a second try to keep the end of the packet aligned.  Don't do
8490          this if the packet is tiny.  */
8491       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8492         {
8493           int new_todo_units;
8494
8495           new_todo_units = align_for_efficient_write (units_written, memaddr);
8496
8497           if (new_todo_units != units_written)
8498             payload_length_bytes =
8499                 remote_escape_output (myaddr, new_todo_units, unit_size,
8500                                       (gdb_byte *) p, &units_written,
8501                                       payload_capacity_bytes);
8502         }
8503
8504       p += payload_length_bytes;
8505       if (use_length && units_written < todo_units)
8506         {
8507           /* Escape chars have filled up the buffer prematurely,
8508              and we have actually sent fewer units than planned.
8509              Fix-up the length field of the packet.  Use the same
8510              number of characters as before.  */
8511           plen += hexnumnstr (plen, (ULONGEST) units_written,
8512                               plenlen);
8513           *plen = ':';  /* overwrite \0 from hexnumnstr() */
8514         }
8515     }
8516   else
8517     {
8518       /* Normal mode: Send target system values byte by byte, in
8519          increasing byte addresses.  Each byte is encoded as a two hex
8520          value.  */
8521       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8522       units_written = todo_units;
8523     }
8524
8525   putpkt_binary (rs->buf, (int) (p - rs->buf));
8526   getpkt (&rs->buf, &rs->buf_size, 0);
8527
8528   if (rs->buf[0] == 'E')
8529     return TARGET_XFER_E_IO;
8530
8531   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8532      send fewer units than we'd planned.  */
8533   *xfered_len_units = (ULONGEST) units_written;
8534   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8535 }
8536
8537 /* Write memory data directly to the remote machine.
8538    This does not inform the data cache; the data cache uses this.
8539    MEMADDR is the address in the remote memory space.
8540    MYADDR is the address of the buffer in our space.
8541    LEN is the number of bytes.
8542
8543    Return the transferred status, error or OK (an
8544    'enum target_xfer_status' value).  Save the number of bytes
8545    transferred in *XFERED_LEN.  Only transfer a single packet.  */
8546
8547 static enum target_xfer_status
8548 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8549                     int unit_size, ULONGEST *xfered_len)
8550 {
8551   const char *packet_format = NULL;
8552
8553   /* Check whether the target supports binary download.  */
8554   check_binary_download (memaddr);
8555
8556   switch (packet_support (PACKET_X))
8557     {
8558     case PACKET_ENABLE:
8559       packet_format = "X";
8560       break;
8561     case PACKET_DISABLE:
8562       packet_format = "M";
8563       break;
8564     case PACKET_SUPPORT_UNKNOWN:
8565       internal_error (__FILE__, __LINE__,
8566                       _("remote_write_bytes: bad internal state"));
8567     default:
8568       internal_error (__FILE__, __LINE__, _("bad switch"));
8569     }
8570
8571   return remote_write_bytes_aux (packet_format,
8572                                  memaddr, myaddr, len, unit_size, xfered_len,
8573                                  packet_format[0], 1);
8574 }
8575
8576 /* Read memory data directly from the remote machine.
8577    This does not use the data cache; the data cache uses this.
8578    MEMADDR is the address in the remote memory space.
8579    MYADDR is the address of the buffer in our space.
8580    LEN_UNITS is the number of addressable memory units to read..
8581    UNIT_SIZE is the length in bytes of an addressable unit.
8582
8583    Return the transferred status, error or OK (an
8584    'enum target_xfer_status' value).  Save the number of bytes
8585    transferred in *XFERED_LEN_UNITS.
8586
8587    See the comment of remote_write_bytes_aux for an example of
8588    memory read/write exchange between gdb and the stub.  */
8589
8590 static enum target_xfer_status
8591 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8592                      int unit_size, ULONGEST *xfered_len_units)
8593 {
8594   struct remote_state *rs = get_remote_state ();
8595   int buf_size_bytes;           /* Max size of packet output buffer.  */
8596   char *p;
8597   int todo_units;
8598   int decoded_bytes;
8599
8600   buf_size_bytes = get_memory_read_packet_size ();
8601   /* The packet buffer will be large enough for the payload;
8602      get_memory_packet_size ensures this.  */
8603
8604   /* Number of units that will fit.  */
8605   todo_units = std::min (len_units,
8606                          (ULONGEST) (buf_size_bytes / unit_size) / 2);
8607
8608   /* Construct "m"<memaddr>","<len>".  */
8609   memaddr = remote_address_masked (memaddr);
8610   p = rs->buf;
8611   *p++ = 'm';
8612   p += hexnumstr (p, (ULONGEST) memaddr);
8613   *p++ = ',';
8614   p += hexnumstr (p, (ULONGEST) todo_units);
8615   *p = '\0';
8616   putpkt (rs->buf);
8617   getpkt (&rs->buf, &rs->buf_size, 0);
8618   if (rs->buf[0] == 'E'
8619       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8620       && rs->buf[3] == '\0')
8621     return TARGET_XFER_E_IO;
8622   /* Reply describes memory byte by byte, each byte encoded as two hex
8623      characters.  */
8624   p = rs->buf;
8625   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8626   /* Return what we have.  Let higher layers handle partial reads.  */
8627   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8628   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8629 }
8630
8631 /* Using the set of read-only target sections of remote, read live
8632    read-only memory.
8633
8634    For interface/parameters/return description see target.h,
8635    to_xfer_partial.  */
8636
8637 static enum target_xfer_status
8638 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8639                                    ULONGEST memaddr, ULONGEST len,
8640                                    int unit_size, ULONGEST *xfered_len)
8641 {
8642   struct target_section *secp;
8643   struct target_section_table *table;
8644
8645   secp = target_section_by_addr (ops, memaddr);
8646   if (secp != NULL
8647       && (bfd_get_section_flags (secp->the_bfd_section->owner,
8648                                  secp->the_bfd_section)
8649           & SEC_READONLY))
8650     {
8651       struct target_section *p;
8652       ULONGEST memend = memaddr + len;
8653
8654       table = target_get_section_table (ops);
8655
8656       for (p = table->sections; p < table->sections_end; p++)
8657         {
8658           if (memaddr >= p->addr)
8659             {
8660               if (memend <= p->endaddr)
8661                 {
8662                   /* Entire transfer is within this section.  */
8663                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8664                                               xfered_len);
8665                 }
8666               else if (memaddr >= p->endaddr)
8667                 {
8668                   /* This section ends before the transfer starts.  */
8669                   continue;
8670                 }
8671               else
8672                 {
8673                   /* This section overlaps the transfer.  Just do half.  */
8674                   len = p->endaddr - memaddr;
8675                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8676                                               xfered_len);
8677                 }
8678             }
8679         }
8680     }
8681
8682   return TARGET_XFER_EOF;
8683 }
8684
8685 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8686    first if the requested memory is unavailable in traceframe.
8687    Otherwise, fall back to remote_read_bytes_1.  */
8688
8689 static enum target_xfer_status
8690 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8691                    gdb_byte *myaddr, ULONGEST len, int unit_size,
8692                    ULONGEST *xfered_len)
8693 {
8694   if (len == 0)
8695     return TARGET_XFER_EOF;
8696
8697   if (get_traceframe_number () != -1)
8698     {
8699       std::vector<mem_range> available;
8700
8701       /* If we fail to get the set of available memory, then the
8702          target does not support querying traceframe info, and so we
8703          attempt reading from the traceframe anyway (assuming the
8704          target implements the old QTro packet then).  */
8705       if (traceframe_available_memory (&available, memaddr, len))
8706         {
8707           if (available.empty () || available[0].start != memaddr)
8708             {
8709               enum target_xfer_status res;
8710
8711               /* Don't read into the traceframe's available
8712                  memory.  */
8713               if (!available.empty ())
8714                 {
8715                   LONGEST oldlen = len;
8716
8717                   len = available[0].start - memaddr;
8718                   gdb_assert (len <= oldlen);
8719                 }
8720
8721               /* This goes through the topmost target again.  */
8722               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8723                                                        len, unit_size, xfered_len);
8724               if (res == TARGET_XFER_OK)
8725                 return TARGET_XFER_OK;
8726               else
8727                 {
8728                   /* No use trying further, we know some memory starting
8729                      at MEMADDR isn't available.  */
8730                   *xfered_len = len;
8731                   return (*xfered_len != 0) ?
8732                     TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8733                 }
8734             }
8735
8736           /* Don't try to read more than how much is available, in
8737              case the target implements the deprecated QTro packet to
8738              cater for older GDBs (the target's knowledge of read-only
8739              sections may be outdated by now).  */
8740           len = available[0].length;
8741         }
8742     }
8743
8744   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8745 }
8746
8747 \f
8748
8749 /* Sends a packet with content determined by the printf format string
8750    FORMAT and the remaining arguments, then gets the reply.  Returns
8751    whether the packet was a success, a failure, or unknown.  */
8752
8753 static enum packet_result remote_send_printf (const char *format, ...)
8754   ATTRIBUTE_PRINTF (1, 2);
8755
8756 static enum packet_result
8757 remote_send_printf (const char *format, ...)
8758 {
8759   struct remote_state *rs = get_remote_state ();
8760   int max_size = get_remote_packet_size ();
8761   va_list ap;
8762
8763   va_start (ap, format);
8764
8765   rs->buf[0] = '\0';
8766   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8767     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8768
8769   if (putpkt (rs->buf) < 0)
8770     error (_("Communication problem with target."));
8771
8772   rs->buf[0] = '\0';
8773   getpkt (&rs->buf, &rs->buf_size, 0);
8774
8775   return packet_check_result (rs->buf);
8776 }
8777
8778 /* Flash writing can take quite some time.  We'll set
8779    effectively infinite timeout for flash operations.
8780    In future, we'll need to decide on a better approach.  */
8781 static const int remote_flash_timeout = 1000;
8782
8783 void
8784 remote_target::flash_erase (ULONGEST address, LONGEST length)
8785 {
8786   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8787   enum packet_result ret;
8788   scoped_restore restore_timeout
8789     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8790
8791   ret = remote_send_printf ("vFlashErase:%s,%s",
8792                             phex (address, addr_size),
8793                             phex (length, 4));
8794   switch (ret)
8795     {
8796     case PACKET_UNKNOWN:
8797       error (_("Remote target does not support flash erase"));
8798     case PACKET_ERROR:
8799       error (_("Error erasing flash with vFlashErase packet"));
8800     default:
8801       break;
8802     }
8803 }
8804
8805 static enum target_xfer_status
8806 remote_flash_write (struct target_ops *ops, ULONGEST address,
8807                     ULONGEST length, ULONGEST *xfered_len,
8808                     const gdb_byte *data)
8809 {
8810   scoped_restore restore_timeout
8811     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8812   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8813                                  xfered_len,'X', 0);
8814 }
8815
8816 void
8817 remote_target::flash_done ()
8818 {
8819   int ret;
8820
8821   scoped_restore restore_timeout
8822     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8823
8824   ret = remote_send_printf ("vFlashDone");
8825
8826   switch (ret)
8827     {
8828     case PACKET_UNKNOWN:
8829       error (_("Remote target does not support vFlashDone"));
8830     case PACKET_ERROR:
8831       error (_("Error finishing flash operation"));
8832     default:
8833       break;
8834     }
8835 }
8836
8837 void
8838 remote_target::files_info ()
8839 {
8840   puts_filtered ("Debugging a target over a serial line.\n");
8841 }
8842 \f
8843 /* Stuff for dealing with the packets which are part of this protocol.
8844    See comment at top of file for details.  */
8845
8846 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8847    error to higher layers.  Called when a serial error is detected.
8848    The exception message is STRING, followed by a colon and a blank,
8849    the system error message for errno at function entry and final dot
8850    for output compatibility with throw_perror_with_name.  */
8851
8852 static void
8853 unpush_and_perror (const char *string)
8854 {
8855   int saved_errno = errno;
8856
8857   remote_unpush_target ();
8858   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8859                safe_strerror (saved_errno));
8860 }
8861
8862 /* Read a single character from the remote end.  The current quit
8863    handler is overridden to avoid quitting in the middle of packet
8864    sequence, as that would break communication with the remote server.
8865    See remote_serial_quit_handler for more detail.  */
8866
8867 static int
8868 readchar (int timeout)
8869 {
8870   int ch;
8871   struct remote_state *rs = get_remote_state ();
8872
8873   {
8874     scoped_restore restore_quit
8875       = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8876
8877     rs->got_ctrlc_during_io = 0;
8878
8879     ch = serial_readchar (rs->remote_desc, timeout);
8880
8881     if (rs->got_ctrlc_during_io)
8882       set_quit_flag ();
8883   }
8884
8885   if (ch >= 0)
8886     return ch;
8887
8888   switch ((enum serial_rc) ch)
8889     {
8890     case SERIAL_EOF:
8891       remote_unpush_target ();
8892       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8893       /* no return */
8894     case SERIAL_ERROR:
8895       unpush_and_perror (_("Remote communication error.  "
8896                            "Target disconnected."));
8897       /* no return */
8898     case SERIAL_TIMEOUT:
8899       break;
8900     }
8901   return ch;
8902 }
8903
8904 /* Wrapper for serial_write that closes the target and throws if
8905    writing fails.  The current quit handler is overridden to avoid
8906    quitting in the middle of packet sequence, as that would break
8907    communication with the remote server.  See
8908    remote_serial_quit_handler for more detail.  */
8909
8910 static void
8911 remote_serial_write (const char *str, int len)
8912 {
8913   struct remote_state *rs = get_remote_state ();
8914
8915   scoped_restore restore_quit
8916     = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8917
8918   rs->got_ctrlc_during_io = 0;
8919
8920   if (serial_write (rs->remote_desc, str, len))
8921     {
8922       unpush_and_perror (_("Remote communication error.  "
8923                            "Target disconnected."));
8924     }
8925
8926   if (rs->got_ctrlc_during_io)
8927     set_quit_flag ();
8928 }
8929
8930 /* Return a string representing an escaped version of BUF, of len N.
8931    E.g. \n is converted to \\n, \t to \\t, etc.  */
8932
8933 static std::string
8934 escape_buffer (const char *buf, int n)
8935 {
8936   string_file stb;
8937
8938   stb.putstrn (buf, n, '\\');
8939   return std::move (stb.string ());
8940 }
8941
8942 /* Display a null-terminated packet on stdout, for debugging, using C
8943    string notation.  */
8944
8945 static void
8946 print_packet (const char *buf)
8947 {
8948   puts_filtered ("\"");
8949   fputstr_filtered (buf, '"', gdb_stdout);
8950   puts_filtered ("\"");
8951 }
8952
8953 int
8954 putpkt (const char *buf)
8955 {
8956   return putpkt_binary (buf, strlen (buf));
8957 }
8958
8959 /* Send a packet to the remote machine, with error checking.  The data
8960    of the packet is in BUF.  The string in BUF can be at most
8961    get_remote_packet_size () - 5 to account for the $, # and checksum,
8962    and for a possible /0 if we are debugging (remote_debug) and want
8963    to print the sent packet as a string.  */
8964
8965 static int
8966 putpkt_binary (const char *buf, int cnt)
8967 {
8968   struct remote_state *rs = get_remote_state ();
8969   int i;
8970   unsigned char csum = 0;
8971   gdb::def_vector<char> data (cnt + 6);
8972   char *buf2 = data.data ();
8973
8974   int ch;
8975   int tcount = 0;
8976   char *p;
8977
8978   /* Catch cases like trying to read memory or listing threads while
8979      we're waiting for a stop reply.  The remote server wouldn't be
8980      ready to handle this request, so we'd hang and timeout.  We don't
8981      have to worry about this in synchronous mode, because in that
8982      case it's not possible to issue a command while the target is
8983      running.  This is not a problem in non-stop mode, because in that
8984      case, the stub is always ready to process serial input.  */
8985   if (!target_is_non_stop_p ()
8986       && target_is_async_p ()
8987       && rs->waiting_for_stop_reply)
8988     {
8989       error (_("Cannot execute this command while the target is running.\n"
8990                "Use the \"interrupt\" command to stop the target\n"
8991                "and then try again."));
8992     }
8993
8994   /* We're sending out a new packet.  Make sure we don't look at a
8995      stale cached response.  */
8996   rs->cached_wait_status = 0;
8997
8998   /* Copy the packet into buffer BUF2, encapsulating it
8999      and giving it a checksum.  */
9000
9001   p = buf2;
9002   *p++ = '$';
9003
9004   for (i = 0; i < cnt; i++)
9005     {
9006       csum += buf[i];
9007       *p++ = buf[i];
9008     }
9009   *p++ = '#';
9010   *p++ = tohex ((csum >> 4) & 0xf);
9011   *p++ = tohex (csum & 0xf);
9012
9013   /* Send it over and over until we get a positive ack.  */
9014
9015   while (1)
9016     {
9017       int started_error_output = 0;
9018
9019       if (remote_debug)
9020         {
9021           *p = '\0';
9022
9023           int len = (int) (p - buf2);
9024
9025           std::string str
9026             = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9027
9028           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9029
9030           if (len > REMOTE_DEBUG_MAX_CHAR)
9031             fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9032                                 len - REMOTE_DEBUG_MAX_CHAR);
9033
9034           fprintf_unfiltered (gdb_stdlog, "...");
9035
9036           gdb_flush (gdb_stdlog);
9037         }
9038       remote_serial_write (buf2, p - buf2);
9039
9040       /* If this is a no acks version of the remote protocol, send the
9041          packet and move on.  */
9042       if (rs->noack_mode)
9043         break;
9044
9045       /* Read until either a timeout occurs (-2) or '+' is read.
9046          Handle any notification that arrives in the mean time.  */
9047       while (1)
9048         {
9049           ch = readchar (remote_timeout);
9050
9051           if (remote_debug)
9052             {
9053               switch (ch)
9054                 {
9055                 case '+':
9056                 case '-':
9057                 case SERIAL_TIMEOUT:
9058                 case '$':
9059                 case '%':
9060                   if (started_error_output)
9061                     {
9062                       putchar_unfiltered ('\n');
9063                       started_error_output = 0;
9064                     }
9065                 }
9066             }
9067
9068           switch (ch)
9069             {
9070             case '+':
9071               if (remote_debug)
9072                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9073               return 1;
9074             case '-':
9075               if (remote_debug)
9076                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9077               /* FALLTHROUGH */
9078             case SERIAL_TIMEOUT:
9079               tcount++;
9080               if (tcount > 3)
9081                 return 0;
9082               break;            /* Retransmit buffer.  */
9083             case '$':
9084               {
9085                 if (remote_debug)
9086                   fprintf_unfiltered (gdb_stdlog,
9087                                       "Packet instead of Ack, ignoring it\n");
9088                 /* It's probably an old response sent because an ACK
9089                    was lost.  Gobble up the packet and ack it so it
9090                    doesn't get retransmitted when we resend this
9091                    packet.  */
9092                 skip_frame ();
9093                 remote_serial_write ("+", 1);
9094                 continue;       /* Now, go look for +.  */
9095               }
9096
9097             case '%':
9098               {
9099                 int val;
9100
9101                 /* If we got a notification, handle it, and go back to looking
9102                    for an ack.  */
9103                 /* We've found the start of a notification.  Now
9104                    collect the data.  */
9105                 val = read_frame (&rs->buf, &rs->buf_size);
9106                 if (val >= 0)
9107                   {
9108                     if (remote_debug)
9109                       {
9110                         std::string str = escape_buffer (rs->buf, val);
9111
9112                         fprintf_unfiltered (gdb_stdlog,
9113                                             "  Notification received: %s\n",
9114                                             str.c_str ());
9115                       }
9116                     handle_notification (rs->notif_state, rs->buf);
9117                     /* We're in sync now, rewait for the ack.  */
9118                     tcount = 0;
9119                   }
9120                 else
9121                   {
9122                     if (remote_debug)
9123                       {
9124                         if (!started_error_output)
9125                           {
9126                             started_error_output = 1;
9127                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9128                           }
9129                         fputc_unfiltered (ch & 0177, gdb_stdlog);
9130                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9131                       }
9132                   }
9133                 continue;
9134               }
9135               /* fall-through */
9136             default:
9137               if (remote_debug)
9138                 {
9139                   if (!started_error_output)
9140                     {
9141                       started_error_output = 1;
9142                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9143                     }
9144                   fputc_unfiltered (ch & 0177, gdb_stdlog);
9145                 }
9146               continue;
9147             }
9148           break;                /* Here to retransmit.  */
9149         }
9150
9151 #if 0
9152       /* This is wrong.  If doing a long backtrace, the user should be
9153          able to get out next time we call QUIT, without anything as
9154          violent as interrupt_query.  If we want to provide a way out of
9155          here without getting to the next QUIT, it should be based on
9156          hitting ^C twice as in remote_wait.  */
9157       if (quit_flag)
9158         {
9159           quit_flag = 0;
9160           interrupt_query ();
9161         }
9162 #endif
9163     }
9164
9165   return 0;
9166 }
9167
9168 /* Come here after finding the start of a frame when we expected an
9169    ack.  Do our best to discard the rest of this packet.  */
9170
9171 static void
9172 skip_frame (void)
9173 {
9174   int c;
9175
9176   while (1)
9177     {
9178       c = readchar (remote_timeout);
9179       switch (c)
9180         {
9181         case SERIAL_TIMEOUT:
9182           /* Nothing we can do.  */
9183           return;
9184         case '#':
9185           /* Discard the two bytes of checksum and stop.  */
9186           c = readchar (remote_timeout);
9187           if (c >= 0)
9188             c = readchar (remote_timeout);
9189
9190           return;
9191         case '*':               /* Run length encoding.  */
9192           /* Discard the repeat count.  */
9193           c = readchar (remote_timeout);
9194           if (c < 0)
9195             return;
9196           break;
9197         default:
9198           /* A regular character.  */
9199           break;
9200         }
9201     }
9202 }
9203
9204 /* Come here after finding the start of the frame.  Collect the rest
9205    into *BUF, verifying the checksum, length, and handling run-length
9206    compression.  NUL terminate the buffer.  If there is not enough room,
9207    expand *BUF using xrealloc.
9208
9209    Returns -1 on error, number of characters in buffer (ignoring the
9210    trailing NULL) on success. (could be extended to return one of the
9211    SERIAL status indications).  */
9212
9213 static long
9214 read_frame (char **buf_p,
9215             long *sizeof_buf)
9216 {
9217   unsigned char csum;
9218   long bc;
9219   int c;
9220   char *buf = *buf_p;
9221   struct remote_state *rs = get_remote_state ();
9222
9223   csum = 0;
9224   bc = 0;
9225
9226   while (1)
9227     {
9228       c = readchar (remote_timeout);
9229       switch (c)
9230         {
9231         case SERIAL_TIMEOUT:
9232           if (remote_debug)
9233             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9234           return -1;
9235         case '$':
9236           if (remote_debug)
9237             fputs_filtered ("Saw new packet start in middle of old one\n",
9238                             gdb_stdlog);
9239           return -1;            /* Start a new packet, count retries.  */
9240         case '#':
9241           {
9242             unsigned char pktcsum;
9243             int check_0 = 0;
9244             int check_1 = 0;
9245
9246             buf[bc] = '\0';
9247
9248             check_0 = readchar (remote_timeout);
9249             if (check_0 >= 0)
9250               check_1 = readchar (remote_timeout);
9251
9252             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9253               {
9254                 if (remote_debug)
9255                   fputs_filtered ("Timeout in checksum, retrying\n",
9256                                   gdb_stdlog);
9257                 return -1;
9258               }
9259             else if (check_0 < 0 || check_1 < 0)
9260               {
9261                 if (remote_debug)
9262                   fputs_filtered ("Communication error in checksum\n",
9263                                   gdb_stdlog);
9264                 return -1;
9265               }
9266
9267             /* Don't recompute the checksum; with no ack packets we
9268                don't have any way to indicate a packet retransmission
9269                is necessary.  */
9270             if (rs->noack_mode)
9271               return bc;
9272
9273             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9274             if (csum == pktcsum)
9275               return bc;
9276
9277             if (remote_debug)
9278               {
9279                 std::string str = escape_buffer (buf, bc);
9280
9281                 fprintf_unfiltered (gdb_stdlog,
9282                                     "Bad checksum, sentsum=0x%x, "
9283                                     "csum=0x%x, buf=%s\n",
9284                                     pktcsum, csum, str.c_str ());
9285               }
9286             /* Number of characters in buffer ignoring trailing
9287                NULL.  */
9288             return -1;
9289           }
9290         case '*':               /* Run length encoding.  */
9291           {
9292             int repeat;
9293
9294             csum += c;
9295             c = readchar (remote_timeout);
9296             csum += c;
9297             repeat = c - ' ' + 3;       /* Compute repeat count.  */
9298
9299             /* The character before ``*'' is repeated.  */
9300
9301             if (repeat > 0 && repeat <= 255 && bc > 0)
9302               {
9303                 if (bc + repeat - 1 >= *sizeof_buf - 1)
9304                   {
9305                     /* Make some more room in the buffer.  */
9306                     *sizeof_buf += repeat;
9307                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9308                     buf = *buf_p;
9309                   }
9310
9311                 memset (&buf[bc], buf[bc - 1], repeat);
9312                 bc += repeat;
9313                 continue;
9314               }
9315
9316             buf[bc] = '\0';
9317             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9318             return -1;
9319           }
9320         default:
9321           if (bc >= *sizeof_buf - 1)
9322             {
9323               /* Make some more room in the buffer.  */
9324               *sizeof_buf *= 2;
9325               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9326               buf = *buf_p;
9327             }
9328
9329           buf[bc++] = c;
9330           csum += c;
9331           continue;
9332         }
9333     }
9334 }
9335
9336 /* Read a packet from the remote machine, with error checking, and
9337    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9338    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9339    rather than timing out; this is used (in synchronous mode) to wait
9340    for a target that is is executing user code to stop.  */
9341 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9342    don't have to change all the calls to getpkt to deal with the
9343    return value, because at the moment I don't know what the right
9344    thing to do it for those.  */
9345 void
9346 getpkt (char **buf,
9347         long *sizeof_buf,
9348         int forever)
9349 {
9350   getpkt_sane (buf, sizeof_buf, forever);
9351 }
9352
9353
9354 /* Read a packet from the remote machine, with error checking, and
9355    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9356    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9357    rather than timing out; this is used (in synchronous mode) to wait
9358    for a target that is is executing user code to stop.  If FOREVER ==
9359    0, this function is allowed to time out gracefully and return an
9360    indication of this to the caller.  Otherwise return the number of
9361    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
9362    enough reason to return to the caller.  *IS_NOTIF is an output
9363    boolean that indicates whether *BUF holds a notification or not
9364    (a regular packet).  */
9365
9366 static int
9367 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9368                         int expecting_notif, int *is_notif)
9369 {
9370   struct remote_state *rs = get_remote_state ();
9371   int c;
9372   int tries;
9373   int timeout;
9374   int val = -1;
9375
9376   /* We're reading a new response.  Make sure we don't look at a
9377      previously cached response.  */
9378   rs->cached_wait_status = 0;
9379
9380   strcpy (*buf, "timeout");
9381
9382   if (forever)
9383     timeout = watchdog > 0 ? watchdog : -1;
9384   else if (expecting_notif)
9385     timeout = 0; /* There should already be a char in the buffer.  If
9386                     not, bail out.  */
9387   else
9388     timeout = remote_timeout;
9389
9390 #define MAX_TRIES 3
9391
9392   /* Process any number of notifications, and then return when
9393      we get a packet.  */
9394   for (;;)
9395     {
9396       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9397          times.  */
9398       for (tries = 1; tries <= MAX_TRIES; tries++)
9399         {
9400           /* This can loop forever if the remote side sends us
9401              characters continuously, but if it pauses, we'll get
9402              SERIAL_TIMEOUT from readchar because of timeout.  Then
9403              we'll count that as a retry.
9404
9405              Note that even when forever is set, we will only wait
9406              forever prior to the start of a packet.  After that, we
9407              expect characters to arrive at a brisk pace.  They should
9408              show up within remote_timeout intervals.  */
9409           do
9410             c = readchar (timeout);
9411           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9412
9413           if (c == SERIAL_TIMEOUT)
9414             {
9415               if (expecting_notif)
9416                 return -1; /* Don't complain, it's normal to not get
9417                               anything in this case.  */
9418
9419               if (forever)      /* Watchdog went off?  Kill the target.  */
9420                 {
9421                   remote_unpush_target ();
9422                   throw_error (TARGET_CLOSE_ERROR,
9423                                _("Watchdog timeout has expired.  "
9424                                  "Target detached."));
9425                 }
9426               if (remote_debug)
9427                 fputs_filtered ("Timed out.\n", gdb_stdlog);
9428             }
9429           else
9430             {
9431               /* We've found the start of a packet or notification.
9432                  Now collect the data.  */
9433               val = read_frame (buf, sizeof_buf);
9434               if (val >= 0)
9435                 break;
9436             }
9437
9438           remote_serial_write ("-", 1);
9439         }
9440
9441       if (tries > MAX_TRIES)
9442         {
9443           /* We have tried hard enough, and just can't receive the
9444              packet/notification.  Give up.  */
9445           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9446
9447           /* Skip the ack char if we're in no-ack mode.  */
9448           if (!rs->noack_mode)
9449             remote_serial_write ("+", 1);
9450           return -1;
9451         }
9452
9453       /* If we got an ordinary packet, return that to our caller.  */
9454       if (c == '$')
9455         {
9456           if (remote_debug)
9457             {
9458               std::string str
9459                 = escape_buffer (*buf,
9460                                  std::min (val, REMOTE_DEBUG_MAX_CHAR));
9461
9462               fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9463                                   str.c_str ());
9464
9465               if (val > REMOTE_DEBUG_MAX_CHAR)
9466                 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9467                                     val - REMOTE_DEBUG_MAX_CHAR);
9468
9469               fprintf_unfiltered (gdb_stdlog, "\n");
9470             }
9471
9472           /* Skip the ack char if we're in no-ack mode.  */
9473           if (!rs->noack_mode)
9474             remote_serial_write ("+", 1);
9475           if (is_notif != NULL)
9476             *is_notif = 0;
9477           return val;
9478         }
9479
9480        /* If we got a notification, handle it, and go back to looking
9481          for a packet.  */
9482       else
9483         {
9484           gdb_assert (c == '%');
9485
9486           if (remote_debug)
9487             {
9488               std::string str = escape_buffer (*buf, val);
9489
9490               fprintf_unfiltered (gdb_stdlog,
9491                                   "  Notification received: %s\n",
9492                                   str.c_str ());
9493             }
9494           if (is_notif != NULL)
9495             *is_notif = 1;
9496
9497           handle_notification (rs->notif_state, *buf);
9498
9499           /* Notifications require no acknowledgement.  */
9500
9501           if (expecting_notif)
9502             return val;
9503         }
9504     }
9505 }
9506
9507 static int
9508 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9509 {
9510   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9511 }
9512
9513 static int
9514 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9515                       int *is_notif)
9516 {
9517   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9518                                  is_notif);
9519 }
9520
9521 /* Check whether EVENT is a fork event for the process specified
9522    by the pid passed in DATA, and if it is, kill the fork child.  */
9523
9524 static int
9525 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9526                             QUEUE_ITER (stop_reply_p) *iter,
9527                             stop_reply_p event,
9528                             void *data)
9529 {
9530   struct queue_iter_param *param = (struct queue_iter_param *) data;
9531   int parent_pid = *(int *) param->input;
9532
9533   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9534     {
9535       struct remote_state *rs = get_remote_state ();
9536       int child_pid = ptid_get_pid (event->ws.value.related_pid);
9537       int res;
9538
9539       res = remote_vkill (child_pid, rs);
9540       if (res != 0)
9541         error (_("Can't kill fork child process %d"), child_pid);
9542     }
9543
9544   return 1;
9545 }
9546
9547 /* Kill any new fork children of process PID that haven't been
9548    processed by follow_fork.  */
9549
9550 static void
9551 kill_new_fork_children (int pid, struct remote_state *rs)
9552 {
9553   struct thread_info *thread;
9554   struct notif_client *notif = &notif_client_stop;
9555   struct queue_iter_param param;
9556
9557   /* Kill the fork child threads of any threads in process PID
9558      that are stopped at a fork event.  */
9559   ALL_NON_EXITED_THREADS (thread)
9560     {
9561       struct target_waitstatus *ws = &thread->pending_follow;
9562
9563       if (is_pending_fork_parent (ws, pid, thread->ptid))
9564         {
9565           struct remote_state *rs = get_remote_state ();
9566           int child_pid = ptid_get_pid (ws->value.related_pid);
9567           int res;
9568
9569           res = remote_vkill (child_pid, rs);
9570           if (res != 0)
9571             error (_("Can't kill fork child process %d"), child_pid);
9572         }
9573     }
9574
9575   /* Check for any pending fork events (not reported or processed yet)
9576      in process PID and kill those fork child threads as well.  */
9577   remote_notif_get_pending_events (notif);
9578   param.input = &pid;
9579   param.output = NULL;
9580   QUEUE_iterate (stop_reply_p, stop_reply_queue,
9581                  kill_child_of_pending_fork, &param);
9582 }
9583
9584 \f
9585 /* Target hook to kill the current inferior.  */
9586
9587 void
9588 remote_target::kill ()
9589 {
9590   int res = -1;
9591   int pid = ptid_get_pid (inferior_ptid);
9592   struct remote_state *rs = get_remote_state ();
9593
9594   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9595     {
9596       /* If we're stopped while forking and we haven't followed yet,
9597          kill the child task.  We need to do this before killing the
9598          parent task because if this is a vfork then the parent will
9599          be sleeping.  */
9600       kill_new_fork_children (pid, rs);
9601
9602       res = remote_vkill (pid, rs);
9603       if (res == 0)
9604         {
9605           target_mourn_inferior (inferior_ptid);
9606           return;
9607         }
9608     }
9609
9610   /* If we are in 'target remote' mode and we are killing the only
9611      inferior, then we will tell gdbserver to exit and unpush the
9612      target.  */
9613   if (res == -1 && !remote_multi_process_p (rs)
9614       && number_of_live_inferiors () == 1)
9615     {
9616       remote_kill_k ();
9617
9618       /* We've killed the remote end, we get to mourn it.  If we are
9619          not in extended mode, mourning the inferior also unpushes
9620          remote_ops from the target stack, which closes the remote
9621          connection.  */
9622       target_mourn_inferior (inferior_ptid);
9623
9624       return;
9625     }
9626
9627   error (_("Can't kill process"));
9628 }
9629
9630 /* Send a kill request to the target using the 'vKill' packet.  */
9631
9632 static int
9633 remote_vkill (int pid, struct remote_state *rs)
9634 {
9635   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9636     return -1;
9637
9638   /* Tell the remote target to detach.  */
9639   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9640   putpkt (rs->buf);
9641   getpkt (&rs->buf, &rs->buf_size, 0);
9642
9643   switch (packet_ok (rs->buf,
9644                      &remote_protocol_packets[PACKET_vKill]))
9645     {
9646     case PACKET_OK:
9647       return 0;
9648     case PACKET_ERROR:
9649       return 1;
9650     case PACKET_UNKNOWN:
9651       return -1;
9652     default:
9653       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9654     }
9655 }
9656
9657 /* Send a kill request to the target using the 'k' packet.  */
9658
9659 static void
9660 remote_kill_k (void)
9661 {
9662   /* Catch errors so the user can quit from gdb even when we
9663      aren't on speaking terms with the remote system.  */
9664   TRY
9665     {
9666       putpkt ("k");
9667     }
9668   CATCH (ex, RETURN_MASK_ERROR)
9669     {
9670       if (ex.error == TARGET_CLOSE_ERROR)
9671         {
9672           /* If we got an (EOF) error that caused the target
9673              to go away, then we're done, that's what we wanted.
9674              "k" is susceptible to cause a premature EOF, given
9675              that the remote server isn't actually required to
9676              reply to "k", and it can happen that it doesn't
9677              even get to reply ACK to the "k".  */
9678           return;
9679         }
9680
9681       /* Otherwise, something went wrong.  We didn't actually kill
9682          the target.  Just propagate the exception, and let the
9683          user or higher layers decide what to do.  */
9684       throw_exception (ex);
9685     }
9686   END_CATCH
9687 }
9688
9689 void
9690 remote_target::mourn_inferior ()
9691 {
9692   struct remote_state *rs = get_remote_state ();
9693
9694   /* We're no longer interested in notification events of an inferior
9695      that exited or was killed/detached.  */
9696   discard_pending_stop_replies (current_inferior ());
9697
9698   /* In 'target remote' mode with one inferior, we close the connection.  */
9699   if (!rs->extended && number_of_live_inferiors () <= 1)
9700     {
9701       unpush_target (this);
9702
9703       /* remote_close takes care of doing most of the clean up.  */
9704       generic_mourn_inferior ();
9705       return;
9706     }
9707
9708   /* In case we got here due to an error, but we're going to stay
9709      connected.  */
9710   rs->waiting_for_stop_reply = 0;
9711
9712   /* If the current general thread belonged to the process we just
9713      detached from or has exited, the remote side current general
9714      thread becomes undefined.  Considering a case like this:
9715
9716      - We just got here due to a detach.
9717      - The process that we're detaching from happens to immediately
9718        report a global breakpoint being hit in non-stop mode, in the
9719        same thread we had selected before.
9720      - GDB attaches to this process again.
9721      - This event happens to be the next event we handle.
9722
9723      GDB would consider that the current general thread didn't need to
9724      be set on the stub side (with Hg), since for all it knew,
9725      GENERAL_THREAD hadn't changed.
9726
9727      Notice that although in all-stop mode, the remote server always
9728      sets the current thread to the thread reporting the stop event,
9729      that doesn't happen in non-stop mode; in non-stop, the stub *must
9730      not* change the current thread when reporting a breakpoint hit,
9731      due to the decoupling of event reporting and event handling.
9732
9733      To keep things simple, we always invalidate our notion of the
9734      current thread.  */
9735   record_currthread (rs, minus_one_ptid);
9736
9737   /* Call common code to mark the inferior as not running.  */
9738   generic_mourn_inferior ();
9739
9740   if (!have_inferiors ())
9741     {
9742       if (!remote_multi_process_p (rs))
9743         {
9744           /* Check whether the target is running now - some remote stubs
9745              automatically restart after kill.  */
9746           putpkt ("?");
9747           getpkt (&rs->buf, &rs->buf_size, 0);
9748
9749           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9750             {
9751               /* Assume that the target has been restarted.  Set
9752                  inferior_ptid so that bits of core GDB realizes
9753                  there's something here, e.g., so that the user can
9754                  say "kill" again.  */
9755               inferior_ptid = magic_null_ptid;
9756             }
9757         }
9758     }
9759 }
9760
9761 bool
9762 extended_remote_target::supports_disable_randomization ()
9763 {
9764   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9765 }
9766
9767 static void
9768 extended_remote_disable_randomization (int val)
9769 {
9770   struct remote_state *rs = get_remote_state ();
9771   char *reply;
9772
9773   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9774              val);
9775   putpkt (rs->buf);
9776   reply = remote_get_noisy_reply ();
9777   if (*reply == '\0')
9778     error (_("Target does not support QDisableRandomization."));
9779   if (strcmp (reply, "OK") != 0)
9780     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9781 }
9782
9783 static int
9784 extended_remote_run (const std::string &args)
9785 {
9786   struct remote_state *rs = get_remote_state ();
9787   int len;
9788   const char *remote_exec_file = get_remote_exec_file ();
9789
9790   /* If the user has disabled vRun support, or we have detected that
9791      support is not available, do not try it.  */
9792   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9793     return -1;
9794
9795   strcpy (rs->buf, "vRun;");
9796   len = strlen (rs->buf);
9797
9798   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9799     error (_("Remote file name too long for run packet"));
9800   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9801                       strlen (remote_exec_file));
9802
9803   if (!args.empty ())
9804     {
9805       int i;
9806
9807       gdb_argv argv (args.c_str ());
9808       for (i = 0; argv[i] != NULL; i++)
9809         {
9810           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9811             error (_("Argument list too long for run packet"));
9812           rs->buf[len++] = ';';
9813           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9814                               strlen (argv[i]));
9815         }
9816     }
9817
9818   rs->buf[len++] = '\0';
9819
9820   putpkt (rs->buf);
9821   getpkt (&rs->buf, &rs->buf_size, 0);
9822
9823   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9824     {
9825     case PACKET_OK:
9826       /* We have a wait response.  All is well.  */
9827       return 0;
9828     case PACKET_UNKNOWN:
9829       return -1;
9830     case PACKET_ERROR:
9831       if (remote_exec_file[0] == '\0')
9832         error (_("Running the default executable on the remote target failed; "
9833                  "try \"set remote exec-file\"?"));
9834       else
9835         error (_("Running \"%s\" on the remote target failed"),
9836                remote_exec_file);
9837     default:
9838       gdb_assert_not_reached (_("bad switch"));
9839     }
9840 }
9841
9842 /* Helper function to send set/unset environment packets.  ACTION is
9843    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
9844    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
9845    sent.  */
9846
9847 static void
9848 send_environment_packet (struct remote_state *rs,
9849                          const char *action,
9850                          const char *packet,
9851                          const char *value)
9852 {
9853   /* Convert the environment variable to an hex string, which
9854      is the best format to be transmitted over the wire.  */
9855   std::string encoded_value = bin2hex ((const gdb_byte *) value,
9856                                          strlen (value));
9857
9858   xsnprintf (rs->buf, get_remote_packet_size (),
9859              "%s:%s", packet, encoded_value.c_str ());
9860
9861   putpkt (rs->buf);
9862   getpkt (&rs->buf, &rs->buf_size, 0);
9863   if (strcmp (rs->buf, "OK") != 0)
9864     warning (_("Unable to %s environment variable '%s' on remote."),
9865              action, value);
9866 }
9867
9868 /* Helper function to handle the QEnvironment* packets.  */
9869
9870 static void
9871 extended_remote_environment_support (struct remote_state *rs)
9872 {
9873   if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9874     {
9875       putpkt ("QEnvironmentReset");
9876       getpkt (&rs->buf, &rs->buf_size, 0);
9877       if (strcmp (rs->buf, "OK") != 0)
9878         warning (_("Unable to reset environment on remote."));
9879     }
9880
9881   gdb_environ *e = &current_inferior ()->environment;
9882
9883   if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9884     for (const std::string &el : e->user_set_env ())
9885       send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9886                                el.c_str ());
9887
9888   if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9889     for (const std::string &el : e->user_unset_env ())
9890       send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9891 }
9892
9893 /* Helper function to set the current working directory for the
9894    inferior in the remote target.  */
9895
9896 static void
9897 extended_remote_set_inferior_cwd (struct remote_state *rs)
9898 {
9899   if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9900     {
9901       const char *inferior_cwd = get_inferior_cwd ();
9902
9903       if (inferior_cwd != NULL)
9904         {
9905           std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9906                                          strlen (inferior_cwd));
9907
9908           xsnprintf (rs->buf, get_remote_packet_size (),
9909                      "QSetWorkingDir:%s", hexpath.c_str ());
9910         }
9911       else
9912         {
9913           /* An empty inferior_cwd means that the user wants us to
9914              reset the remote server's inferior's cwd.  */
9915           xsnprintf (rs->buf, get_remote_packet_size (),
9916                      "QSetWorkingDir:");
9917         }
9918
9919       putpkt (rs->buf);
9920       getpkt (&rs->buf, &rs->buf_size, 0);
9921       if (packet_ok (rs->buf,
9922                      &remote_protocol_packets[PACKET_QSetWorkingDir])
9923           != PACKET_OK)
9924         error (_("\
9925 Remote replied unexpectedly while setting the inferior's working\n\
9926 directory: %s"),
9927                rs->buf);
9928
9929     }
9930 }
9931
9932 /* In the extended protocol we want to be able to do things like
9933    "run" and have them basically work as expected.  So we need
9934    a special create_inferior function.  We support changing the
9935    executable file and the command line arguments, but not the
9936    environment.  */
9937
9938 void
9939 extended_remote_target::create_inferior (const char *exec_file,
9940                                          const std::string &args,
9941                                          char **env, int from_tty)
9942 {
9943   int run_worked;
9944   char *stop_reply;
9945   struct remote_state *rs = get_remote_state ();
9946   const char *remote_exec_file = get_remote_exec_file ();
9947
9948   /* If running asynchronously, register the target file descriptor
9949      with the event loop.  */
9950   if (target_can_async_p ())
9951     target_async (1);
9952
9953   /* Disable address space randomization if requested (and supported).  */
9954   if (supports_disable_randomization ())
9955     extended_remote_disable_randomization (disable_randomization);
9956
9957   /* If startup-with-shell is on, we inform gdbserver to start the
9958      remote inferior using a shell.  */
9959   if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9960     {
9961       xsnprintf (rs->buf, get_remote_packet_size (),
9962                  "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9963       putpkt (rs->buf);
9964       getpkt (&rs->buf, &rs->buf_size, 0);
9965       if (strcmp (rs->buf, "OK") != 0)
9966         error (_("\
9967 Remote replied unexpectedly while setting startup-with-shell: %s"),
9968                rs->buf);
9969     }
9970
9971   extended_remote_environment_support (rs);
9972
9973   extended_remote_set_inferior_cwd (rs);
9974
9975   /* Now restart the remote server.  */
9976   run_worked = extended_remote_run (args) != -1;
9977   if (!run_worked)
9978     {
9979       /* vRun was not supported.  Fail if we need it to do what the
9980          user requested.  */
9981       if (remote_exec_file[0])
9982         error (_("Remote target does not support \"set remote exec-file\""));
9983       if (!args.empty ())
9984         error (_("Remote target does not support \"set args\" or run <ARGS>"));
9985
9986       /* Fall back to "R".  */
9987       extended_remote_restart ();
9988     }
9989
9990   if (!have_inferiors ())
9991     {
9992       /* Clean up from the last time we ran, before we mark the target
9993          running again.  This will mark breakpoints uninserted, and
9994          get_offsets may insert breakpoints.  */
9995       init_thread_list ();
9996       init_wait_for_inferior ();
9997     }
9998
9999   /* vRun's success return is a stop reply.  */
10000   stop_reply = run_worked ? rs->buf : NULL;
10001   add_current_inferior_and_thread (stop_reply);
10002
10003   /* Get updated offsets, if the stub uses qOffsets.  */
10004   get_offsets ();
10005 }
10006 \f
10007
10008 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
10009    the list of conditions (in agent expression bytecode format), if any, the
10010    target needs to evaluate.  The output is placed into the packet buffer
10011    started from BUF and ended at BUF_END.  */
10012
10013 static int
10014 remote_add_target_side_condition (struct gdbarch *gdbarch,
10015                                   struct bp_target_info *bp_tgt, char *buf,
10016                                   char *buf_end)
10017 {
10018   if (bp_tgt->conditions.empty ())
10019     return 0;
10020
10021   buf += strlen (buf);
10022   xsnprintf (buf, buf_end - buf, "%s", ";");
10023   buf++;
10024
10025   /* Send conditions to the target.  */
10026   for (agent_expr *aexpr : bp_tgt->conditions)
10027     {
10028       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10029       buf += strlen (buf);
10030       for (int i = 0; i < aexpr->len; ++i)
10031         buf = pack_hex_byte (buf, aexpr->buf[i]);
10032       *buf = '\0';
10033     }
10034   return 0;
10035 }
10036
10037 static void
10038 remote_add_target_side_commands (struct gdbarch *gdbarch,
10039                                  struct bp_target_info *bp_tgt, char *buf)
10040 {
10041   if (bp_tgt->tcommands.empty ())
10042     return;
10043
10044   buf += strlen (buf);
10045
10046   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10047   buf += strlen (buf);
10048
10049   /* Concatenate all the agent expressions that are commands into the
10050      cmds parameter.  */
10051   for (agent_expr *aexpr : bp_tgt->tcommands)
10052     {
10053       sprintf (buf, "X%x,", aexpr->len);
10054       buf += strlen (buf);
10055       for (int i = 0; i < aexpr->len; ++i)
10056         buf = pack_hex_byte (buf, aexpr->buf[i]);
10057       *buf = '\0';
10058     }
10059 }
10060
10061 /* Insert a breakpoint.  On targets that have software breakpoint
10062    support, we ask the remote target to do the work; on targets
10063    which don't, we insert a traditional memory breakpoint.  */
10064
10065 int
10066 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10067                                   struct bp_target_info *bp_tgt)
10068 {
10069   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10070      If it succeeds, then set the support to PACKET_ENABLE.  If it
10071      fails, and the user has explicitly requested the Z support then
10072      report an error, otherwise, mark it disabled and go on.  */
10073
10074   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10075     {
10076       CORE_ADDR addr = bp_tgt->reqstd_address;
10077       struct remote_state *rs;
10078       char *p, *endbuf;
10079
10080       /* Make sure the remote is pointing at the right process, if
10081          necessary.  */
10082       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10083         set_general_process ();
10084
10085       rs = get_remote_state ();
10086       p = rs->buf;
10087       endbuf = rs->buf + get_remote_packet_size ();
10088
10089       *(p++) = 'Z';
10090       *(p++) = '0';
10091       *(p++) = ',';
10092       addr = (ULONGEST) remote_address_masked (addr);
10093       p += hexnumstr (p, addr);
10094       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10095
10096       if (supports_evaluation_of_breakpoint_conditions ())
10097         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10098
10099       if (can_run_breakpoint_commands ())
10100         remote_add_target_side_commands (gdbarch, bp_tgt, p);
10101
10102       putpkt (rs->buf);
10103       getpkt (&rs->buf, &rs->buf_size, 0);
10104
10105       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10106         {
10107         case PACKET_ERROR:
10108           return -1;
10109         case PACKET_OK:
10110           return 0;
10111         case PACKET_UNKNOWN:
10112           break;
10113         }
10114     }
10115
10116   /* If this breakpoint has target-side commands but this stub doesn't
10117      support Z0 packets, throw error.  */
10118   if (!bp_tgt->tcommands.empty ())
10119     throw_error (NOT_SUPPORTED_ERROR, _("\
10120 Target doesn't support breakpoints that have target side commands."));
10121
10122   return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10123 }
10124
10125 int
10126 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10127                                   struct bp_target_info *bp_tgt,
10128                                   enum remove_bp_reason reason)
10129 {
10130   CORE_ADDR addr = bp_tgt->placed_address;
10131   struct remote_state *rs = get_remote_state ();
10132
10133   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10134     {
10135       char *p = rs->buf;
10136       char *endbuf = rs->buf + get_remote_packet_size ();
10137
10138       /* Make sure the remote is pointing at the right process, if
10139          necessary.  */
10140       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10141         set_general_process ();
10142
10143       *(p++) = 'z';
10144       *(p++) = '0';
10145       *(p++) = ',';
10146
10147       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10148       p += hexnumstr (p, addr);
10149       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10150
10151       putpkt (rs->buf);
10152       getpkt (&rs->buf, &rs->buf_size, 0);
10153
10154       return (rs->buf[0] == 'E');
10155     }
10156
10157   return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10158 }
10159
10160 static enum Z_packet_type
10161 watchpoint_to_Z_packet (int type)
10162 {
10163   switch (type)
10164     {
10165     case hw_write:
10166       return Z_PACKET_WRITE_WP;
10167       break;
10168     case hw_read:
10169       return Z_PACKET_READ_WP;
10170       break;
10171     case hw_access:
10172       return Z_PACKET_ACCESS_WP;
10173       break;
10174     default:
10175       internal_error (__FILE__, __LINE__,
10176                       _("hw_bp_to_z: bad watchpoint type %d"), type);
10177     }
10178 }
10179
10180 int
10181 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10182                                   enum target_hw_bp_type type, struct expression *cond)
10183 {
10184   struct remote_state *rs = get_remote_state ();
10185   char *endbuf = rs->buf + get_remote_packet_size ();
10186   char *p;
10187   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10188
10189   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10190     return 1;
10191
10192   /* Make sure the remote is pointing at the right process, if
10193      necessary.  */
10194   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10195     set_general_process ();
10196
10197   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10198   p = strchr (rs->buf, '\0');
10199   addr = remote_address_masked (addr);
10200   p += hexnumstr (p, (ULONGEST) addr);
10201   xsnprintf (p, endbuf - p, ",%x", len);
10202
10203   putpkt (rs->buf);
10204   getpkt (&rs->buf, &rs->buf_size, 0);
10205
10206   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10207     {
10208     case PACKET_ERROR:
10209       return -1;
10210     case PACKET_UNKNOWN:
10211       return 1;
10212     case PACKET_OK:
10213       return 0;
10214     }
10215   internal_error (__FILE__, __LINE__,
10216                   _("remote_insert_watchpoint: reached end of function"));
10217 }
10218
10219 bool
10220 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10221                                              CORE_ADDR start, int length)
10222 {
10223   CORE_ADDR diff = remote_address_masked (addr - start);
10224
10225   return diff < length;
10226 }
10227
10228
10229 int
10230 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10231                                   enum target_hw_bp_type type, struct expression *cond)
10232 {
10233   struct remote_state *rs = get_remote_state ();
10234   char *endbuf = rs->buf + get_remote_packet_size ();
10235   char *p;
10236   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10237
10238   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10239     return -1;
10240
10241   /* Make sure the remote is pointing at the right process, if
10242      necessary.  */
10243   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10244     set_general_process ();
10245
10246   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10247   p = strchr (rs->buf, '\0');
10248   addr = remote_address_masked (addr);
10249   p += hexnumstr (p, (ULONGEST) addr);
10250   xsnprintf (p, endbuf - p, ",%x", len);
10251   putpkt (rs->buf);
10252   getpkt (&rs->buf, &rs->buf_size, 0);
10253
10254   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10255     {
10256     case PACKET_ERROR:
10257     case PACKET_UNKNOWN:
10258       return -1;
10259     case PACKET_OK:
10260       return 0;
10261     }
10262   internal_error (__FILE__, __LINE__,
10263                   _("remote_remove_watchpoint: reached end of function"));
10264 }
10265
10266
10267 int remote_hw_watchpoint_limit = -1;
10268 int remote_hw_watchpoint_length_limit = -1;
10269 int remote_hw_breakpoint_limit = -1;
10270
10271 int
10272 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10273 {
10274   if (remote_hw_watchpoint_length_limit == 0)
10275     return 0;
10276   else if (remote_hw_watchpoint_length_limit < 0)
10277     return 1;
10278   else if (len <= remote_hw_watchpoint_length_limit)
10279     return 1;
10280   else
10281     return 0;
10282 }
10283
10284 int
10285 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10286 {
10287   if (type == bp_hardware_breakpoint)
10288     {
10289       if (remote_hw_breakpoint_limit == 0)
10290         return 0;
10291       else if (remote_hw_breakpoint_limit < 0)
10292         return 1;
10293       else if (cnt <= remote_hw_breakpoint_limit)
10294         return 1;
10295     }
10296   else
10297     {
10298       if (remote_hw_watchpoint_limit == 0)
10299         return 0;
10300       else if (remote_hw_watchpoint_limit < 0)
10301         return 1;
10302       else if (ot)
10303         return -1;
10304       else if (cnt <= remote_hw_watchpoint_limit)
10305         return 1;
10306     }
10307   return -1;
10308 }
10309
10310 /* The to_stopped_by_sw_breakpoint method of target remote.  */
10311
10312 bool
10313 remote_target::stopped_by_sw_breakpoint ()
10314 {
10315   struct thread_info *thread = inferior_thread ();
10316
10317   return (thread->priv != NULL
10318           && (get_remote_thread_info (thread)->stop_reason
10319               == TARGET_STOPPED_BY_SW_BREAKPOINT));
10320 }
10321
10322 /* The to_supports_stopped_by_sw_breakpoint method of target
10323    remote.  */
10324
10325 bool
10326 remote_target::supports_stopped_by_sw_breakpoint ()
10327 {
10328   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10329 }
10330
10331 /* The to_stopped_by_hw_breakpoint method of target remote.  */
10332
10333 bool
10334 remote_target::stopped_by_hw_breakpoint ()
10335 {
10336   struct thread_info *thread = inferior_thread ();
10337
10338   return (thread->priv != NULL
10339           && (get_remote_thread_info (thread)->stop_reason
10340               == TARGET_STOPPED_BY_HW_BREAKPOINT));
10341 }
10342
10343 /* The to_supports_stopped_by_hw_breakpoint method of target
10344    remote.  */
10345
10346 bool
10347 remote_target::supports_stopped_by_hw_breakpoint ()
10348 {
10349   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10350 }
10351
10352 bool
10353 remote_target::stopped_by_watchpoint ()
10354 {
10355   struct thread_info *thread = inferior_thread ();
10356
10357   return (thread->priv != NULL
10358           && (get_remote_thread_info (thread)->stop_reason
10359               == TARGET_STOPPED_BY_WATCHPOINT));
10360 }
10361
10362 bool
10363 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10364 {
10365   struct thread_info *thread = inferior_thread ();
10366
10367   if (thread->priv != NULL
10368       && (get_remote_thread_info (thread)->stop_reason
10369           == TARGET_STOPPED_BY_WATCHPOINT))
10370     {
10371       *addr_p = get_remote_thread_info (thread)->watch_data_address;
10372       return true;
10373     }
10374
10375   return false;
10376 }
10377
10378
10379 int
10380 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10381                                      struct bp_target_info *bp_tgt)
10382 {
10383   CORE_ADDR addr = bp_tgt->reqstd_address;
10384   struct remote_state *rs;
10385   char *p, *endbuf;
10386   char *message;
10387
10388   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10389     return -1;
10390
10391   /* Make sure the remote is pointing at the right process, if
10392      necessary.  */
10393   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10394     set_general_process ();
10395
10396   rs = get_remote_state ();
10397   p = rs->buf;
10398   endbuf = rs->buf + get_remote_packet_size ();
10399
10400   *(p++) = 'Z';
10401   *(p++) = '1';
10402   *(p++) = ',';
10403
10404   addr = remote_address_masked (addr);
10405   p += hexnumstr (p, (ULONGEST) addr);
10406   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10407
10408   if (supports_evaluation_of_breakpoint_conditions ())
10409     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10410
10411   if (can_run_breakpoint_commands ())
10412     remote_add_target_side_commands (gdbarch, bp_tgt, p);
10413
10414   putpkt (rs->buf);
10415   getpkt (&rs->buf, &rs->buf_size, 0);
10416
10417   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10418     {
10419     case PACKET_ERROR:
10420       if (rs->buf[1] == '.')
10421         {
10422           message = strchr (rs->buf + 2, '.');
10423           if (message)
10424             error (_("Remote failure reply: %s"), message + 1);
10425         }
10426       return -1;
10427     case PACKET_UNKNOWN:
10428       return -1;
10429     case PACKET_OK:
10430       return 0;
10431     }
10432   internal_error (__FILE__, __LINE__,
10433                   _("remote_insert_hw_breakpoint: reached end of function"));
10434 }
10435
10436
10437 int
10438 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10439                                      struct bp_target_info *bp_tgt)
10440 {
10441   CORE_ADDR addr;
10442   struct remote_state *rs = get_remote_state ();
10443   char *p = rs->buf;
10444   char *endbuf = rs->buf + get_remote_packet_size ();
10445
10446   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10447     return -1;
10448
10449   /* Make sure the remote is pointing at the right process, if
10450      necessary.  */
10451   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10452     set_general_process ();
10453
10454   *(p++) = 'z';
10455   *(p++) = '1';
10456   *(p++) = ',';
10457
10458   addr = remote_address_masked (bp_tgt->placed_address);
10459   p += hexnumstr (p, (ULONGEST) addr);
10460   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
10461
10462   putpkt (rs->buf);
10463   getpkt (&rs->buf, &rs->buf_size, 0);
10464
10465   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10466     {
10467     case PACKET_ERROR:
10468     case PACKET_UNKNOWN:
10469       return -1;
10470     case PACKET_OK:
10471       return 0;
10472     }
10473   internal_error (__FILE__, __LINE__,
10474                   _("remote_remove_hw_breakpoint: reached end of function"));
10475 }
10476
10477 /* Verify memory using the "qCRC:" request.  */
10478
10479 int
10480 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10481 {
10482   struct remote_state *rs = get_remote_state ();
10483   unsigned long host_crc, target_crc;
10484   char *tmp;
10485
10486   /* It doesn't make sense to use qCRC if the remote target is
10487      connected but not running.  */
10488   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10489     {
10490       enum packet_result result;
10491
10492       /* Make sure the remote is pointing at the right process.  */
10493       set_general_process ();
10494
10495       /* FIXME: assumes lma can fit into long.  */
10496       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10497                  (long) lma, (long) size);
10498       putpkt (rs->buf);
10499
10500       /* Be clever; compute the host_crc before waiting for target
10501          reply.  */
10502       host_crc = xcrc32 (data, size, 0xffffffff);
10503
10504       getpkt (&rs->buf, &rs->buf_size, 0);
10505
10506       result = packet_ok (rs->buf,
10507                           &remote_protocol_packets[PACKET_qCRC]);
10508       if (result == PACKET_ERROR)
10509         return -1;
10510       else if (result == PACKET_OK)
10511         {
10512           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10513             target_crc = target_crc * 16 + fromhex (*tmp);
10514
10515           return (host_crc == target_crc);
10516         }
10517     }
10518
10519   return simple_verify_memory (this, data, lma, size);
10520 }
10521
10522 /* compare-sections command
10523
10524    With no arguments, compares each loadable section in the exec bfd
10525    with the same memory range on the target, and reports mismatches.
10526    Useful for verifying the image on the target against the exec file.  */
10527
10528 static void
10529 compare_sections_command (const char *args, int from_tty)
10530 {
10531   asection *s;
10532   const char *sectname;
10533   bfd_size_type size;
10534   bfd_vma lma;
10535   int matched = 0;
10536   int mismatched = 0;
10537   int res;
10538   int read_only = 0;
10539
10540   if (!exec_bfd)
10541     error (_("command cannot be used without an exec file"));
10542
10543   if (args != NULL && strcmp (args, "-r") == 0)
10544     {
10545       read_only = 1;
10546       args = NULL;
10547     }
10548
10549   for (s = exec_bfd->sections; s; s = s->next)
10550     {
10551       if (!(s->flags & SEC_LOAD))
10552         continue;               /* Skip non-loadable section.  */
10553
10554       if (read_only && (s->flags & SEC_READONLY) == 0)
10555         continue;               /* Skip writeable sections */
10556
10557       size = bfd_get_section_size (s);
10558       if (size == 0)
10559         continue;               /* Skip zero-length section.  */
10560
10561       sectname = bfd_get_section_name (exec_bfd, s);
10562       if (args && strcmp (args, sectname) != 0)
10563         continue;               /* Not the section selected by user.  */
10564
10565       matched = 1;              /* Do this section.  */
10566       lma = s->lma;
10567
10568       gdb::byte_vector sectdata (size);
10569       bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10570
10571       res = target_verify_memory (sectdata.data (), lma, size);
10572
10573       if (res == -1)
10574         error (_("target memory fault, section %s, range %s -- %s"), sectname,
10575                paddress (target_gdbarch (), lma),
10576                paddress (target_gdbarch (), lma + size));
10577
10578       printf_filtered ("Section %s, range %s -- %s: ", sectname,
10579                        paddress (target_gdbarch (), lma),
10580                        paddress (target_gdbarch (), lma + size));
10581       if (res)
10582         printf_filtered ("matched.\n");
10583       else
10584         {
10585           printf_filtered ("MIS-MATCHED!\n");
10586           mismatched++;
10587         }
10588     }
10589   if (mismatched > 0)
10590     warning (_("One or more sections of the target image does not match\n\
10591 the loaded file\n"));
10592   if (args && !matched)
10593     printf_filtered (_("No loaded section named '%s'.\n"), args);
10594 }
10595
10596 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10597    into remote target.  The number of bytes written to the remote
10598    target is returned, or -1 for error.  */
10599
10600 static enum target_xfer_status
10601 remote_write_qxfer (const char *object_name,
10602                     const char *annex, const gdb_byte *writebuf, 
10603                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10604                     struct packet_config *packet)
10605 {
10606   int i, buf_len;
10607   ULONGEST n;
10608   struct remote_state *rs = get_remote_state ();
10609   int max_size = get_memory_write_packet_size (); 
10610
10611   if (packet_config_support (packet) == PACKET_DISABLE)
10612     return TARGET_XFER_E_IO;
10613
10614   /* Insert header.  */
10615   i = snprintf (rs->buf, max_size, 
10616                 "qXfer:%s:write:%s:%s:",
10617                 object_name, annex ? annex : "",
10618                 phex_nz (offset, sizeof offset));
10619   max_size -= (i + 1);
10620
10621   /* Escape as much data as fits into rs->buf.  */
10622   buf_len = remote_escape_output 
10623     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10624
10625   if (putpkt_binary (rs->buf, i + buf_len) < 0
10626       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10627       || packet_ok (rs->buf, packet) != PACKET_OK)
10628     return TARGET_XFER_E_IO;
10629
10630   unpack_varlen_hex (rs->buf, &n);
10631
10632   *xfered_len = n;
10633   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10634 }
10635
10636 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10637    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10638    number of bytes read is returned, or 0 for EOF, or -1 for error.
10639    The number of bytes read may be less than LEN without indicating an
10640    EOF.  PACKET is checked and updated to indicate whether the remote
10641    target supports this object.  */
10642
10643 static enum target_xfer_status
10644 remote_read_qxfer (const char *object_name,
10645                    const char *annex,
10646                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10647                    ULONGEST *xfered_len,
10648                    struct packet_config *packet)
10649 {
10650   struct remote_state *rs = get_remote_state ();
10651   LONGEST i, n, packet_len;
10652
10653   if (packet_config_support (packet) == PACKET_DISABLE)
10654     return TARGET_XFER_E_IO;
10655
10656   /* Check whether we've cached an end-of-object packet that matches
10657      this request.  */
10658   if (rs->finished_object)
10659     {
10660       if (strcmp (object_name, rs->finished_object) == 0
10661           && strcmp (annex ? annex : "", rs->finished_annex) == 0
10662           && offset == rs->finished_offset)
10663         return TARGET_XFER_EOF;
10664
10665
10666       /* Otherwise, we're now reading something different.  Discard
10667          the cache.  */
10668       xfree (rs->finished_object);
10669       xfree (rs->finished_annex);
10670       rs->finished_object = NULL;
10671       rs->finished_annex = NULL;
10672     }
10673
10674   /* Request only enough to fit in a single packet.  The actual data
10675      may not, since we don't know how much of it will need to be escaped;
10676      the target is free to respond with slightly less data.  We subtract
10677      five to account for the response type and the protocol frame.  */
10678   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10679   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10680             object_name, annex ? annex : "",
10681             phex_nz (offset, sizeof offset),
10682             phex_nz (n, sizeof n));
10683   i = putpkt (rs->buf);
10684   if (i < 0)
10685     return TARGET_XFER_E_IO;
10686
10687   rs->buf[0] = '\0';
10688   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10689   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10690     return TARGET_XFER_E_IO;
10691
10692   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10693     error (_("Unknown remote qXfer reply: %s"), rs->buf);
10694
10695   /* 'm' means there is (or at least might be) more data after this
10696      batch.  That does not make sense unless there's at least one byte
10697      of data in this reply.  */
10698   if (rs->buf[0] == 'm' && packet_len == 1)
10699     error (_("Remote qXfer reply contained no data."));
10700
10701   /* Got some data.  */
10702   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10703                              packet_len - 1, readbuf, n);
10704
10705   /* 'l' is an EOF marker, possibly including a final block of data,
10706      or possibly empty.  If we have the final block of a non-empty
10707      object, record this fact to bypass a subsequent partial read.  */
10708   if (rs->buf[0] == 'l' && offset + i > 0)
10709     {
10710       rs->finished_object = xstrdup (object_name);
10711       rs->finished_annex = xstrdup (annex ? annex : "");
10712       rs->finished_offset = offset + i;
10713     }
10714
10715   if (i == 0)
10716     return TARGET_XFER_EOF;
10717   else
10718     {
10719       *xfered_len = i;
10720       return TARGET_XFER_OK;
10721     }
10722 }
10723
10724 enum target_xfer_status
10725 remote_target::xfer_partial (enum target_object object,
10726                              const char *annex, gdb_byte *readbuf,
10727                              const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10728                              ULONGEST *xfered_len)
10729 {
10730   struct remote_state *rs;
10731   int i;
10732   char *p2;
10733   char query_type;
10734   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10735
10736   set_remote_traceframe ();
10737   set_general_thread (inferior_ptid);
10738
10739   rs = get_remote_state ();
10740
10741   /* Handle memory using the standard memory routines.  */
10742   if (object == TARGET_OBJECT_MEMORY)
10743     {
10744       /* If the remote target is connected but not running, we should
10745          pass this request down to a lower stratum (e.g. the executable
10746          file).  */
10747       if (!target_has_execution)
10748         return TARGET_XFER_EOF;
10749
10750       if (writebuf != NULL)
10751         return remote_write_bytes (offset, writebuf, len, unit_size,
10752                                    xfered_len);
10753       else
10754         return remote_read_bytes (this, offset, readbuf, len, unit_size,
10755                                   xfered_len);
10756     }
10757
10758   /* Handle SPU memory using qxfer packets.  */
10759   if (object == TARGET_OBJECT_SPU)
10760     {
10761       if (readbuf)
10762         return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10763                                   xfered_len, &remote_protocol_packets
10764                                   [PACKET_qXfer_spu_read]);
10765       else
10766         return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10767                                    xfered_len, &remote_protocol_packets
10768                                    [PACKET_qXfer_spu_write]);
10769     }
10770
10771   /* Handle extra signal info using qxfer packets.  */
10772   if (object == TARGET_OBJECT_SIGNAL_INFO)
10773     {
10774       if (readbuf)
10775         return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10776                                   xfered_len, &remote_protocol_packets
10777                                   [PACKET_qXfer_siginfo_read]);
10778       else
10779         return remote_write_qxfer ("siginfo", annex,
10780                                    writebuf, offset, len, xfered_len,
10781                                    &remote_protocol_packets
10782                                    [PACKET_qXfer_siginfo_write]);
10783     }
10784
10785   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10786     {
10787       if (readbuf)
10788         return remote_read_qxfer ("statictrace", annex,
10789                                   readbuf, offset, len, xfered_len,
10790                                   &remote_protocol_packets
10791                                   [PACKET_qXfer_statictrace_read]);
10792       else
10793         return TARGET_XFER_E_IO;
10794     }
10795
10796   /* Only handle flash writes.  */
10797   if (writebuf != NULL)
10798     {
10799       switch (object)
10800         {
10801         case TARGET_OBJECT_FLASH:
10802           return remote_flash_write (this, offset, len, xfered_len,
10803                                      writebuf);
10804
10805         default:
10806           return TARGET_XFER_E_IO;
10807         }
10808     }
10809
10810   /* Map pre-existing objects onto letters.  DO NOT do this for new
10811      objects!!!  Instead specify new query packets.  */
10812   switch (object)
10813     {
10814     case TARGET_OBJECT_AVR:
10815       query_type = 'R';
10816       break;
10817
10818     case TARGET_OBJECT_AUXV:
10819       gdb_assert (annex == NULL);
10820       return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10821                                 xfered_len,
10822                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10823
10824     case TARGET_OBJECT_AVAILABLE_FEATURES:
10825       return remote_read_qxfer
10826         ("features", annex, readbuf, offset, len, xfered_len,
10827          &remote_protocol_packets[PACKET_qXfer_features]);
10828
10829     case TARGET_OBJECT_LIBRARIES:
10830       return remote_read_qxfer
10831         ("libraries", annex, readbuf, offset, len, xfered_len,
10832          &remote_protocol_packets[PACKET_qXfer_libraries]);
10833
10834     case TARGET_OBJECT_LIBRARIES_SVR4:
10835       return remote_read_qxfer
10836         ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10837          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10838
10839     case TARGET_OBJECT_MEMORY_MAP:
10840       gdb_assert (annex == NULL);
10841       return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10842                                  xfered_len,
10843                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10844
10845     case TARGET_OBJECT_OSDATA:
10846       /* Should only get here if we're connected.  */
10847       gdb_assert (rs->remote_desc);
10848       return remote_read_qxfer
10849         ("osdata", annex, readbuf, offset, len, xfered_len,
10850         &remote_protocol_packets[PACKET_qXfer_osdata]);
10851
10852     case TARGET_OBJECT_THREADS:
10853       gdb_assert (annex == NULL);
10854       return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10855                                 xfered_len,
10856                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10857
10858     case TARGET_OBJECT_TRACEFRAME_INFO:
10859       gdb_assert (annex == NULL);
10860       return remote_read_qxfer
10861         ("traceframe-info", annex, readbuf, offset, len, xfered_len,
10862          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10863
10864     case TARGET_OBJECT_FDPIC:
10865       return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
10866                                 xfered_len,
10867                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10868
10869     case TARGET_OBJECT_OPENVMS_UIB:
10870       return remote_read_qxfer ("uib", annex, readbuf, offset, len,
10871                                 xfered_len,
10872                                 &remote_protocol_packets[PACKET_qXfer_uib]);
10873
10874     case TARGET_OBJECT_BTRACE:
10875       return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
10876                                 xfered_len,
10877         &remote_protocol_packets[PACKET_qXfer_btrace]);
10878
10879     case TARGET_OBJECT_BTRACE_CONF:
10880       return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
10881                                 len, xfered_len,
10882         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10883
10884     case TARGET_OBJECT_EXEC_FILE:
10885       return remote_read_qxfer ("exec-file", annex, readbuf, offset,
10886                                 len, xfered_len,
10887         &remote_protocol_packets[PACKET_qXfer_exec_file]);
10888
10889     default:
10890       return TARGET_XFER_E_IO;
10891     }
10892
10893   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
10894      large enough let the caller deal with it.  */
10895   if (len < get_remote_packet_size ())
10896     return TARGET_XFER_E_IO;
10897   len = get_remote_packet_size ();
10898
10899   /* Except for querying the minimum buffer size, target must be open.  */
10900   if (!rs->remote_desc)
10901     error (_("remote query is only available after target open"));
10902
10903   gdb_assert (annex != NULL);
10904   gdb_assert (readbuf != NULL);
10905
10906   p2 = rs->buf;
10907   *p2++ = 'q';
10908   *p2++ = query_type;
10909
10910   /* We used one buffer char for the remote protocol q command and
10911      another for the query type.  As the remote protocol encapsulation
10912      uses 4 chars plus one extra in case we are debugging
10913      (remote_debug), we have PBUFZIZ - 7 left to pack the query
10914      string.  */
10915   i = 0;
10916   while (annex[i] && (i < (get_remote_packet_size () - 8)))
10917     {
10918       /* Bad caller may have sent forbidden characters.  */
10919       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10920       *p2++ = annex[i];
10921       i++;
10922     }
10923   *p2 = '\0';
10924   gdb_assert (annex[i] == '\0');
10925
10926   i = putpkt (rs->buf);
10927   if (i < 0)
10928     return TARGET_XFER_E_IO;
10929
10930   getpkt (&rs->buf, &rs->buf_size, 0);
10931   strcpy ((char *) readbuf, rs->buf);
10932
10933   *xfered_len = strlen ((char *) readbuf);
10934   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10935 }
10936
10937 /* Implementation of to_get_memory_xfer_limit.  */
10938
10939 ULONGEST
10940 remote_target::get_memory_xfer_limit ()
10941 {
10942   return get_memory_write_packet_size ();
10943 }
10944
10945 int
10946 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
10947                               const gdb_byte *pattern, ULONGEST pattern_len,
10948                               CORE_ADDR *found_addrp)
10949 {
10950   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10951   struct remote_state *rs = get_remote_state ();
10952   int max_size = get_memory_write_packet_size ();
10953   struct packet_config *packet =
10954     &remote_protocol_packets[PACKET_qSearch_memory];
10955   /* Number of packet bytes used to encode the pattern;
10956      this could be more than PATTERN_LEN due to escape characters.  */
10957   int escaped_pattern_len;
10958   /* Amount of pattern that was encodable in the packet.  */
10959   int used_pattern_len;
10960   int i;
10961   int found;
10962   ULONGEST found_addr;
10963
10964   /* Don't go to the target if we don't have to.  This is done before
10965      checking packet_config_support to avoid the possibility that a
10966      success for this edge case means the facility works in
10967      general.  */
10968   if (pattern_len > search_space_len)
10969     return 0;
10970   if (pattern_len == 0)
10971     {
10972       *found_addrp = start_addr;
10973       return 1;
10974     }
10975
10976   /* If we already know the packet isn't supported, fall back to the simple
10977      way of searching memory.  */
10978
10979   if (packet_config_support (packet) == PACKET_DISABLE)
10980     {
10981       /* Target doesn't provided special support, fall back and use the
10982          standard support (copy memory and do the search here).  */
10983       return simple_search_memory (this, start_addr, search_space_len,
10984                                    pattern, pattern_len, found_addrp);
10985     }
10986
10987   /* Make sure the remote is pointing at the right process.  */
10988   set_general_process ();
10989
10990   /* Insert header.  */
10991   i = snprintf (rs->buf, max_size, 
10992                 "qSearch:memory:%s;%s;",
10993                 phex_nz (start_addr, addr_size),
10994                 phex_nz (search_space_len, sizeof (search_space_len)));
10995   max_size -= (i + 1);
10996
10997   /* Escape as much data as fits into rs->buf.  */
10998   escaped_pattern_len =
10999     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
11000                           &used_pattern_len, max_size);
11001
11002   /* Bail if the pattern is too large.  */
11003   if (used_pattern_len != pattern_len)
11004     error (_("Pattern is too large to transmit to remote target."));
11005
11006   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11007       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11008       || packet_ok (rs->buf, packet) != PACKET_OK)
11009     {
11010       /* The request may not have worked because the command is not
11011          supported.  If so, fall back to the simple way.  */
11012       if (packet_config_support (packet) == PACKET_DISABLE)
11013         {
11014           return simple_search_memory (this, start_addr, search_space_len,
11015                                        pattern, pattern_len, found_addrp);
11016         }
11017       return -1;
11018     }
11019
11020   if (rs->buf[0] == '0')
11021     found = 0;
11022   else if (rs->buf[0] == '1')
11023     {
11024       found = 1;
11025       if (rs->buf[1] != ',')
11026         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11027       unpack_varlen_hex (rs->buf + 2, &found_addr);
11028       *found_addrp = found_addr;
11029     }
11030   else
11031     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11032
11033   return found;
11034 }
11035
11036 void
11037 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11038 {
11039   struct remote_state *rs = get_remote_state ();
11040   char *p = rs->buf;
11041
11042   if (!rs->remote_desc)
11043     error (_("remote rcmd is only available after target open"));
11044
11045   /* Send a NULL command across as an empty command.  */
11046   if (command == NULL)
11047     command = "";
11048
11049   /* The query prefix.  */
11050   strcpy (rs->buf, "qRcmd,");
11051   p = strchr (rs->buf, '\0');
11052
11053   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11054       > get_remote_packet_size ())
11055     error (_("\"monitor\" command ``%s'' is too long."), command);
11056
11057   /* Encode the actual command.  */
11058   bin2hex ((const gdb_byte *) command, p, strlen (command));
11059
11060   if (putpkt (rs->buf) < 0)
11061     error (_("Communication problem with target."));
11062
11063   /* get/display the response */
11064   while (1)
11065     {
11066       char *buf;
11067
11068       /* XXX - see also remote_get_noisy_reply().  */
11069       QUIT;                     /* Allow user to bail out with ^C.  */
11070       rs->buf[0] = '\0';
11071       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11072         { 
11073           /* Timeout.  Continue to (try to) read responses.
11074              This is better than stopping with an error, assuming the stub
11075              is still executing the (long) monitor command.
11076              If needed, the user can interrupt gdb using C-c, obtaining
11077              an effect similar to stop on timeout.  */
11078           continue;
11079         }
11080       buf = rs->buf;
11081       if (buf[0] == '\0')
11082         error (_("Target does not support this command."));
11083       if (buf[0] == 'O' && buf[1] != 'K')
11084         {
11085           remote_console_output (buf + 1); /* 'O' message from stub.  */
11086           continue;
11087         }
11088       if (strcmp (buf, "OK") == 0)
11089         break;
11090       if (strlen (buf) == 3 && buf[0] == 'E'
11091           && isdigit (buf[1]) && isdigit (buf[2]))
11092         {
11093           error (_("Protocol error with Rcmd"));
11094         }
11095       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11096         {
11097           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11098
11099           fputc_unfiltered (c, outbuf);
11100         }
11101       break;
11102     }
11103 }
11104
11105 std::vector<mem_region>
11106 remote_target::memory_map ()
11107 {
11108   std::vector<mem_region> result;
11109   gdb::optional<gdb::char_vector> text
11110     = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
11111
11112   if (text)
11113     result = parse_memory_map (text->data ());
11114
11115   return result;
11116 }
11117
11118 static void
11119 packet_command (const char *args, int from_tty)
11120 {
11121   struct remote_state *rs = get_remote_state ();
11122
11123   if (!rs->remote_desc)
11124     error (_("command can only be used with remote target"));
11125
11126   if (!args)
11127     error (_("remote-packet command requires packet text as argument"));
11128
11129   puts_filtered ("sending: ");
11130   print_packet (args);
11131   puts_filtered ("\n");
11132   putpkt (args);
11133
11134   getpkt (&rs->buf, &rs->buf_size, 0);
11135   puts_filtered ("received: ");
11136   print_packet (rs->buf);
11137   puts_filtered ("\n");
11138 }
11139
11140 #if 0
11141 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11142
11143 static void display_thread_info (struct gdb_ext_thread_info *info);
11144
11145 static void threadset_test_cmd (char *cmd, int tty);
11146
11147 static void threadalive_test (char *cmd, int tty);
11148
11149 static void threadlist_test_cmd (char *cmd, int tty);
11150
11151 int get_and_display_threadinfo (threadref *ref);
11152
11153 static void threadinfo_test_cmd (char *cmd, int tty);
11154
11155 static int thread_display_step (threadref *ref, void *context);
11156
11157 static void threadlist_update_test_cmd (char *cmd, int tty);
11158
11159 static void init_remote_threadtests (void);
11160
11161 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
11162
11163 static void
11164 threadset_test_cmd (const char *cmd, int tty)
11165 {
11166   int sample_thread = SAMPLE_THREAD;
11167
11168   printf_filtered (_("Remote threadset test\n"));
11169   set_general_thread (sample_thread);
11170 }
11171
11172
11173 static void
11174 threadalive_test (const char *cmd, int tty)
11175 {
11176   int sample_thread = SAMPLE_THREAD;
11177   int pid = ptid_get_pid (inferior_ptid);
11178   ptid_t ptid = ptid_build (pid, sample_thread, 0);
11179
11180   if (remote_thread_alive (ptid))
11181     printf_filtered ("PASS: Thread alive test\n");
11182   else
11183     printf_filtered ("FAIL: Thread alive test\n");
11184 }
11185
11186 void output_threadid (char *title, threadref *ref);
11187
11188 void
11189 output_threadid (char *title, threadref *ref)
11190 {
11191   char hexid[20];
11192
11193   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
11194   hexid[16] = 0;
11195   printf_filtered ("%s  %s\n", title, (&hexid[0]));
11196 }
11197
11198 static void
11199 threadlist_test_cmd (const char *cmd, int tty)
11200 {
11201   int startflag = 1;
11202   threadref nextthread;
11203   int done, result_count;
11204   threadref threadlist[3];
11205
11206   printf_filtered ("Remote Threadlist test\n");
11207   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11208                               &result_count, &threadlist[0]))
11209     printf_filtered ("FAIL: threadlist test\n");
11210   else
11211     {
11212       threadref *scan = threadlist;
11213       threadref *limit = scan + result_count;
11214
11215       while (scan < limit)
11216         output_threadid (" thread ", scan++);
11217     }
11218 }
11219
11220 void
11221 display_thread_info (struct gdb_ext_thread_info *info)
11222 {
11223   output_threadid ("Threadid: ", &info->threadid);
11224   printf_filtered ("Name: %s\n ", info->shortname);
11225   printf_filtered ("State: %s\n", info->display);
11226   printf_filtered ("other: %s\n\n", info->more_display);
11227 }
11228
11229 int
11230 get_and_display_threadinfo (threadref *ref)
11231 {
11232   int result;
11233   int set;
11234   struct gdb_ext_thread_info threadinfo;
11235
11236   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11237     | TAG_MOREDISPLAY | TAG_DISPLAY;
11238   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11239     display_thread_info (&threadinfo);
11240   return result;
11241 }
11242
11243 static void
11244 threadinfo_test_cmd (const char *cmd, int tty)
11245 {
11246   int athread = SAMPLE_THREAD;
11247   threadref thread;
11248   int set;
11249
11250   int_to_threadref (&thread, athread);
11251   printf_filtered ("Remote Threadinfo test\n");
11252   if (!get_and_display_threadinfo (&thread))
11253     printf_filtered ("FAIL cannot get thread info\n");
11254 }
11255
11256 static int
11257 thread_display_step (threadref *ref, void *context)
11258 {
11259   /* output_threadid(" threadstep ",ref); *//* simple test */
11260   return get_and_display_threadinfo (ref);
11261 }
11262
11263 static void
11264 threadlist_update_test_cmd (const char *cmd, int tty)
11265 {
11266   printf_filtered ("Remote Threadlist update test\n");
11267   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11268 }
11269
11270 static void
11271 init_remote_threadtests (void)
11272 {
11273   add_com ("tlist", class_obscure, threadlist_test_cmd,
11274            _("Fetch and print the remote list of "
11275              "thread identifiers, one pkt only"));
11276   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11277            _("Fetch and display info about one thread"));
11278   add_com ("tset", class_obscure, threadset_test_cmd,
11279            _("Test setting to a different thread"));
11280   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11281            _("Iterate through updating all remote thread info"));
11282   add_com ("talive", class_obscure, threadalive_test,
11283            _(" Remote thread alive test "));
11284 }
11285
11286 #endif /* 0 */
11287
11288 /* Convert a thread ID to a string.  Returns the string in a static
11289    buffer.  */
11290
11291 const char *
11292 remote_target::pid_to_str (ptid_t ptid)
11293 {
11294   static char buf[64];
11295   struct remote_state *rs = get_remote_state ();
11296
11297   if (ptid_equal (ptid, null_ptid))
11298     return normal_pid_to_str (ptid);
11299   else if (ptid_is_pid (ptid))
11300     {
11301       /* Printing an inferior target id.  */
11302
11303       /* When multi-process extensions are off, there's no way in the
11304          remote protocol to know the remote process id, if there's any
11305          at all.  There's one exception --- when we're connected with
11306          target extended-remote, and we manually attached to a process
11307          with "attach PID".  We don't record anywhere a flag that
11308          allows us to distinguish that case from the case of
11309          connecting with extended-remote and the stub already being
11310          attached to a process, and reporting yes to qAttached, hence
11311          no smart special casing here.  */
11312       if (!remote_multi_process_p (rs))
11313         {
11314           xsnprintf (buf, sizeof buf, "Remote target");
11315           return buf;
11316         }
11317
11318       return normal_pid_to_str (ptid);
11319     }
11320   else
11321     {
11322       if (ptid_equal (magic_null_ptid, ptid))
11323         xsnprintf (buf, sizeof buf, "Thread <main>");
11324       else if (remote_multi_process_p (rs))
11325         if (ptid_get_lwp (ptid) == 0)
11326           return normal_pid_to_str (ptid);
11327         else
11328           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11329                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
11330       else
11331         xsnprintf (buf, sizeof buf, "Thread %ld",
11332                    ptid_get_lwp (ptid));
11333       return buf;
11334     }
11335 }
11336
11337 /* Get the address of the thread local variable in OBJFILE which is
11338    stored at OFFSET within the thread local storage for thread PTID.  */
11339
11340 CORE_ADDR
11341 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11342                                          CORE_ADDR offset)
11343 {
11344   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11345     {
11346       struct remote_state *rs = get_remote_state ();
11347       char *p = rs->buf;
11348       char *endp = rs->buf + get_remote_packet_size ();
11349       enum packet_result result;
11350
11351       strcpy (p, "qGetTLSAddr:");
11352       p += strlen (p);
11353       p = write_ptid (p, endp, ptid);
11354       *p++ = ',';
11355       p += hexnumstr (p, offset);
11356       *p++ = ',';
11357       p += hexnumstr (p, lm);
11358       *p++ = '\0';
11359
11360       putpkt (rs->buf);
11361       getpkt (&rs->buf, &rs->buf_size, 0);
11362       result = packet_ok (rs->buf,
11363                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
11364       if (result == PACKET_OK)
11365         {
11366           ULONGEST result;
11367
11368           unpack_varlen_hex (rs->buf, &result);
11369           return result;
11370         }
11371       else if (result == PACKET_UNKNOWN)
11372         throw_error (TLS_GENERIC_ERROR,
11373                      _("Remote target doesn't support qGetTLSAddr packet"));
11374       else
11375         throw_error (TLS_GENERIC_ERROR,
11376                      _("Remote target failed to process qGetTLSAddr request"));
11377     }
11378   else
11379     throw_error (TLS_GENERIC_ERROR,
11380                  _("TLS not supported or disabled on this target"));
11381   /* Not reached.  */
11382   return 0;
11383 }
11384
11385 /* Provide thread local base, i.e. Thread Information Block address.
11386    Returns 1 if ptid is found and thread_local_base is non zero.  */
11387
11388 bool
11389 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11390 {
11391   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11392     {
11393       struct remote_state *rs = get_remote_state ();
11394       char *p = rs->buf;
11395       char *endp = rs->buf + get_remote_packet_size ();
11396       enum packet_result result;
11397
11398       strcpy (p, "qGetTIBAddr:");
11399       p += strlen (p);
11400       p = write_ptid (p, endp, ptid);
11401       *p++ = '\0';
11402
11403       putpkt (rs->buf);
11404       getpkt (&rs->buf, &rs->buf_size, 0);
11405       result = packet_ok (rs->buf,
11406                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
11407       if (result == PACKET_OK)
11408         {
11409           ULONGEST result;
11410
11411           unpack_varlen_hex (rs->buf, &result);
11412           if (addr)
11413             *addr = (CORE_ADDR) result;
11414           return true;
11415         }
11416       else if (result == PACKET_UNKNOWN)
11417         error (_("Remote target doesn't support qGetTIBAddr packet"));
11418       else
11419         error (_("Remote target failed to process qGetTIBAddr request"));
11420     }
11421   else
11422     error (_("qGetTIBAddr not supported or disabled on this target"));
11423   /* Not reached.  */
11424   return false;
11425 }
11426
11427 /* Support for inferring a target description based on the current
11428    architecture and the size of a 'g' packet.  While the 'g' packet
11429    can have any size (since optional registers can be left off the
11430    end), some sizes are easily recognizable given knowledge of the
11431    approximate architecture.  */
11432
11433 struct remote_g_packet_guess
11434 {
11435   int bytes;
11436   const struct target_desc *tdesc;
11437 };
11438 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11439 DEF_VEC_O(remote_g_packet_guess_s);
11440
11441 struct remote_g_packet_data
11442 {
11443   VEC(remote_g_packet_guess_s) *guesses;
11444 };
11445
11446 static struct gdbarch_data *remote_g_packet_data_handle;
11447
11448 static void *
11449 remote_g_packet_data_init (struct obstack *obstack)
11450 {
11451   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11452 }
11453
11454 void
11455 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11456                                 const struct target_desc *tdesc)
11457 {
11458   struct remote_g_packet_data *data
11459     = ((struct remote_g_packet_data *)
11460        gdbarch_data (gdbarch, remote_g_packet_data_handle));
11461   struct remote_g_packet_guess new_guess, *guess;
11462   int ix;
11463
11464   gdb_assert (tdesc != NULL);
11465
11466   for (ix = 0;
11467        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11468        ix++)
11469     if (guess->bytes == bytes)
11470       internal_error (__FILE__, __LINE__,
11471                       _("Duplicate g packet description added for size %d"),
11472                       bytes);
11473
11474   new_guess.bytes = bytes;
11475   new_guess.tdesc = tdesc;
11476   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11477 }
11478
11479 /* Return 1 if remote_read_description would do anything on this target
11480    and architecture, 0 otherwise.  */
11481
11482 static int
11483 remote_read_description_p (struct target_ops *target)
11484 {
11485   struct remote_g_packet_data *data
11486     = ((struct remote_g_packet_data *)
11487        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11488
11489   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11490     return 1;
11491
11492   return 0;
11493 }
11494
11495 const struct target_desc *
11496 remote_target::read_description ()
11497 {
11498   struct remote_g_packet_data *data
11499     = ((struct remote_g_packet_data *)
11500        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11501
11502   /* Do not try this during initial connection, when we do not know
11503      whether there is a running but stopped thread.  */
11504   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11505     return beneath->read_description ();
11506
11507   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11508     {
11509       struct remote_g_packet_guess *guess;
11510       int ix;
11511       int bytes = send_g_packet ();
11512
11513       for (ix = 0;
11514            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11515            ix++)
11516         if (guess->bytes == bytes)
11517           return guess->tdesc;
11518
11519       /* We discard the g packet.  A minor optimization would be to
11520          hold on to it, and fill the register cache once we have selected
11521          an architecture, but it's too tricky to do safely.  */
11522     }
11523
11524   return beneath->read_description ();
11525 }
11526
11527 /* Remote file transfer support.  This is host-initiated I/O, not
11528    target-initiated; for target-initiated, see remote-fileio.c.  */
11529
11530 /* If *LEFT is at least the length of STRING, copy STRING to
11531    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11532    decrease *LEFT.  Otherwise raise an error.  */
11533
11534 static void
11535 remote_buffer_add_string (char **buffer, int *left, const char *string)
11536 {
11537   int len = strlen (string);
11538
11539   if (len > *left)
11540     error (_("Packet too long for target."));
11541
11542   memcpy (*buffer, string, len);
11543   *buffer += len;
11544   *left -= len;
11545
11546   /* NUL-terminate the buffer as a convenience, if there is
11547      room.  */
11548   if (*left)
11549     **buffer = '\0';
11550 }
11551
11552 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11553    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11554    decrease *LEFT.  Otherwise raise an error.  */
11555
11556 static void
11557 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11558                          int len)
11559 {
11560   if (2 * len > *left)
11561     error (_("Packet too long for target."));
11562
11563   bin2hex (bytes, *buffer, len);
11564   *buffer += 2 * len;
11565   *left -= 2 * len;
11566
11567   /* NUL-terminate the buffer as a convenience, if there is
11568      room.  */
11569   if (*left)
11570     **buffer = '\0';
11571 }
11572
11573 /* If *LEFT is large enough, convert VALUE to hex and add it to
11574    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11575    decrease *LEFT.  Otherwise raise an error.  */
11576
11577 static void
11578 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11579 {
11580   int len = hexnumlen (value);
11581
11582   if (len > *left)
11583     error (_("Packet too long for target."));
11584
11585   hexnumstr (*buffer, value);
11586   *buffer += len;
11587   *left -= len;
11588
11589   /* NUL-terminate the buffer as a convenience, if there is
11590      room.  */
11591   if (*left)
11592     **buffer = '\0';
11593 }
11594
11595 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
11596    value, *REMOTE_ERRNO to the remote error number or zero if none
11597    was included, and *ATTACHMENT to point to the start of the annex
11598    if any.  The length of the packet isn't needed here; there may
11599    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11600
11601    Return 0 if the packet could be parsed, -1 if it could not.  If
11602    -1 is returned, the other variables may not be initialized.  */
11603
11604 static int
11605 remote_hostio_parse_result (char *buffer, int *retcode,
11606                             int *remote_errno, char **attachment)
11607 {
11608   char *p, *p2;
11609
11610   *remote_errno = 0;
11611   *attachment = NULL;
11612
11613   if (buffer[0] != 'F')
11614     return -1;
11615
11616   errno = 0;
11617   *retcode = strtol (&buffer[1], &p, 16);
11618   if (errno != 0 || p == &buffer[1])
11619     return -1;
11620
11621   /* Check for ",errno".  */
11622   if (*p == ',')
11623     {
11624       errno = 0;
11625       *remote_errno = strtol (p + 1, &p2, 16);
11626       if (errno != 0 || p + 1 == p2)
11627         return -1;
11628       p = p2;
11629     }
11630
11631   /* Check for ";attachment".  If there is no attachment, the
11632      packet should end here.  */
11633   if (*p == ';')
11634     {
11635       *attachment = p + 1;
11636       return 0;
11637     }
11638   else if (*p == '\0')
11639     return 0;
11640   else
11641     return -1;
11642 }
11643
11644 /* Send a prepared I/O packet to the target and read its response.
11645    The prepared packet is in the global RS->BUF before this function
11646    is called, and the answer is there when we return.
11647
11648    COMMAND_BYTES is the length of the request to send, which may include
11649    binary data.  WHICH_PACKET is the packet configuration to check
11650    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
11651    is set to the error number and -1 is returned.  Otherwise the value
11652    returned by the function is returned.
11653
11654    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11655    attachment is expected; an error will be reported if there's a
11656    mismatch.  If one is found, *ATTACHMENT will be set to point into
11657    the packet buffer and *ATTACHMENT_LEN will be set to the
11658    attachment's length.  */
11659
11660 static int
11661 remote_hostio_send_command (int command_bytes, int which_packet,
11662                             int *remote_errno, char **attachment,
11663                             int *attachment_len)
11664 {
11665   struct remote_state *rs = get_remote_state ();
11666   int ret, bytes_read;
11667   char *attachment_tmp;
11668
11669   if (packet_support (which_packet) == PACKET_DISABLE)
11670     {
11671       *remote_errno = FILEIO_ENOSYS;
11672       return -1;
11673     }
11674
11675   putpkt_binary (rs->buf, command_bytes);
11676   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11677
11678   /* If it timed out, something is wrong.  Don't try to parse the
11679      buffer.  */
11680   if (bytes_read < 0)
11681     {
11682       *remote_errno = FILEIO_EINVAL;
11683       return -1;
11684     }
11685
11686   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11687     {
11688     case PACKET_ERROR:
11689       *remote_errno = FILEIO_EINVAL;
11690       return -1;
11691     case PACKET_UNKNOWN:
11692       *remote_errno = FILEIO_ENOSYS;
11693       return -1;
11694     case PACKET_OK:
11695       break;
11696     }
11697
11698   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11699                                   &attachment_tmp))
11700     {
11701       *remote_errno = FILEIO_EINVAL;
11702       return -1;
11703     }
11704
11705   /* Make sure we saw an attachment if and only if we expected one.  */
11706   if ((attachment_tmp == NULL && attachment != NULL)
11707       || (attachment_tmp != NULL && attachment == NULL))
11708     {
11709       *remote_errno = FILEIO_EINVAL;
11710       return -1;
11711     }
11712
11713   /* If an attachment was found, it must point into the packet buffer;
11714      work out how many bytes there were.  */
11715   if (attachment_tmp != NULL)
11716     {
11717       *attachment = attachment_tmp;
11718       *attachment_len = bytes_read - (*attachment - rs->buf);
11719     }
11720
11721   return ret;
11722 }
11723
11724 /* See declaration.h.  */
11725
11726 void
11727 readahead_cache::invalidate ()
11728 {
11729   this->fd = -1;
11730 }
11731
11732 /* See declaration.h.  */
11733
11734 void
11735 readahead_cache::invalidate_fd (int fd)
11736 {
11737   if (this->fd == fd)
11738     this->fd = -1;
11739 }
11740
11741 /* Set the filesystem remote_hostio functions that take FILENAME
11742    arguments will use.  Return 0 on success, or -1 if an error
11743    occurs (and set *REMOTE_ERRNO).  */
11744
11745 static int
11746 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11747 {
11748   struct remote_state *rs = get_remote_state ();
11749   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11750   char *p = rs->buf;
11751   int left = get_remote_packet_size () - 1;
11752   char arg[9];
11753   int ret;
11754
11755   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11756     return 0;
11757
11758   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11759     return 0;
11760
11761   remote_buffer_add_string (&p, &left, "vFile:setfs:");
11762
11763   xsnprintf (arg, sizeof (arg), "%x", required_pid);
11764   remote_buffer_add_string (&p, &left, arg);
11765
11766   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11767                                     remote_errno, NULL, NULL);
11768
11769   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11770     return 0;
11771
11772   if (ret == 0)
11773     rs->fs_pid = required_pid;
11774
11775   return ret;
11776 }
11777
11778 /* Implementation of to_fileio_open.  */
11779
11780 static int
11781 remote_hostio_open (struct target_ops *self,
11782                     struct inferior *inf, const char *filename,
11783                     int flags, int mode, int warn_if_slow,
11784                     int *remote_errno)
11785 {
11786   struct remote_state *rs = get_remote_state ();
11787   char *p = rs->buf;
11788   int left = get_remote_packet_size () - 1;
11789
11790   if (warn_if_slow)
11791     {
11792       static int warning_issued = 0;
11793
11794       printf_unfiltered (_("Reading %s from remote target...\n"),
11795                          filename);
11796
11797       if (!warning_issued)
11798         {
11799           warning (_("File transfers from remote targets can be slow."
11800                      " Use \"set sysroot\" to access files locally"
11801                      " instead."));
11802           warning_issued = 1;
11803         }
11804     }
11805
11806   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11807     return -1;
11808
11809   remote_buffer_add_string (&p, &left, "vFile:open:");
11810
11811   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11812                            strlen (filename));
11813   remote_buffer_add_string (&p, &left, ",");
11814
11815   remote_buffer_add_int (&p, &left, flags);
11816   remote_buffer_add_string (&p, &left, ",");
11817
11818   remote_buffer_add_int (&p, &left, mode);
11819
11820   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11821                                      remote_errno, NULL, NULL);
11822 }
11823
11824 int
11825 remote_target::fileio_open (struct inferior *inf, const char *filename,
11826                             int flags, int mode, int warn_if_slow,
11827                             int *remote_errno)
11828 {
11829   return remote_hostio_open (this, inf, filename, flags, mode, warn_if_slow,
11830                              remote_errno);
11831 }
11832
11833 /* Implementation of to_fileio_pwrite.  */
11834
11835 static int
11836 remote_hostio_pwrite (struct target_ops *self,
11837                       int fd, const gdb_byte *write_buf, int len,
11838                       ULONGEST offset, int *remote_errno)
11839 {
11840   struct remote_state *rs = get_remote_state ();
11841   char *p = rs->buf;
11842   int left = get_remote_packet_size ();
11843   int out_len;
11844
11845   rs->readahead_cache.invalidate_fd (fd);
11846
11847   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11848
11849   remote_buffer_add_int (&p, &left, fd);
11850   remote_buffer_add_string (&p, &left, ",");
11851
11852   remote_buffer_add_int (&p, &left, offset);
11853   remote_buffer_add_string (&p, &left, ",");
11854
11855   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11856                              get_remote_packet_size () - (p - rs->buf));
11857
11858   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11859                                      remote_errno, NULL, NULL);
11860 }
11861
11862 int
11863 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
11864                               ULONGEST offset, int *remote_errno)
11865 {
11866   return remote_hostio_pwrite (this, fd, write_buf, len, offset, remote_errno);
11867 }
11868
11869 /* Helper for the implementation of to_fileio_pread.  Read the file
11870    from the remote side with vFile:pread.  */
11871
11872 static int
11873 remote_hostio_pread_vFile (struct target_ops *self,
11874                            int fd, gdb_byte *read_buf, int len,
11875                            ULONGEST offset, int *remote_errno)
11876 {
11877   struct remote_state *rs = get_remote_state ();
11878   char *p = rs->buf;
11879   char *attachment;
11880   int left = get_remote_packet_size ();
11881   int ret, attachment_len;
11882   int read_len;
11883
11884   remote_buffer_add_string (&p, &left, "vFile:pread:");
11885
11886   remote_buffer_add_int (&p, &left, fd);
11887   remote_buffer_add_string (&p, &left, ",");
11888
11889   remote_buffer_add_int (&p, &left, len);
11890   remote_buffer_add_string (&p, &left, ",");
11891
11892   remote_buffer_add_int (&p, &left, offset);
11893
11894   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11895                                     remote_errno, &attachment,
11896                                     &attachment_len);
11897
11898   if (ret < 0)
11899     return ret;
11900
11901   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11902                                     read_buf, len);
11903   if (read_len != ret)
11904     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11905
11906   return ret;
11907 }
11908
11909 /* See declaration.h.  */
11910
11911 int
11912 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
11913                         ULONGEST offset)
11914 {
11915   if (this->fd == fd
11916       && this->offset <= offset
11917       && offset < this->offset + this->bufsize)
11918     {
11919       ULONGEST max = this->offset + this->bufsize;
11920
11921       if (offset + len > max)
11922         len = max - offset;
11923
11924       memcpy (read_buf, this->buf + offset - this->offset, len);
11925       return len;
11926     }
11927
11928   return 0;
11929 }
11930
11931 /* Implementation of to_fileio_pread.  */
11932
11933 static int
11934 remote_hostio_pread (struct target_ops *self,
11935                      int fd, gdb_byte *read_buf, int len,
11936                      ULONGEST offset, int *remote_errno)
11937 {
11938   int ret;
11939   struct remote_state *rs = get_remote_state ();
11940   readahead_cache *cache = &rs->readahead_cache;
11941
11942   ret = cache->pread (fd, read_buf, len, offset);
11943   if (ret > 0)
11944     {
11945       cache->hit_count++;
11946
11947       if (remote_debug)
11948         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11949                             pulongest (cache->hit_count));
11950       return ret;
11951     }
11952
11953   cache->miss_count++;
11954   if (remote_debug)
11955     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11956                         pulongest (cache->miss_count));
11957
11958   cache->fd = fd;
11959   cache->offset = offset;
11960   cache->bufsize = get_remote_packet_size ();
11961   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11962
11963   ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11964                                    cache->offset, remote_errno);
11965   if (ret <= 0)
11966     {
11967       cache->invalidate_fd (fd);
11968       return ret;
11969     }
11970
11971   cache->bufsize = ret;
11972   return cache->pread (fd, read_buf, len, offset);
11973 }
11974
11975 int
11976 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
11977                              ULONGEST offset, int *remote_errno)
11978 {
11979   return remote_hostio_pread (this, fd, read_buf, len, offset, remote_errno);
11980 }
11981
11982 /* Implementation of to_fileio_close.  */
11983
11984 static int
11985 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11986 {
11987   struct remote_state *rs = get_remote_state ();
11988   char *p = rs->buf;
11989   int left = get_remote_packet_size () - 1;
11990
11991   rs->readahead_cache.invalidate_fd (fd);
11992
11993   remote_buffer_add_string (&p, &left, "vFile:close:");
11994
11995   remote_buffer_add_int (&p, &left, fd);
11996
11997   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11998                                      remote_errno, NULL, NULL);
11999 }
12000
12001 int
12002 remote_target::fileio_close (int fd, int *remote_errno)
12003 {
12004   return remote_hostio_close (this, fd, remote_errno);
12005 }
12006
12007 /* Implementation of to_fileio_unlink.  */
12008
12009 static int
12010 remote_hostio_unlink (struct target_ops *self,
12011                       struct inferior *inf, const char *filename,
12012                       int *remote_errno)
12013 {
12014   struct remote_state *rs = get_remote_state ();
12015   char *p = rs->buf;
12016   int left = get_remote_packet_size () - 1;
12017
12018   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12019     return -1;
12020
12021   remote_buffer_add_string (&p, &left, "vFile:unlink:");
12022
12023   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12024                            strlen (filename));
12025
12026   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12027                                      remote_errno, NULL, NULL);
12028 }
12029
12030 int
12031 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12032                               int *remote_errno)
12033 {
12034   return remote_hostio_unlink (this, inf, filename, remote_errno);
12035 }
12036
12037 /* Implementation of to_fileio_readlink.  */
12038
12039 gdb::optional<std::string>
12040 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12041                                 int *remote_errno)
12042 {
12043   struct remote_state *rs = get_remote_state ();
12044   char *p = rs->buf;
12045   char *attachment;
12046   int left = get_remote_packet_size ();
12047   int len, attachment_len;
12048   int read_len;
12049
12050   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12051     return {};
12052
12053   remote_buffer_add_string (&p, &left, "vFile:readlink:");
12054
12055   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12056                            strlen (filename));
12057
12058   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12059                                     remote_errno, &attachment,
12060                                     &attachment_len);
12061
12062   if (len < 0)
12063     return {};
12064
12065   std::string ret (len, '\0');
12066
12067   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12068                                     (gdb_byte *) &ret[0], len);
12069   if (read_len != len)
12070     error (_("Readlink returned %d, but %d bytes."), len, read_len);
12071
12072   return ret;
12073 }
12074
12075 /* Implementation of to_fileio_fstat.  */
12076
12077 int
12078 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12079 {
12080   struct remote_state *rs = get_remote_state ();
12081   char *p = rs->buf;
12082   int left = get_remote_packet_size ();
12083   int attachment_len, ret;
12084   char *attachment;
12085   struct fio_stat fst;
12086   int read_len;
12087
12088   remote_buffer_add_string (&p, &left, "vFile:fstat:");
12089
12090   remote_buffer_add_int (&p, &left, fd);
12091
12092   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12093                                     remote_errno, &attachment,
12094                                     &attachment_len);
12095   if (ret < 0)
12096     {
12097       if (*remote_errno != FILEIO_ENOSYS)
12098         return ret;
12099
12100       /* Strictly we should return -1, ENOSYS here, but when
12101          "set sysroot remote:" was implemented in August 2008
12102          BFD's need for a stat function was sidestepped with
12103          this hack.  This was not remedied until March 2015
12104          so we retain the previous behavior to avoid breaking
12105          compatibility.
12106
12107          Note that the memset is a March 2015 addition; older
12108          GDBs set st_size *and nothing else* so the structure
12109          would have garbage in all other fields.  This might
12110          break something but retaining the previous behavior
12111          here would be just too wrong.  */
12112
12113       memset (st, 0, sizeof (struct stat));
12114       st->st_size = INT_MAX;
12115       return 0;
12116     }
12117
12118   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12119                                     (gdb_byte *) &fst, sizeof (fst));
12120
12121   if (read_len != ret)
12122     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12123
12124   if (read_len != sizeof (fst))
12125     error (_("vFile:fstat returned %d bytes, but expecting %d."),
12126            read_len, (int) sizeof (fst));
12127
12128   remote_fileio_to_host_stat (&fst, st);
12129
12130   return 0;
12131 }
12132
12133 /* Implementation of to_filesystem_is_local.  */
12134
12135 bool
12136 remote_target::filesystem_is_local ()
12137 {
12138   /* Valgrind GDB presents itself as a remote target but works
12139      on the local filesystem: it does not implement remote get
12140      and users are not expected to set a sysroot.  To handle
12141      this case we treat the remote filesystem as local if the
12142      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12143      does not support vFile:open.  */
12144   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12145     {
12146       enum packet_support ps = packet_support (PACKET_vFile_open);
12147
12148       if (ps == PACKET_SUPPORT_UNKNOWN)
12149         {
12150           int fd, remote_errno;
12151
12152           /* Try opening a file to probe support.  The supplied
12153              filename is irrelevant, we only care about whether
12154              the stub recognizes the packet or not.  */
12155           fd = remote_hostio_open (this, NULL, "just probing",
12156                                    FILEIO_O_RDONLY, 0700, 0,
12157                                    &remote_errno);
12158
12159           if (fd >= 0)
12160             remote_hostio_close (this, fd, &remote_errno);
12161
12162           ps = packet_support (PACKET_vFile_open);
12163         }
12164
12165       if (ps == PACKET_DISABLE)
12166         {
12167           static int warning_issued = 0;
12168
12169           if (!warning_issued)
12170             {
12171               warning (_("remote target does not support file"
12172                          " transfer, attempting to access files"
12173                          " from local filesystem."));
12174               warning_issued = 1;
12175             }
12176
12177           return true;
12178         }
12179     }
12180
12181   return false;
12182 }
12183
12184 static int
12185 remote_fileio_errno_to_host (int errnum)
12186 {
12187   switch (errnum)
12188     {
12189       case FILEIO_EPERM:
12190         return EPERM;
12191       case FILEIO_ENOENT:
12192         return ENOENT;
12193       case FILEIO_EINTR:
12194         return EINTR;
12195       case FILEIO_EIO:
12196         return EIO;
12197       case FILEIO_EBADF:
12198         return EBADF;
12199       case FILEIO_EACCES:
12200         return EACCES;
12201       case FILEIO_EFAULT:
12202         return EFAULT;
12203       case FILEIO_EBUSY:
12204         return EBUSY;
12205       case FILEIO_EEXIST:
12206         return EEXIST;
12207       case FILEIO_ENODEV:
12208         return ENODEV;
12209       case FILEIO_ENOTDIR:
12210         return ENOTDIR;
12211       case FILEIO_EISDIR:
12212         return EISDIR;
12213       case FILEIO_EINVAL:
12214         return EINVAL;
12215       case FILEIO_ENFILE:
12216         return ENFILE;
12217       case FILEIO_EMFILE:
12218         return EMFILE;
12219       case FILEIO_EFBIG:
12220         return EFBIG;
12221       case FILEIO_ENOSPC:
12222         return ENOSPC;
12223       case FILEIO_ESPIPE:
12224         return ESPIPE;
12225       case FILEIO_EROFS:
12226         return EROFS;
12227       case FILEIO_ENOSYS:
12228         return ENOSYS;
12229       case FILEIO_ENAMETOOLONG:
12230         return ENAMETOOLONG;
12231     }
12232   return -1;
12233 }
12234
12235 static char *
12236 remote_hostio_error (int errnum)
12237 {
12238   int host_error = remote_fileio_errno_to_host (errnum);
12239
12240   if (host_error == -1)
12241     error (_("Unknown remote I/O error %d"), errnum);
12242   else
12243     error (_("Remote I/O error: %s"), safe_strerror (host_error));
12244 }
12245
12246 /* A RAII wrapper around a remote file descriptor.  */
12247
12248 class scoped_remote_fd
12249 {
12250 public:
12251   explicit scoped_remote_fd (int fd)
12252     : m_fd (fd)
12253   {
12254   }
12255
12256   ~scoped_remote_fd ()
12257   {
12258     if (m_fd != -1)
12259       {
12260         try
12261           {
12262             int remote_errno;
12263             remote_hostio_close (find_target_at (process_stratum),
12264                                  m_fd, &remote_errno);
12265           }
12266         catch (...)
12267           {
12268             /* Swallow exception before it escapes the dtor.  If
12269                something goes wrong, likely the connection is gone,
12270                and there's nothing else that can be done.  */
12271           }
12272       }
12273   }
12274
12275   DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12276
12277   /* Release ownership of the file descriptor, and return it.  */
12278   int release () noexcept
12279   {
12280     int fd = m_fd;
12281     m_fd = -1;
12282     return fd;
12283   }
12284
12285   /* Return the owned file descriptor.  */
12286   int get () const noexcept
12287   {
12288     return m_fd;
12289   }
12290
12291 private:
12292   /* The owned remote I/O file descriptor.  */
12293   int m_fd;
12294 };
12295
12296 void
12297 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12298 {
12299   struct cleanup *back_to;
12300   int retcode, remote_errno, bytes, io_size;
12301   gdb_byte *buffer;
12302   int bytes_in_buffer;
12303   int saw_eof;
12304   ULONGEST offset;
12305   struct remote_state *rs = get_remote_state ();
12306
12307   if (!rs->remote_desc)
12308     error (_("command can only be used with remote target"));
12309
12310   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12311   if (file == NULL)
12312     perror_with_name (local_file);
12313
12314   scoped_remote_fd fd
12315     (remote_hostio_open (find_target_at (process_stratum), NULL,
12316                          remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12317                                        | FILEIO_O_TRUNC),
12318                          0700, 0, &remote_errno));
12319   if (fd.get () == -1)
12320     remote_hostio_error (remote_errno);
12321
12322   /* Send up to this many bytes at once.  They won't all fit in the
12323      remote packet limit, so we'll transfer slightly fewer.  */
12324   io_size = get_remote_packet_size ();
12325   buffer = (gdb_byte *) xmalloc (io_size);
12326   back_to = make_cleanup (xfree, buffer);
12327
12328   bytes_in_buffer = 0;
12329   saw_eof = 0;
12330   offset = 0;
12331   while (bytes_in_buffer || !saw_eof)
12332     {
12333       if (!saw_eof)
12334         {
12335           bytes = fread (buffer + bytes_in_buffer, 1,
12336                          io_size - bytes_in_buffer,
12337                          file.get ());
12338           if (bytes == 0)
12339             {
12340               if (ferror (file.get ()))
12341                 error (_("Error reading %s."), local_file);
12342               else
12343                 {
12344                   /* EOF.  Unless there is something still in the
12345                      buffer from the last iteration, we are done.  */
12346                   saw_eof = 1;
12347                   if (bytes_in_buffer == 0)
12348                     break;
12349                 }
12350             }
12351         }
12352       else
12353         bytes = 0;
12354
12355       bytes += bytes_in_buffer;
12356       bytes_in_buffer = 0;
12357
12358       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12359                                       fd.get (), buffer, bytes,
12360                                       offset, &remote_errno);
12361
12362       if (retcode < 0)
12363         remote_hostio_error (remote_errno);
12364       else if (retcode == 0)
12365         error (_("Remote write of %d bytes returned 0!"), bytes);
12366       else if (retcode < bytes)
12367         {
12368           /* Short write.  Save the rest of the read data for the next
12369              write.  */
12370           bytes_in_buffer = bytes - retcode;
12371           memmove (buffer, buffer + retcode, bytes_in_buffer);
12372         }
12373
12374       offset += retcode;
12375     }
12376
12377   if (remote_hostio_close (find_target_at (process_stratum),
12378                            fd.release (), &remote_errno))
12379     remote_hostio_error (remote_errno);
12380
12381   if (from_tty)
12382     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12383   do_cleanups (back_to);
12384 }
12385
12386 void
12387 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12388 {
12389   struct cleanup *back_to;
12390   int remote_errno, bytes, io_size;
12391   gdb_byte *buffer;
12392   ULONGEST offset;
12393   struct remote_state *rs = get_remote_state ();
12394
12395   if (!rs->remote_desc)
12396     error (_("command can only be used with remote target"));
12397
12398   scoped_remote_fd fd
12399     (remote_hostio_open (find_target_at (process_stratum), NULL,
12400                          remote_file, FILEIO_O_RDONLY, 0, 0,
12401                          &remote_errno));
12402   if (fd.get () == -1)
12403     remote_hostio_error (remote_errno);
12404
12405   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12406   if (file == NULL)
12407     perror_with_name (local_file);
12408
12409   /* Send up to this many bytes at once.  They won't all fit in the
12410      remote packet limit, so we'll transfer slightly fewer.  */
12411   io_size = get_remote_packet_size ();
12412   buffer = (gdb_byte *) xmalloc (io_size);
12413   back_to = make_cleanup (xfree, buffer);
12414
12415   offset = 0;
12416   while (1)
12417     {
12418       bytes = remote_hostio_pread (find_target_at (process_stratum),
12419                                    fd.get (), buffer, io_size, offset,
12420                                    &remote_errno);
12421       if (bytes == 0)
12422         /* Success, but no bytes, means end-of-file.  */
12423         break;
12424       if (bytes == -1)
12425         remote_hostio_error (remote_errno);
12426
12427       offset += bytes;
12428
12429       bytes = fwrite (buffer, 1, bytes, file.get ());
12430       if (bytes == 0)
12431         perror_with_name (local_file);
12432     }
12433
12434   if (remote_hostio_close (find_target_at (process_stratum),
12435                            fd.release (), &remote_errno))
12436     remote_hostio_error (remote_errno);
12437
12438   if (from_tty)
12439     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12440   do_cleanups (back_to);
12441 }
12442
12443 void
12444 remote_file_delete (const char *remote_file, int from_tty)
12445 {
12446   int retcode, remote_errno;
12447   struct remote_state *rs = get_remote_state ();
12448
12449   if (!rs->remote_desc)
12450     error (_("command can only be used with remote target"));
12451
12452   retcode = remote_hostio_unlink (find_target_at (process_stratum),
12453                                   NULL, remote_file, &remote_errno);
12454   if (retcode == -1)
12455     remote_hostio_error (remote_errno);
12456
12457   if (from_tty)
12458     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12459 }
12460
12461 static void
12462 remote_put_command (const char *args, int from_tty)
12463 {
12464   if (args == NULL)
12465     error_no_arg (_("file to put"));
12466
12467   gdb_argv argv (args);
12468   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12469     error (_("Invalid parameters to remote put"));
12470
12471   remote_file_put (argv[0], argv[1], from_tty);
12472 }
12473
12474 static void
12475 remote_get_command (const char *args, int from_tty)
12476 {
12477   if (args == NULL)
12478     error_no_arg (_("file to get"));
12479
12480   gdb_argv argv (args);
12481   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12482     error (_("Invalid parameters to remote get"));
12483
12484   remote_file_get (argv[0], argv[1], from_tty);
12485 }
12486
12487 static void
12488 remote_delete_command (const char *args, int from_tty)
12489 {
12490   if (args == NULL)
12491     error_no_arg (_("file to delete"));
12492
12493   gdb_argv argv (args);
12494   if (argv[0] == NULL || argv[1] != NULL)
12495     error (_("Invalid parameters to remote delete"));
12496
12497   remote_file_delete (argv[0], from_tty);
12498 }
12499
12500 static void
12501 remote_command (const char *args, int from_tty)
12502 {
12503   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12504 }
12505
12506 bool
12507 remote_target::can_execute_reverse ()
12508 {
12509   if (packet_support (PACKET_bs) == PACKET_ENABLE
12510       || packet_support (PACKET_bc) == PACKET_ENABLE)
12511     return true;
12512   else
12513     return false;
12514 }
12515
12516 bool
12517 remote_target::supports_non_stop ()
12518 {
12519   return true;
12520 }
12521
12522 bool
12523 remote_target::supports_disable_randomization ()
12524 {
12525   /* Only supported in extended mode.  */
12526   return false;
12527 }
12528
12529 bool
12530 remote_target::supports_multi_process ()
12531 {
12532   struct remote_state *rs = get_remote_state ();
12533
12534   return remote_multi_process_p (rs);
12535 }
12536
12537 static int
12538 remote_supports_cond_tracepoints ()
12539 {
12540   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12541 }
12542
12543 bool
12544 remote_target::supports_evaluation_of_breakpoint_conditions ()
12545 {
12546   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12547 }
12548
12549 static int
12550 remote_supports_fast_tracepoints ()
12551 {
12552   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12553 }
12554
12555 static int
12556 remote_supports_static_tracepoints ()
12557 {
12558   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12559 }
12560
12561 static int
12562 remote_supports_install_in_trace ()
12563 {
12564   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12565 }
12566
12567 bool
12568 remote_target::supports_enable_disable_tracepoint ()
12569 {
12570   return (packet_support (PACKET_EnableDisableTracepoints_feature)
12571           == PACKET_ENABLE);
12572 }
12573
12574 bool
12575 remote_target::supports_string_tracing ()
12576 {
12577   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12578 }
12579
12580 bool
12581 remote_target::can_run_breakpoint_commands ()
12582 {
12583   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12584 }
12585
12586 void
12587 remote_target::trace_init ()
12588 {
12589   struct remote_state *rs = get_remote_state ();
12590
12591   putpkt ("QTinit");
12592   remote_get_noisy_reply ();
12593   if (strcmp (rs->buf, "OK") != 0)
12594     error (_("Target does not support this command."));
12595 }
12596
12597 /* Recursive routine to walk through command list including loops, and
12598    download packets for each command.  */
12599
12600 static void
12601 remote_download_command_source (int num, ULONGEST addr,
12602                                 struct command_line *cmds)
12603 {
12604   struct remote_state *rs = get_remote_state ();
12605   struct command_line *cmd;
12606
12607   for (cmd = cmds; cmd; cmd = cmd->next)
12608     {
12609       QUIT;     /* Allow user to bail out with ^C.  */
12610       strcpy (rs->buf, "QTDPsrc:");
12611       encode_source_string (num, addr, "cmd", cmd->line,
12612                             rs->buf + strlen (rs->buf),
12613                             rs->buf_size - strlen (rs->buf));
12614       putpkt (rs->buf);
12615       remote_get_noisy_reply ();
12616       if (strcmp (rs->buf, "OK"))
12617         warning (_("Target does not support source download."));
12618
12619       if (cmd->control_type == while_control
12620           || cmd->control_type == while_stepping_control)
12621         {
12622           remote_download_command_source (num, addr, cmd->body_list_0.get ());
12623
12624           QUIT; /* Allow user to bail out with ^C.  */
12625           strcpy (rs->buf, "QTDPsrc:");
12626           encode_source_string (num, addr, "cmd", "end",
12627                                 rs->buf + strlen (rs->buf),
12628                                 rs->buf_size - strlen (rs->buf));
12629           putpkt (rs->buf);
12630           remote_get_noisy_reply ();
12631           if (strcmp (rs->buf, "OK"))
12632             warning (_("Target does not support source download."));
12633         }
12634     }
12635 }
12636
12637 void
12638 remote_target::download_tracepoint (struct bp_location *loc)
12639 {
12640 #define BUF_SIZE 2048
12641
12642   CORE_ADDR tpaddr;
12643   char addrbuf[40];
12644   char buf[BUF_SIZE];
12645   std::vector<std::string> tdp_actions;
12646   std::vector<std::string> stepping_actions;
12647   char *pkt;
12648   struct breakpoint *b = loc->owner;
12649   struct tracepoint *t = (struct tracepoint *) b;
12650   struct remote_state *rs = get_remote_state ();
12651
12652   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12653
12654   tpaddr = loc->address;
12655   sprintf_vma (addrbuf, tpaddr);
12656   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12657              addrbuf, /* address */
12658              (b->enable_state == bp_enabled ? 'E' : 'D'),
12659              t->step_count, t->pass_count);
12660   /* Fast tracepoints are mostly handled by the target, but we can
12661      tell the target how big of an instruction block should be moved
12662      around.  */
12663   if (b->type == bp_fast_tracepoint)
12664     {
12665       /* Only test for support at download time; we may not know
12666          target capabilities at definition time.  */
12667       if (remote_supports_fast_tracepoints ())
12668         {
12669           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12670                                                 NULL))
12671             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12672                        gdb_insn_length (loc->gdbarch, tpaddr));
12673           else
12674             /* If it passed validation at definition but fails now,
12675                something is very wrong.  */
12676             internal_error (__FILE__, __LINE__,
12677                             _("Fast tracepoint not "
12678                               "valid during download"));
12679         }
12680       else
12681         /* Fast tracepoints are functionally identical to regular
12682            tracepoints, so don't take lack of support as a reason to
12683            give up on the trace run.  */
12684         warning (_("Target does not support fast tracepoints, "
12685                    "downloading %d as regular tracepoint"), b->number);
12686     }
12687   else if (b->type == bp_static_tracepoint)
12688     {
12689       /* Only test for support at download time; we may not know
12690          target capabilities at definition time.  */
12691       if (remote_supports_static_tracepoints ())
12692         {
12693           struct static_tracepoint_marker marker;
12694
12695           if (target_static_tracepoint_marker_at (tpaddr, &marker))
12696             strcat (buf, ":S");
12697           else
12698             error (_("Static tracepoint not valid during download"));
12699         }
12700       else
12701         /* Fast tracepoints are functionally identical to regular
12702            tracepoints, so don't take lack of support as a reason
12703            to give up on the trace run.  */
12704         error (_("Target does not support static tracepoints"));
12705     }
12706   /* If the tracepoint has a conditional, make it into an agent
12707      expression and append to the definition.  */
12708   if (loc->cond)
12709     {
12710       /* Only test support at download time, we may not know target
12711          capabilities at definition time.  */
12712       if (remote_supports_cond_tracepoints ())
12713         {
12714           agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12715           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12716                      aexpr->len);
12717           pkt = buf + strlen (buf);
12718           for (int ndx = 0; ndx < aexpr->len; ++ndx)
12719             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12720           *pkt = '\0';
12721         }
12722       else
12723         warning (_("Target does not support conditional tracepoints, "
12724                    "ignoring tp %d cond"), b->number);
12725     }
12726
12727   if (b->commands || *default_collect)
12728     strcat (buf, "-");
12729   putpkt (buf);
12730   remote_get_noisy_reply ();
12731   if (strcmp (rs->buf, "OK"))
12732     error (_("Target does not support tracepoints."));
12733
12734   /* do_single_steps (t); */
12735   for (auto action_it = tdp_actions.begin ();
12736        action_it != tdp_actions.end (); action_it++)
12737     {
12738       QUIT;     /* Allow user to bail out with ^C.  */
12739
12740       bool has_more = (action_it != tdp_actions.end ()
12741                        || !stepping_actions.empty ());
12742
12743       xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12744                  b->number, addrbuf, /* address */
12745                  action_it->c_str (),
12746                  has_more ? '-' : 0);
12747       putpkt (buf);
12748       remote_get_noisy_reply ();
12749       if (strcmp (rs->buf, "OK"))
12750         error (_("Error on target while setting tracepoints."));
12751     }
12752
12753     for (auto action_it = stepping_actions.begin ();
12754          action_it != stepping_actions.end (); action_it++)
12755       {
12756         QUIT;   /* Allow user to bail out with ^C.  */
12757
12758         bool is_first = action_it == stepping_actions.begin ();
12759         bool has_more = action_it != stepping_actions.end ();
12760
12761         xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12762                    b->number, addrbuf, /* address */
12763                    is_first ? "S" : "",
12764                    action_it->c_str (),
12765                    has_more ? "-" : "");
12766         putpkt (buf);
12767         remote_get_noisy_reply ();
12768         if (strcmp (rs->buf, "OK"))
12769           error (_("Error on target while setting tracepoints."));
12770       }
12771
12772   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12773     {
12774       if (b->location != NULL)
12775         {
12776           strcpy (buf, "QTDPsrc:");
12777           encode_source_string (b->number, loc->address, "at",
12778                                 event_location_to_string (b->location.get ()),
12779                                 buf + strlen (buf), 2048 - strlen (buf));
12780           putpkt (buf);
12781           remote_get_noisy_reply ();
12782           if (strcmp (rs->buf, "OK"))
12783             warning (_("Target does not support source download."));
12784         }
12785       if (b->cond_string)
12786         {
12787           strcpy (buf, "QTDPsrc:");
12788           encode_source_string (b->number, loc->address,
12789                                 "cond", b->cond_string, buf + strlen (buf),
12790                                 2048 - strlen (buf));
12791           putpkt (buf);
12792           remote_get_noisy_reply ();
12793           if (strcmp (rs->buf, "OK"))
12794             warning (_("Target does not support source download."));
12795         }
12796       remote_download_command_source (b->number, loc->address,
12797                                       breakpoint_commands (b));
12798     }
12799 }
12800
12801 bool
12802 remote_target::can_download_tracepoint ()
12803 {
12804   struct remote_state *rs = get_remote_state ();
12805   struct trace_status *ts;
12806   int status;
12807
12808   /* Don't try to install tracepoints until we've relocated our
12809      symbols, and fetched and merged the target's tracepoint list with
12810      ours.  */
12811   if (rs->starting_up)
12812     return false;
12813
12814   ts = current_trace_status ();
12815   status = get_trace_status (ts);
12816
12817   if (status == -1 || !ts->running_known || !ts->running)
12818     return false;
12819
12820   /* If we are in a tracing experiment, but remote stub doesn't support
12821      installing tracepoint in trace, we have to return.  */
12822   if (!remote_supports_install_in_trace ())
12823     return false;
12824
12825   return true;
12826 }
12827
12828
12829 void
12830 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12831 {
12832   struct remote_state *rs = get_remote_state ();
12833   char *p;
12834
12835   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12836              tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12837              tsv.builtin);
12838   p = rs->buf + strlen (rs->buf);
12839   if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12840     error (_("Trace state variable name too long for tsv definition packet"));
12841   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12842   *p++ = '\0';
12843   putpkt (rs->buf);
12844   remote_get_noisy_reply ();
12845   if (*rs->buf == '\0')
12846     error (_("Target does not support this command."));
12847   if (strcmp (rs->buf, "OK") != 0)
12848     error (_("Error on target while downloading trace state variable."));
12849 }
12850
12851 void
12852 remote_target::enable_tracepoint (struct bp_location *location)
12853 {
12854   struct remote_state *rs = get_remote_state ();
12855   char addr_buf[40];
12856
12857   sprintf_vma (addr_buf, location->address);
12858   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12859              location->owner->number, addr_buf);
12860   putpkt (rs->buf);
12861   remote_get_noisy_reply ();
12862   if (*rs->buf == '\0')
12863     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12864   if (strcmp (rs->buf, "OK") != 0)
12865     error (_("Error on target while enabling tracepoint."));
12866 }
12867
12868 void
12869 remote_target::disable_tracepoint (struct bp_location *location)
12870 {
12871   struct remote_state *rs = get_remote_state ();
12872   char addr_buf[40];
12873
12874   sprintf_vma (addr_buf, location->address);
12875   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12876              location->owner->number, addr_buf);
12877   putpkt (rs->buf);
12878   remote_get_noisy_reply ();
12879   if (*rs->buf == '\0')
12880     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12881   if (strcmp (rs->buf, "OK") != 0)
12882     error (_("Error on target while disabling tracepoint."));
12883 }
12884
12885 void
12886 remote_target::trace_set_readonly_regions ()
12887 {
12888   asection *s;
12889   bfd *abfd = NULL;
12890   bfd_size_type size;
12891   bfd_vma vma;
12892   int anysecs = 0;
12893   int offset = 0;
12894
12895   if (!exec_bfd)
12896     return;                     /* No information to give.  */
12897
12898   struct remote_state *rs = get_remote_state ();
12899
12900   strcpy (rs->buf, "QTro");
12901   offset = strlen (rs->buf);
12902   for (s = exec_bfd->sections; s; s = s->next)
12903     {
12904       char tmp1[40], tmp2[40];
12905       int sec_length;
12906
12907       if ((s->flags & SEC_LOAD) == 0 ||
12908       /*  (s->flags & SEC_CODE) == 0 || */
12909           (s->flags & SEC_READONLY) == 0)
12910         continue;
12911
12912       anysecs = 1;
12913       vma = bfd_get_section_vma (abfd, s);
12914       size = bfd_get_section_size (s);
12915       sprintf_vma (tmp1, vma);
12916       sprintf_vma (tmp2, vma + size);
12917       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12918       if (offset + sec_length + 1 > rs->buf_size)
12919         {
12920           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12921             warning (_("\
12922 Too many sections for read-only sections definition packet."));
12923           break;
12924         }
12925       xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
12926                  tmp1, tmp2);
12927       offset += sec_length;
12928     }
12929   if (anysecs)
12930     {
12931       putpkt (rs->buf);
12932       getpkt (&rs->buf, &rs->buf_size, 0);
12933     }
12934 }
12935
12936 void
12937 remote_target::trace_start ()
12938 {
12939   struct remote_state *rs = get_remote_state ();
12940
12941   putpkt ("QTStart");
12942   remote_get_noisy_reply ();
12943   if (*rs->buf == '\0')
12944     error (_("Target does not support this command."));
12945   if (strcmp (rs->buf, "OK") != 0)
12946     error (_("Bogus reply from target: %s"), rs->buf);
12947 }
12948
12949 int
12950 remote_target::get_trace_status (struct trace_status *ts)
12951 {
12952   /* Initialize it just to avoid a GCC false warning.  */
12953   char *p = NULL;
12954   /* FIXME we need to get register block size some other way.  */
12955   extern int trace_regblock_size;
12956   enum packet_result result;
12957   struct remote_state *rs = get_remote_state ();
12958
12959   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12960     return -1;
12961
12962   trace_regblock_size
12963     = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
12964
12965   putpkt ("qTStatus");
12966
12967   TRY
12968     {
12969       p = remote_get_noisy_reply ();
12970     }
12971   CATCH (ex, RETURN_MASK_ERROR)
12972     {
12973       if (ex.error != TARGET_CLOSE_ERROR)
12974         {
12975           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12976           return -1;
12977         }
12978       throw_exception (ex);
12979     }
12980   END_CATCH
12981
12982   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12983
12984   /* If the remote target doesn't do tracing, flag it.  */
12985   if (result == PACKET_UNKNOWN)
12986     return -1;
12987
12988   /* We're working with a live target.  */
12989   ts->filename = NULL;
12990
12991   if (*p++ != 'T')
12992     error (_("Bogus trace status reply from target: %s"), rs->buf);
12993
12994   /* Function 'parse_trace_status' sets default value of each field of
12995      'ts' at first, so we don't have to do it here.  */
12996   parse_trace_status (p, ts);
12997
12998   return ts->running;
12999 }
13000
13001 void
13002 remote_target::get_tracepoint_status (struct breakpoint *bp,
13003                                       struct uploaded_tp *utp)
13004 {
13005   struct remote_state *rs = get_remote_state ();
13006   char *reply;
13007   struct bp_location *loc;
13008   struct tracepoint *tp = (struct tracepoint *) bp;
13009   size_t size = get_remote_packet_size ();
13010
13011   if (tp)
13012     {
13013       tp->hit_count = 0;
13014       tp->traceframe_usage = 0;
13015       for (loc = tp->loc; loc; loc = loc->next)
13016         {
13017           /* If the tracepoint was never downloaded, don't go asking for
13018              any status.  */
13019           if (tp->number_on_target == 0)
13020             continue;
13021           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13022                      phex_nz (loc->address, 0));
13023           putpkt (rs->buf);
13024           reply = remote_get_noisy_reply ();
13025           if (reply && *reply)
13026             {
13027               if (*reply == 'V')
13028                 parse_tracepoint_status (reply + 1, bp, utp);
13029             }
13030         }
13031     }
13032   else if (utp)
13033     {
13034       utp->hit_count = 0;
13035       utp->traceframe_usage = 0;
13036       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13037                  phex_nz (utp->addr, 0));
13038       putpkt (rs->buf);
13039       reply = remote_get_noisy_reply ();
13040       if (reply && *reply)
13041         {
13042           if (*reply == 'V')
13043             parse_tracepoint_status (reply + 1, bp, utp);
13044         }
13045     }
13046 }
13047
13048 void
13049 remote_target::trace_stop ()
13050 {
13051   struct remote_state *rs = get_remote_state ();
13052
13053   putpkt ("QTStop");
13054   remote_get_noisy_reply ();
13055   if (*rs->buf == '\0')
13056     error (_("Target does not support this command."));
13057   if (strcmp (rs->buf, "OK") != 0)
13058     error (_("Bogus reply from target: %s"), rs->buf);
13059 }
13060
13061 int
13062 remote_target::trace_find (enum trace_find_type type, int num,
13063                            CORE_ADDR addr1, CORE_ADDR addr2,
13064                            int *tpp)
13065 {
13066   struct remote_state *rs = get_remote_state ();
13067   char *endbuf = rs->buf + get_remote_packet_size ();
13068   char *p, *reply;
13069   int target_frameno = -1, target_tracept = -1;
13070
13071   /* Lookups other than by absolute frame number depend on the current
13072      trace selected, so make sure it is correct on the remote end
13073      first.  */
13074   if (type != tfind_number)
13075     set_remote_traceframe ();
13076
13077   p = rs->buf;
13078   strcpy (p, "QTFrame:");
13079   p = strchr (p, '\0');
13080   switch (type)
13081     {
13082     case tfind_number:
13083       xsnprintf (p, endbuf - p, "%x", num);
13084       break;
13085     case tfind_pc:
13086       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13087       break;
13088     case tfind_tp:
13089       xsnprintf (p, endbuf - p, "tdp:%x", num);
13090       break;
13091     case tfind_range:
13092       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13093                  phex_nz (addr2, 0));
13094       break;
13095     case tfind_outside:
13096       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13097                  phex_nz (addr2, 0));
13098       break;
13099     default:
13100       error (_("Unknown trace find type %d"), type);
13101     }
13102
13103   putpkt (rs->buf);
13104   reply = remote_get_noisy_reply ();
13105   if (*reply == '\0')
13106     error (_("Target does not support this command."));
13107
13108   while (reply && *reply)
13109     switch (*reply)
13110       {
13111       case 'F':
13112         p = ++reply;
13113         target_frameno = (int) strtol (p, &reply, 16);
13114         if (reply == p)
13115           error (_("Unable to parse trace frame number"));
13116         /* Don't update our remote traceframe number cache on failure
13117            to select a remote traceframe.  */
13118         if (target_frameno == -1)
13119           return -1;
13120         break;
13121       case 'T':
13122         p = ++reply;
13123         target_tracept = (int) strtol (p, &reply, 16);
13124         if (reply == p)
13125           error (_("Unable to parse tracepoint number"));
13126         break;
13127       case 'O':         /* "OK"? */
13128         if (reply[1] == 'K' && reply[2] == '\0')
13129           reply += 2;
13130         else
13131           error (_("Bogus reply from target: %s"), reply);
13132         break;
13133       default:
13134         error (_("Bogus reply from target: %s"), reply);
13135       }
13136   if (tpp)
13137     *tpp = target_tracept;
13138
13139   rs->remote_traceframe_number = target_frameno;
13140   return target_frameno;
13141 }
13142
13143 bool
13144 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13145 {
13146   struct remote_state *rs = get_remote_state ();
13147   char *reply;
13148   ULONGEST uval;
13149
13150   set_remote_traceframe ();
13151
13152   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13153   putpkt (rs->buf);
13154   reply = remote_get_noisy_reply ();
13155   if (reply && *reply)
13156     {
13157       if (*reply == 'V')
13158         {
13159           unpack_varlen_hex (reply + 1, &uval);
13160           *val = (LONGEST) uval;
13161           return true;
13162         }
13163     }
13164   return false;
13165 }
13166
13167 int
13168 remote_target::save_trace_data (const char *filename)
13169 {
13170   struct remote_state *rs = get_remote_state ();
13171   char *p, *reply;
13172
13173   p = rs->buf;
13174   strcpy (p, "QTSave:");
13175   p += strlen (p);
13176   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13177     error (_("Remote file name too long for trace save packet"));
13178   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13179   *p++ = '\0';
13180   putpkt (rs->buf);
13181   reply = remote_get_noisy_reply ();
13182   if (*reply == '\0')
13183     error (_("Target does not support this command."));
13184   if (strcmp (reply, "OK") != 0)
13185     error (_("Bogus reply from target: %s"), reply);
13186   return 0;
13187 }
13188
13189 /* This is basically a memory transfer, but needs to be its own packet
13190    because we don't know how the target actually organizes its trace
13191    memory, plus we want to be able to ask for as much as possible, but
13192    not be unhappy if we don't get as much as we ask for.  */
13193
13194 LONGEST
13195 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13196 {
13197   struct remote_state *rs = get_remote_state ();
13198   char *reply;
13199   char *p;
13200   int rslt;
13201
13202   p = rs->buf;
13203   strcpy (p, "qTBuffer:");
13204   p += strlen (p);
13205   p += hexnumstr (p, offset);
13206   *p++ = ',';
13207   p += hexnumstr (p, len);
13208   *p++ = '\0';
13209
13210   putpkt (rs->buf);
13211   reply = remote_get_noisy_reply ();
13212   if (reply && *reply)
13213     {
13214       /* 'l' by itself means we're at the end of the buffer and
13215          there is nothing more to get.  */
13216       if (*reply == 'l')
13217         return 0;
13218
13219       /* Convert the reply into binary.  Limit the number of bytes to
13220          convert according to our passed-in buffer size, rather than
13221          what was returned in the packet; if the target is
13222          unexpectedly generous and gives us a bigger reply than we
13223          asked for, we don't want to crash.  */
13224       rslt = hex2bin (reply, buf, len);
13225       return rslt;
13226     }
13227
13228   /* Something went wrong, flag as an error.  */
13229   return -1;
13230 }
13231
13232 void
13233 remote_target::set_disconnected_tracing (int val)
13234 {
13235   struct remote_state *rs = get_remote_state ();
13236
13237   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13238     {
13239       char *reply;
13240
13241       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13242       putpkt (rs->buf);
13243       reply = remote_get_noisy_reply ();
13244       if (*reply == '\0')
13245         error (_("Target does not support this command."));
13246       if (strcmp (reply, "OK") != 0)
13247         error (_("Bogus reply from target: %s"), reply);
13248     }
13249   else if (val)
13250     warning (_("Target does not support disconnected tracing."));
13251 }
13252
13253 int
13254 remote_target::core_of_thread (ptid_t ptid)
13255 {
13256   struct thread_info *info = find_thread_ptid (ptid);
13257
13258   if (info != NULL && info->priv != NULL)
13259     return get_remote_thread_info (info)->core;
13260
13261   return -1;
13262 }
13263
13264 void
13265 remote_target::set_circular_trace_buffer (int val)
13266 {
13267   struct remote_state *rs = get_remote_state ();
13268   char *reply;
13269
13270   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13271   putpkt (rs->buf);
13272   reply = remote_get_noisy_reply ();
13273   if (*reply == '\0')
13274     error (_("Target does not support this command."));
13275   if (strcmp (reply, "OK") != 0)
13276     error (_("Bogus reply from target: %s"), reply);
13277 }
13278
13279 traceframe_info_up
13280 remote_target::traceframe_info ()
13281 {
13282   gdb::optional<gdb::char_vector> text
13283     = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
13284                             NULL);
13285   if (text)
13286     return parse_traceframe_info (text->data ());
13287
13288   return NULL;
13289 }
13290
13291 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
13292    instruction on which a fast tracepoint may be placed.  Returns -1
13293    if the packet is not supported, and 0 if the minimum instruction
13294    length is unknown.  */
13295
13296 int
13297 remote_target::get_min_fast_tracepoint_insn_len ()
13298 {
13299   struct remote_state *rs = get_remote_state ();
13300   char *reply;
13301
13302   /* If we're not debugging a process yet, the IPA can't be
13303      loaded.  */
13304   if (!target_has_execution)
13305     return 0;
13306
13307   /* Make sure the remote is pointing at the right process.  */
13308   set_general_process ();
13309
13310   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13311   putpkt (rs->buf);
13312   reply = remote_get_noisy_reply ();
13313   if (*reply == '\0')
13314     return -1;
13315   else
13316     {
13317       ULONGEST min_insn_len;
13318
13319       unpack_varlen_hex (reply, &min_insn_len);
13320
13321       return (int) min_insn_len;
13322     }
13323 }
13324
13325 void
13326 remote_target::set_trace_buffer_size (LONGEST val)
13327 {
13328   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13329     {
13330       struct remote_state *rs = get_remote_state ();
13331       char *buf = rs->buf;
13332       char *endbuf = rs->buf + get_remote_packet_size ();
13333       enum packet_result result;
13334
13335       gdb_assert (val >= 0 || val == -1);
13336       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13337       /* Send -1 as literal "-1" to avoid host size dependency.  */
13338       if (val < 0)
13339         {
13340           *buf++ = '-';
13341           buf += hexnumstr (buf, (ULONGEST) -val);
13342         }
13343       else
13344         buf += hexnumstr (buf, (ULONGEST) val);
13345
13346       putpkt (rs->buf);
13347       remote_get_noisy_reply ();
13348       result = packet_ok (rs->buf,
13349                   &remote_protocol_packets[PACKET_QTBuffer_size]);
13350
13351       if (result != PACKET_OK)
13352         warning (_("Bogus reply from target: %s"), rs->buf);
13353     }
13354 }
13355
13356 bool
13357 remote_target::set_trace_notes (const char *user, const char *notes,
13358                                 const char *stop_notes)
13359 {
13360   struct remote_state *rs = get_remote_state ();
13361   char *reply;
13362   char *buf = rs->buf;
13363   char *endbuf = rs->buf + get_remote_packet_size ();
13364   int nbytes;
13365
13366   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13367   if (user)
13368     {
13369       buf += xsnprintf (buf, endbuf - buf, "user:");
13370       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13371       buf += 2 * nbytes;
13372       *buf++ = ';';
13373     }
13374   if (notes)
13375     {
13376       buf += xsnprintf (buf, endbuf - buf, "notes:");
13377       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13378       buf += 2 * nbytes;
13379       *buf++ = ';';
13380     }
13381   if (stop_notes)
13382     {
13383       buf += xsnprintf (buf, endbuf - buf, "tstop:");
13384       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13385       buf += 2 * nbytes;
13386       *buf++ = ';';
13387     }
13388   /* Ensure the buffer is terminated.  */
13389   *buf = '\0';
13390
13391   putpkt (rs->buf);
13392   reply = remote_get_noisy_reply ();
13393   if (*reply == '\0')
13394     return false;
13395
13396   if (strcmp (reply, "OK") != 0)
13397     error (_("Bogus reply from target: %s"), reply);
13398
13399   return true;
13400 }
13401
13402 bool
13403 remote_target::use_agent (bool use)
13404 {
13405   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13406     {
13407       struct remote_state *rs = get_remote_state ();
13408
13409       /* If the stub supports QAgent.  */
13410       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13411       putpkt (rs->buf);
13412       getpkt (&rs->buf, &rs->buf_size, 0);
13413
13414       if (strcmp (rs->buf, "OK") == 0)
13415         {
13416           ::use_agent = use;
13417           return true;
13418         }
13419     }
13420
13421   return false;
13422 }
13423
13424 bool
13425 remote_target::can_use_agent ()
13426 {
13427   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13428 }
13429
13430 struct btrace_target_info
13431 {
13432   /* The ptid of the traced thread.  */
13433   ptid_t ptid;
13434
13435   /* The obtained branch trace configuration.  */
13436   struct btrace_config conf;
13437 };
13438
13439 /* Reset our idea of our target's btrace configuration.  */
13440
13441 static void
13442 remote_btrace_reset (void)
13443 {
13444   struct remote_state *rs = get_remote_state ();
13445
13446   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13447 }
13448
13449 /* Synchronize the configuration with the target.  */
13450
13451 static void
13452 btrace_sync_conf (const struct btrace_config *conf)
13453 {
13454   struct packet_config *packet;
13455   struct remote_state *rs;
13456   char *buf, *pos, *endbuf;
13457
13458   rs = get_remote_state ();
13459   buf = rs->buf;
13460   endbuf = buf + get_remote_packet_size ();
13461
13462   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13463   if (packet_config_support (packet) == PACKET_ENABLE
13464       && conf->bts.size != rs->btrace_config.bts.size)
13465     {
13466       pos = buf;
13467       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13468                         conf->bts.size);
13469
13470       putpkt (buf);
13471       getpkt (&buf, &rs->buf_size, 0);
13472
13473       if (packet_ok (buf, packet) == PACKET_ERROR)
13474         {
13475           if (buf[0] == 'E' && buf[1] == '.')
13476             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13477           else
13478             error (_("Failed to configure the BTS buffer size."));
13479         }
13480
13481       rs->btrace_config.bts.size = conf->bts.size;
13482     }
13483
13484   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13485   if (packet_config_support (packet) == PACKET_ENABLE
13486       && conf->pt.size != rs->btrace_config.pt.size)
13487     {
13488       pos = buf;
13489       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13490                         conf->pt.size);
13491
13492       putpkt (buf);
13493       getpkt (&buf, &rs->buf_size, 0);
13494
13495       if (packet_ok (buf, packet) == PACKET_ERROR)
13496         {
13497           if (buf[0] == 'E' && buf[1] == '.')
13498             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13499           else
13500             error (_("Failed to configure the trace buffer size."));
13501         }
13502
13503       rs->btrace_config.pt.size = conf->pt.size;
13504     }
13505 }
13506
13507 /* Read the current thread's btrace configuration from the target and
13508    store it into CONF.  */
13509
13510 static void
13511 btrace_read_config (struct btrace_config *conf)
13512 {
13513   gdb::optional<gdb::char_vector> xml
13514     = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
13515   if (xml)
13516     parse_xml_btrace_conf (conf, xml->data ());
13517 }
13518
13519 /* Maybe reopen target btrace.  */
13520
13521 static void
13522 remote_btrace_maybe_reopen (void)
13523 {
13524   struct remote_state *rs = get_remote_state ();
13525   struct thread_info *tp;
13526   int btrace_target_pushed = 0;
13527   int warned = 0;
13528
13529   scoped_restore_current_thread restore_thread;
13530
13531   ALL_NON_EXITED_THREADS (tp)
13532     {
13533       set_general_thread (tp->ptid);
13534
13535       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13536       btrace_read_config (&rs->btrace_config);
13537
13538       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13539         continue;
13540
13541 #if !defined (HAVE_LIBIPT)
13542       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13543         {
13544           if (!warned)
13545             {
13546               warned = 1;
13547               warning (_("Target is recording using Intel Processor Trace "
13548                          "but support was disabled at compile time."));
13549             }
13550
13551           continue;
13552         }
13553 #endif /* !defined (HAVE_LIBIPT) */
13554
13555       /* Push target, once, but before anything else happens.  This way our
13556          changes to the threads will be cleaned up by unpushing the target
13557          in case btrace_read_config () throws.  */
13558       if (!btrace_target_pushed)
13559         {
13560           btrace_target_pushed = 1;
13561           record_btrace_push_target ();
13562           printf_filtered (_("Target is recording using %s.\n"),
13563                            btrace_format_string (rs->btrace_config.format));
13564         }
13565
13566       tp->btrace.target = XCNEW (struct btrace_target_info);
13567       tp->btrace.target->ptid = tp->ptid;
13568       tp->btrace.target->conf = rs->btrace_config;
13569     }
13570 }
13571
13572 /* Enable branch tracing.  */
13573
13574 struct btrace_target_info *
13575 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13576 {
13577   struct btrace_target_info *tinfo = NULL;
13578   struct packet_config *packet = NULL;
13579   struct remote_state *rs = get_remote_state ();
13580   char *buf = rs->buf;
13581   char *endbuf = rs->buf + get_remote_packet_size ();
13582
13583   switch (conf->format)
13584     {
13585       case BTRACE_FORMAT_BTS:
13586         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13587         break;
13588
13589       case BTRACE_FORMAT_PT:
13590         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13591         break;
13592     }
13593
13594   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13595     error (_("Target does not support branch tracing."));
13596
13597   btrace_sync_conf (conf);
13598
13599   set_general_thread (ptid);
13600
13601   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13602   putpkt (rs->buf);
13603   getpkt (&rs->buf, &rs->buf_size, 0);
13604
13605   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13606     {
13607       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13608         error (_("Could not enable branch tracing for %s: %s"),
13609                target_pid_to_str (ptid), rs->buf + 2);
13610       else
13611         error (_("Could not enable branch tracing for %s."),
13612                target_pid_to_str (ptid));
13613     }
13614
13615   tinfo = XCNEW (struct btrace_target_info);
13616   tinfo->ptid = ptid;
13617
13618   /* If we fail to read the configuration, we lose some information, but the
13619      tracing itself is not impacted.  */
13620   TRY
13621     {
13622       btrace_read_config (&tinfo->conf);
13623     }
13624   CATCH (err, RETURN_MASK_ERROR)
13625     {
13626       if (err.message != NULL)
13627         warning ("%s", err.message);
13628     }
13629   END_CATCH
13630
13631   return tinfo;
13632 }
13633
13634 /* Disable branch tracing.  */
13635
13636 void
13637 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13638 {
13639   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13640   struct remote_state *rs = get_remote_state ();
13641   char *buf = rs->buf;
13642   char *endbuf = rs->buf + get_remote_packet_size ();
13643
13644   if (packet_config_support (packet) != PACKET_ENABLE)
13645     error (_("Target does not support branch tracing."));
13646
13647   set_general_thread (tinfo->ptid);
13648
13649   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13650   putpkt (rs->buf);
13651   getpkt (&rs->buf, &rs->buf_size, 0);
13652
13653   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13654     {
13655       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13656         error (_("Could not disable branch tracing for %s: %s"),
13657                target_pid_to_str (tinfo->ptid), rs->buf + 2);
13658       else
13659         error (_("Could not disable branch tracing for %s."),
13660                target_pid_to_str (tinfo->ptid));
13661     }
13662
13663   xfree (tinfo);
13664 }
13665
13666 /* Teardown branch tracing.  */
13667
13668 void
13669 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13670 {
13671   /* We must not talk to the target during teardown.  */
13672   xfree (tinfo);
13673 }
13674
13675 /* Read the branch trace.  */
13676
13677 enum btrace_error
13678 remote_target::read_btrace (struct btrace_data *btrace,
13679                             struct btrace_target_info *tinfo,
13680                             enum btrace_read_type type)
13681 {
13682   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13683   const char *annex;
13684
13685   if (packet_config_support (packet) != PACKET_ENABLE)
13686     error (_("Target does not support branch tracing."));
13687
13688 #if !defined(HAVE_LIBEXPAT)
13689   error (_("Cannot process branch tracing result. XML parsing not supported."));
13690 #endif
13691
13692   switch (type)
13693     {
13694     case BTRACE_READ_ALL:
13695       annex = "all";
13696       break;
13697     case BTRACE_READ_NEW:
13698       annex = "new";
13699       break;
13700     case BTRACE_READ_DELTA:
13701       annex = "delta";
13702       break;
13703     default:
13704       internal_error (__FILE__, __LINE__,
13705                       _("Bad branch tracing read type: %u."),
13706                       (unsigned int) type);
13707     }
13708
13709   gdb::optional<gdb::char_vector> xml
13710     = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
13711   if (!xml)
13712     return BTRACE_ERR_UNKNOWN;
13713
13714   parse_xml_btrace (btrace, xml->data ());
13715
13716   return BTRACE_ERR_NONE;
13717 }
13718
13719 const struct btrace_config *
13720 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13721 {
13722   return &tinfo->conf;
13723 }
13724
13725 bool
13726 remote_target::augmented_libraries_svr4_read ()
13727 {
13728   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13729           == PACKET_ENABLE);
13730 }
13731
13732 /* Implementation of to_load.  */
13733
13734 void
13735 remote_target::load (const char *name, int from_tty)
13736 {
13737   generic_load (name, from_tty);
13738 }
13739
13740 /* Accepts an integer PID; returns a string representing a file that
13741    can be opened on the remote side to get the symbols for the child
13742    process.  Returns NULL if the operation is not supported.  */
13743
13744 char *
13745 remote_target::pid_to_exec_file (int pid)
13746 {
13747   static gdb::optional<gdb::char_vector> filename;
13748   struct inferior *inf;
13749   char *annex = NULL;
13750
13751   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13752     return NULL;
13753
13754   inf = find_inferior_pid (pid);
13755   if (inf == NULL)
13756     internal_error (__FILE__, __LINE__,
13757                     _("not currently attached to process %d"), pid);
13758
13759   if (!inf->fake_pid_p)
13760     {
13761       const int annex_size = 9;
13762
13763       annex = (char *) alloca (annex_size);
13764       xsnprintf (annex, annex_size, "%x", pid);
13765     }
13766
13767   filename = target_read_stralloc (target_stack,
13768                                    TARGET_OBJECT_EXEC_FILE, annex);
13769
13770   return filename ? filename->data () : nullptr;
13771 }
13772
13773 /* Implement the to_can_do_single_step target_ops method.  */
13774
13775 int
13776 remote_target::can_do_single_step ()
13777 {
13778   /* We can only tell whether target supports single step or not by
13779      supported s and S vCont actions if the stub supports vContSupported
13780      feature.  If the stub doesn't support vContSupported feature,
13781      we have conservatively to think target doesn't supports single
13782      step.  */
13783   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13784     {
13785       struct remote_state *rs = get_remote_state ();
13786
13787       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13788         remote_vcont_probe (rs);
13789
13790       return rs->supports_vCont.s && rs->supports_vCont.S;
13791     }
13792   else
13793     return 0;
13794 }
13795
13796 /* Implementation of the to_execution_direction method for the remote
13797    target.  */
13798
13799 enum exec_direction_kind
13800 remote_target::execution_direction ()
13801 {
13802   struct remote_state *rs = get_remote_state ();
13803
13804   return rs->last_resume_exec_dir;
13805 }
13806
13807 /* Return pointer to the thread_info struct which corresponds to
13808    THREAD_HANDLE (having length HANDLE_LEN).  */
13809
13810 thread_info *
13811 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13812                                              int handle_len,
13813                                              inferior *inf)
13814 {
13815   struct thread_info *tp;
13816
13817   ALL_NON_EXITED_THREADS (tp)
13818     {
13819       remote_thread_info *priv = get_remote_thread_info (tp);
13820
13821       if (tp->inf == inf && priv != NULL)
13822         {
13823           if (handle_len != priv->thread_handle.size ())
13824             error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13825                    handle_len, priv->thread_handle.size ());
13826           if (memcmp (thread_handle, priv->thread_handle.data (),
13827                       handle_len) == 0)
13828             return tp;
13829         }
13830     }
13831
13832   return NULL;
13833 }
13834
13835 bool
13836 remote_target::can_async_p ()
13837 {
13838   struct remote_state *rs = get_remote_state ();
13839
13840   /* We don't go async if the user has explicitly prevented it with the
13841      "maint set target-async" command.  */
13842   if (!target_async_permitted)
13843     return false;
13844
13845   /* We're async whenever the serial device is.  */
13846   return serial_can_async_p (rs->remote_desc);
13847 }
13848
13849 bool
13850 remote_target::is_async_p ()
13851 {
13852   struct remote_state *rs = get_remote_state ();
13853
13854   if (!target_async_permitted)
13855     /* We only enable async when the user specifically asks for it.  */
13856     return false;
13857
13858   /* We're async whenever the serial device is.  */
13859   return serial_is_async_p (rs->remote_desc);
13860 }
13861
13862 /* Pass the SERIAL event on and up to the client.  One day this code
13863    will be able to delay notifying the client of an event until the
13864    point where an entire packet has been received.  */
13865
13866 static serial_event_ftype remote_async_serial_handler;
13867
13868 static void
13869 remote_async_serial_handler (struct serial *scb, void *context)
13870 {
13871   /* Don't propogate error information up to the client.  Instead let
13872      the client find out about the error by querying the target.  */
13873   inferior_event_handler (INF_REG_EVENT, NULL);
13874 }
13875
13876 static void
13877 remote_async_inferior_event_handler (gdb_client_data data)
13878 {
13879   inferior_event_handler (INF_REG_EVENT, NULL);
13880 }
13881
13882 void
13883 remote_target::async (int enable)
13884 {
13885   struct remote_state *rs = get_remote_state ();
13886
13887   if (enable)
13888     {
13889       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13890
13891       /* If there are pending events in the stop reply queue tell the
13892          event loop to process them.  */
13893       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13894         mark_async_event_handler (remote_async_inferior_event_token);
13895       /* For simplicity, below we clear the pending events token
13896          without remembering whether it is marked, so here we always
13897          mark it.  If there's actually no pending notification to
13898          process, this ends up being a no-op (other than a spurious
13899          event-loop wakeup).  */
13900       if (target_is_non_stop_p ())
13901         mark_async_event_handler (rs->notif_state->get_pending_events_token);
13902     }
13903   else
13904     {
13905       serial_async (rs->remote_desc, NULL, NULL);
13906       /* If the core is disabling async, it doesn't want to be
13907          disturbed with target events.  Clear all async event sources
13908          too.  */
13909       clear_async_event_handler (remote_async_inferior_event_token);
13910       if (target_is_non_stop_p ())
13911         clear_async_event_handler (rs->notif_state->get_pending_events_token);
13912     }
13913 }
13914
13915 /* Implementation of the to_thread_events method.  */
13916
13917 void
13918 remote_target::thread_events (int enable)
13919 {
13920   struct remote_state *rs = get_remote_state ();
13921   size_t size = get_remote_packet_size ();
13922
13923   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13924     return;
13925
13926   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13927   putpkt (rs->buf);
13928   getpkt (&rs->buf, &rs->buf_size, 0);
13929
13930   switch (packet_ok (rs->buf,
13931                      &remote_protocol_packets[PACKET_QThreadEvents]))
13932     {
13933     case PACKET_OK:
13934       if (strcmp (rs->buf, "OK") != 0)
13935         error (_("Remote refused setting thread events: %s"), rs->buf);
13936       break;
13937     case PACKET_ERROR:
13938       warning (_("Remote failure reply: %s"), rs->buf);
13939       break;
13940     case PACKET_UNKNOWN:
13941       break;
13942     }
13943 }
13944
13945 static void
13946 set_remote_cmd (const char *args, int from_tty)
13947 {
13948   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13949 }
13950
13951 static void
13952 show_remote_cmd (const char *args, int from_tty)
13953 {
13954   /* We can't just use cmd_show_list here, because we want to skip
13955      the redundant "show remote Z-packet" and the legacy aliases.  */
13956   struct cmd_list_element *list = remote_show_cmdlist;
13957   struct ui_out *uiout = current_uiout;
13958
13959   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13960   for (; list != NULL; list = list->next)
13961     if (strcmp (list->name, "Z-packet") == 0)
13962       continue;
13963     else if (list->type == not_set_cmd)
13964       /* Alias commands are exactly like the original, except they
13965          don't have the normal type.  */
13966       continue;
13967     else
13968       {
13969         ui_out_emit_tuple option_emitter (uiout, "option");
13970
13971         uiout->field_string ("name", list->name);
13972         uiout->text (":  ");
13973         if (list->type == show_cmd)
13974           do_show_command (NULL, from_tty, list);
13975         else
13976           cmd_func (list, NULL, from_tty);
13977       }
13978 }
13979
13980
13981 /* Function to be called whenever a new objfile (shlib) is detected.  */
13982 static void
13983 remote_new_objfile (struct objfile *objfile)
13984 {
13985   struct remote_state *rs = get_remote_state ();
13986
13987   if (rs->remote_desc != 0)             /* Have a remote connection.  */
13988     remote_check_symbols ();
13989 }
13990
13991 /* Pull all the tracepoints defined on the target and create local
13992    data structures representing them.  We don't want to create real
13993    tracepoints yet, we don't want to mess up the user's existing
13994    collection.  */
13995   
13996 int
13997 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
13998 {
13999   struct remote_state *rs = get_remote_state ();
14000   char *p;
14001
14002   /* Ask for a first packet of tracepoint definition.  */
14003   putpkt ("qTfP");
14004   getpkt (&rs->buf, &rs->buf_size, 0);
14005   p = rs->buf;
14006   while (*p && *p != 'l')
14007     {
14008       parse_tracepoint_definition (p, utpp);
14009       /* Ask for another packet of tracepoint definition.  */
14010       putpkt ("qTsP");
14011       getpkt (&rs->buf, &rs->buf_size, 0);
14012       p = rs->buf;
14013     }
14014   return 0;
14015 }
14016
14017 int
14018 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14019 {
14020   struct remote_state *rs = get_remote_state ();
14021   char *p;
14022
14023   /* Ask for a first packet of variable definition.  */
14024   putpkt ("qTfV");
14025   getpkt (&rs->buf, &rs->buf_size, 0);
14026   p = rs->buf;
14027   while (*p && *p != 'l')
14028     {
14029       parse_tsv_definition (p, utsvp);
14030       /* Ask for another packet of variable definition.  */
14031       putpkt ("qTsV");
14032       getpkt (&rs->buf, &rs->buf_size, 0);
14033       p = rs->buf;
14034     }
14035   return 0;
14036 }
14037
14038 /* The "set/show range-stepping" show hook.  */
14039
14040 static void
14041 show_range_stepping (struct ui_file *file, int from_tty,
14042                      struct cmd_list_element *c,
14043                      const char *value)
14044 {
14045   fprintf_filtered (file,
14046                     _("Debugger's willingness to use range stepping "
14047                       "is %s.\n"), value);
14048 }
14049
14050 /* The "set/show range-stepping" set hook.  */
14051
14052 static void
14053 set_range_stepping (const char *ignore_args, int from_tty,
14054                     struct cmd_list_element *c)
14055 {
14056   struct remote_state *rs = get_remote_state ();
14057
14058   /* Whene enabling, check whether range stepping is actually
14059      supported by the target, and warn if not.  */
14060   if (use_range_stepping)
14061     {
14062       if (rs->remote_desc != NULL)
14063         {
14064           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14065             remote_vcont_probe (rs);
14066
14067           if (packet_support (PACKET_vCont) == PACKET_ENABLE
14068               && rs->supports_vCont.r)
14069             return;
14070         }
14071
14072       warning (_("Range stepping is not supported by the current target"));
14073     }
14074 }
14075
14076 void
14077 _initialize_remote (void)
14078 {
14079   struct cmd_list_element *cmd;
14080   const char *cmd_name;
14081
14082   /* architecture specific data */
14083   remote_g_packet_data_handle =
14084     gdbarch_data_register_pre_init (remote_g_packet_data_init);
14085
14086   remote_pspace_data
14087     = register_program_space_data_with_cleanup (NULL,
14088                                                 remote_pspace_data_cleanup);
14089
14090   /* Initialize the per-target state.  At the moment there is only one
14091      of these, not one per target.  Only one target is active at a
14092      time.  */
14093   remote_state = new struct remote_state ();
14094
14095   add_target (remote_target_info, remote_target::open);
14096   add_target (extended_remote_target_info, extended_remote_target::open);
14097
14098   /* Hook into new objfile notification.  */
14099   gdb::observers::new_objfile.attach (remote_new_objfile);
14100
14101 #if 0
14102   init_remote_threadtests ();
14103 #endif
14104
14105   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14106   /* set/show remote ...  */
14107
14108   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14109 Remote protocol specific variables\n\
14110 Configure various remote-protocol specific variables such as\n\
14111 the packets being used"),
14112                   &remote_set_cmdlist, "set remote ",
14113                   0 /* allow-unknown */, &setlist);
14114   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14115 Remote protocol specific variables\n\
14116 Configure various remote-protocol specific variables such as\n\
14117 the packets being used"),
14118                   &remote_show_cmdlist, "show remote ",
14119                   0 /* allow-unknown */, &showlist);
14120
14121   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14122 Compare section data on target to the exec file.\n\
14123 Argument is a single section name (default: all loaded sections).\n\
14124 To compare only read-only loaded sections, specify the -r option."),
14125            &cmdlist);
14126
14127   add_cmd ("packet", class_maintenance, packet_command, _("\
14128 Send an arbitrary packet to a remote target.\n\
14129    maintenance packet TEXT\n\
14130 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14131 this command sends the string TEXT to the inferior, and displays the\n\
14132 response packet.  GDB supplies the initial `$' character, and the\n\
14133 terminating `#' character and checksum."),
14134            &maintenancelist);
14135
14136   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14137 Set whether to send break if interrupted."), _("\
14138 Show whether to send break if interrupted."), _("\
14139 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14140                            set_remotebreak, show_remotebreak,
14141                            &setlist, &showlist);
14142   cmd_name = "remotebreak";
14143   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14144   deprecate_cmd (cmd, "set remote interrupt-sequence");
14145   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14146   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14147   deprecate_cmd (cmd, "show remote interrupt-sequence");
14148
14149   add_setshow_enum_cmd ("interrupt-sequence", class_support,
14150                         interrupt_sequence_modes, &interrupt_sequence_mode,
14151                         _("\
14152 Set interrupt sequence to remote target."), _("\
14153 Show interrupt sequence to remote target."), _("\
14154 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14155                         NULL, show_interrupt_sequence,
14156                         &remote_set_cmdlist,
14157                         &remote_show_cmdlist);
14158
14159   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14160                            &interrupt_on_connect, _("\
14161 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
14162 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
14163 If set, interrupt sequence is sent to remote target."),
14164                            NULL, NULL,
14165                            &remote_set_cmdlist, &remote_show_cmdlist);
14166
14167   /* Install commands for configuring memory read/write packets.  */
14168
14169   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14170 Set the maximum number of bytes per memory write packet (deprecated)."),
14171            &setlist);
14172   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14173 Show the maximum number of bytes per memory write packet (deprecated)."),
14174            &showlist);
14175   add_cmd ("memory-write-packet-size", no_class,
14176            set_memory_write_packet_size, _("\
14177 Set the maximum number of bytes per memory-write packet.\n\
14178 Specify the number of bytes in a packet or 0 (zero) for the\n\
14179 default packet size.  The actual limit is further reduced\n\
14180 dependent on the target.  Specify ``fixed'' to disable the\n\
14181 further restriction and ``limit'' to enable that restriction."),
14182            &remote_set_cmdlist);
14183   add_cmd ("memory-read-packet-size", no_class,
14184            set_memory_read_packet_size, _("\
14185 Set the maximum number of bytes per memory-read packet.\n\
14186 Specify the number of bytes in a packet or 0 (zero) for the\n\
14187 default packet size.  The actual limit is further reduced\n\
14188 dependent on the target.  Specify ``fixed'' to disable the\n\
14189 further restriction and ``limit'' to enable that restriction."),
14190            &remote_set_cmdlist);
14191   add_cmd ("memory-write-packet-size", no_class,
14192            show_memory_write_packet_size,
14193            _("Show the maximum number of bytes per memory-write packet."),
14194            &remote_show_cmdlist);
14195   add_cmd ("memory-read-packet-size", no_class,
14196            show_memory_read_packet_size,
14197            _("Show the maximum number of bytes per memory-read packet."),
14198            &remote_show_cmdlist);
14199
14200   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14201                             &remote_hw_watchpoint_limit, _("\
14202 Set the maximum number of target hardware watchpoints."), _("\
14203 Show the maximum number of target hardware watchpoints."), _("\
14204 Specify a negative limit for unlimited."),
14205                             NULL, NULL, /* FIXME: i18n: The maximum
14206                                            number of target hardware
14207                                            watchpoints is %s.  */
14208                             &remote_set_cmdlist, &remote_show_cmdlist);
14209   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14210                             &remote_hw_watchpoint_length_limit, _("\
14211 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14212 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14213 Specify a negative limit for unlimited."),
14214                             NULL, NULL, /* FIXME: i18n: The maximum
14215                                            length (in bytes) of a target
14216                                            hardware watchpoint is %s.  */
14217                             &remote_set_cmdlist, &remote_show_cmdlist);
14218   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14219                             &remote_hw_breakpoint_limit, _("\
14220 Set the maximum number of target hardware breakpoints."), _("\
14221 Show the maximum number of target hardware breakpoints."), _("\
14222 Specify a negative limit for unlimited."),
14223                             NULL, NULL, /* FIXME: i18n: The maximum
14224                                            number of target hardware
14225                                            breakpoints is %s.  */
14226                             &remote_set_cmdlist, &remote_show_cmdlist);
14227
14228   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14229                              &remote_address_size, _("\
14230 Set the maximum size of the address (in bits) in a memory packet."), _("\
14231 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14232                              NULL,
14233                              NULL, /* FIXME: i18n: */
14234                              &setlist, &showlist);
14235
14236   init_all_packet_configs ();
14237
14238   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14239                          "X", "binary-download", 1);
14240
14241   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14242                          "vCont", "verbose-resume", 0);
14243
14244   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14245                          "QPassSignals", "pass-signals", 0);
14246
14247   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14248                          "QCatchSyscalls", "catch-syscalls", 0);
14249
14250   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14251                          "QProgramSignals", "program-signals", 0);
14252
14253   add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14254                          "QSetWorkingDir", "set-working-dir", 0);
14255
14256   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14257                          "QStartupWithShell", "startup-with-shell", 0);
14258
14259   add_packet_config_cmd (&remote_protocol_packets
14260                          [PACKET_QEnvironmentHexEncoded],
14261                          "QEnvironmentHexEncoded", "environment-hex-encoded",
14262                          0);
14263
14264   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14265                          "QEnvironmentReset", "environment-reset",
14266                          0);
14267
14268   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14269                          "QEnvironmentUnset", "environment-unset",
14270                          0);
14271
14272   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14273                          "qSymbol", "symbol-lookup", 0);
14274
14275   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14276                          "P", "set-register", 1);
14277
14278   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14279                          "p", "fetch-register", 1);
14280
14281   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14282                          "Z0", "software-breakpoint", 0);
14283
14284   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14285                          "Z1", "hardware-breakpoint", 0);
14286
14287   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14288                          "Z2", "write-watchpoint", 0);
14289
14290   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14291                          "Z3", "read-watchpoint", 0);
14292
14293   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14294                          "Z4", "access-watchpoint", 0);
14295
14296   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14297                          "qXfer:auxv:read", "read-aux-vector", 0);
14298
14299   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14300                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
14301
14302   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14303                          "qXfer:features:read", "target-features", 0);
14304
14305   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14306                          "qXfer:libraries:read", "library-info", 0);
14307
14308   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14309                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14310
14311   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14312                          "qXfer:memory-map:read", "memory-map", 0);
14313
14314   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14315                          "qXfer:spu:read", "read-spu-object", 0);
14316
14317   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14318                          "qXfer:spu:write", "write-spu-object", 0);
14319
14320   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14321                         "qXfer:osdata:read", "osdata", 0);
14322
14323   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14324                          "qXfer:threads:read", "threads", 0);
14325
14326   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14327                          "qXfer:siginfo:read", "read-siginfo-object", 0);
14328
14329   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14330                          "qXfer:siginfo:write", "write-siginfo-object", 0);
14331
14332   add_packet_config_cmd
14333     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14334      "qXfer:traceframe-info:read", "traceframe-info", 0);
14335
14336   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14337                          "qXfer:uib:read", "unwind-info-block", 0);
14338
14339   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14340                          "qGetTLSAddr", "get-thread-local-storage-address",
14341                          0);
14342
14343   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14344                          "qGetTIBAddr", "get-thread-information-block-address",
14345                          0);
14346
14347   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14348                          "bc", "reverse-continue", 0);
14349
14350   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14351                          "bs", "reverse-step", 0);
14352
14353   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14354                          "qSupported", "supported-packets", 0);
14355
14356   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14357                          "qSearch:memory", "search-memory", 0);
14358
14359   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14360                          "qTStatus", "trace-status", 0);
14361
14362   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14363                          "vFile:setfs", "hostio-setfs", 0);
14364
14365   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14366                          "vFile:open", "hostio-open", 0);
14367
14368   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14369                          "vFile:pread", "hostio-pread", 0);
14370
14371   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14372                          "vFile:pwrite", "hostio-pwrite", 0);
14373
14374   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14375                          "vFile:close", "hostio-close", 0);
14376
14377   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14378                          "vFile:unlink", "hostio-unlink", 0);
14379
14380   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14381                          "vFile:readlink", "hostio-readlink", 0);
14382
14383   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14384                          "vFile:fstat", "hostio-fstat", 0);
14385
14386   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14387                          "vAttach", "attach", 0);
14388
14389   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14390                          "vRun", "run", 0);
14391
14392   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14393                          "QStartNoAckMode", "noack", 0);
14394
14395   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14396                          "vKill", "kill", 0);
14397
14398   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14399                          "qAttached", "query-attached", 0);
14400
14401   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14402                          "ConditionalTracepoints",
14403                          "conditional-tracepoints", 0);
14404
14405   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14406                          "ConditionalBreakpoints",
14407                          "conditional-breakpoints", 0);
14408
14409   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14410                          "BreakpointCommands",
14411                          "breakpoint-commands", 0);
14412
14413   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14414                          "FastTracepoints", "fast-tracepoints", 0);
14415
14416   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14417                          "TracepointSource", "TracepointSource", 0);
14418
14419   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14420                          "QAllow", "allow", 0);
14421
14422   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14423                          "StaticTracepoints", "static-tracepoints", 0);
14424
14425   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14426                          "InstallInTrace", "install-in-trace", 0);
14427
14428   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14429                          "qXfer:statictrace:read", "read-sdata-object", 0);
14430
14431   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14432                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14433
14434   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14435                          "QDisableRandomization", "disable-randomization", 0);
14436
14437   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14438                          "QAgent", "agent", 0);
14439
14440   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14441                          "QTBuffer:size", "trace-buffer-size", 0);
14442
14443   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14444        "Qbtrace:off", "disable-btrace", 0);
14445
14446   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14447        "Qbtrace:bts", "enable-btrace-bts", 0);
14448
14449   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14450        "Qbtrace:pt", "enable-btrace-pt", 0);
14451
14452   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14453        "qXfer:btrace", "read-btrace", 0);
14454
14455   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14456        "qXfer:btrace-conf", "read-btrace-conf", 0);
14457
14458   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14459        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14460
14461   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14462        "multiprocess-feature", "multiprocess-feature", 0);
14463
14464   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14465                          "swbreak-feature", "swbreak-feature", 0);
14466
14467   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14468                          "hwbreak-feature", "hwbreak-feature", 0);
14469
14470   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14471                          "fork-event-feature", "fork-event-feature", 0);
14472
14473   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14474                          "vfork-event-feature", "vfork-event-feature", 0);
14475
14476   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14477        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14478
14479   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14480                          "vContSupported", "verbose-resume-supported", 0);
14481
14482   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14483                          "exec-event-feature", "exec-event-feature", 0);
14484
14485   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14486                          "vCtrlC", "ctrl-c", 0);
14487
14488   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14489                          "QThreadEvents", "thread-events", 0);
14490
14491   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14492                          "N stop reply", "no-resumed-stop-reply", 0);
14493
14494   /* Assert that we've registered "set remote foo-packet" commands
14495      for all packet configs.  */
14496   {
14497     int i;
14498
14499     for (i = 0; i < PACKET_MAX; i++)
14500       {
14501         /* Ideally all configs would have a command associated.  Some
14502            still don't though.  */
14503         int excepted;
14504
14505         switch (i)
14506           {
14507           case PACKET_QNonStop:
14508           case PACKET_EnableDisableTracepoints_feature:
14509           case PACKET_tracenz_feature:
14510           case PACKET_DisconnectedTracing_feature:
14511           case PACKET_augmented_libraries_svr4_read_feature:
14512           case PACKET_qCRC:
14513             /* Additions to this list need to be well justified:
14514                pre-existing packets are OK; new packets are not.  */
14515             excepted = 1;
14516             break;
14517           default:
14518             excepted = 0;
14519             break;
14520           }
14521
14522         /* This catches both forgetting to add a config command, and
14523            forgetting to remove a packet from the exception list.  */
14524         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14525       }
14526   }
14527
14528   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
14529      Z sub-packet has its own set and show commands, but users may
14530      have sets to this variable in their .gdbinit files (or in their
14531      documentation).  */
14532   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14533                                 &remote_Z_packet_detect, _("\
14534 Set use of remote protocol `Z' packets"), _("\
14535 Show use of remote protocol `Z' packets "), _("\
14536 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14537 packets."),
14538                                 set_remote_protocol_Z_packet_cmd,
14539                                 show_remote_protocol_Z_packet_cmd,
14540                                 /* FIXME: i18n: Use of remote protocol
14541                                    `Z' packets is %s.  */
14542                                 &remote_set_cmdlist, &remote_show_cmdlist);
14543
14544   add_prefix_cmd ("remote", class_files, remote_command, _("\
14545 Manipulate files on the remote system\n\
14546 Transfer files to and from the remote target system."),
14547                   &remote_cmdlist, "remote ",
14548                   0 /* allow-unknown */, &cmdlist);
14549
14550   add_cmd ("put", class_files, remote_put_command,
14551            _("Copy a local file to the remote system."),
14552            &remote_cmdlist);
14553
14554   add_cmd ("get", class_files, remote_get_command,
14555            _("Copy a remote file to the local system."),
14556            &remote_cmdlist);
14557
14558   add_cmd ("delete", class_files, remote_delete_command,
14559            _("Delete a remote file."),
14560            &remote_cmdlist);
14561
14562   add_setshow_string_noescape_cmd ("exec-file", class_files,
14563                                    &remote_exec_file_var, _("\
14564 Set the remote pathname for \"run\""), _("\
14565 Show the remote pathname for \"run\""), NULL,
14566                                    set_remote_exec_file,
14567                                    show_remote_exec_file,
14568                                    &remote_set_cmdlist,
14569                                    &remote_show_cmdlist);
14570
14571   add_setshow_boolean_cmd ("range-stepping", class_run,
14572                            &use_range_stepping, _("\
14573 Enable or disable range stepping."), _("\
14574 Show whether target-assisted range stepping is enabled."), _("\
14575 If on, and the target supports it, when stepping a source line, GDB\n\
14576 tells the target to step the corresponding range of addresses itself instead\n\
14577 of issuing multiple single-steps.  This speeds up source level\n\
14578 stepping.  If off, GDB always issues single-steps, even if range\n\
14579 stepping is supported by the target.  The default is on."),
14580                            set_range_stepping,
14581                            show_range_stepping,
14582                            &setlist,
14583                            &showlist);
14584
14585   /* Eventually initialize fileio.  See fileio.c */
14586   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14587
14588   /* Take advantage of the fact that the TID field is not used, to tag
14589      special ptids with it set to != 0.  */
14590   magic_null_ptid = ptid_build (42000, -1, 1);
14591   not_sent_ptid = ptid_build (42000, -2, 1);
14592   any_thread_ptid = ptid_build (42000, 0, 1);
14593 }