remote: Make readahead_cache a C++ class
[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
79 /* The remote target.  */
80
81 static const char remote_doc[] = N_("\
82 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
83 Specify the serial device it is connected to\n\
84 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
85
86 static const target_info remote_target_info = {
87   "remote",
88   N_("Remote serial target in gdb-specific protocol"),
89   remote_doc
90 };
91
92 class remote_target : public target_ops
93 {
94 public:
95   remote_target ()
96   {
97     to_stratum = process_stratum;
98   }
99
100   const target_info &info () const override
101   { return remote_target_info; }
102
103   thread_control_capabilities get_thread_control_capabilities () override
104   { return tc_schedlock; }
105
106   /* Open a remote connection.  */
107   static void open (const char *, int);
108
109   void close () override;
110
111   void detach (inferior *, int) override;
112   void disconnect (const char *, int) override;
113
114   void commit_resume () override;
115   void resume (ptid_t, int, enum gdb_signal) override;
116   ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
117
118   void fetch_registers (struct regcache *, int) override;
119   void store_registers (struct regcache *, int) override;
120   void prepare_to_store (struct regcache *) override;
121
122   void files_info () override;
123
124   int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
125
126   int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
127                          enum remove_bp_reason) override;
128
129
130   bool stopped_by_sw_breakpoint () override;
131   bool supports_stopped_by_sw_breakpoint () override;
132
133   bool stopped_by_hw_breakpoint () override;
134
135   bool supports_stopped_by_hw_breakpoint () override;
136
137   bool stopped_by_watchpoint () override;
138
139   bool stopped_data_address (CORE_ADDR *) override;
140
141   bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
142
143   int can_use_hw_breakpoint (enum bptype, int, int) override;
144
145   int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
146
147   int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
148
149   int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
150
151   int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
152                          struct expression *) override;
153
154   int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
155                          struct expression *) override;
156
157   void kill () override;
158
159   void load (const char *, int) override;
160
161   void mourn_inferior () override;
162
163   void pass_signals (int, unsigned char *) override;
164
165   int set_syscall_catchpoint (int, bool, int,
166                               gdb::array_view<const int>) override;
167
168   void program_signals (int, unsigned char *) override;
169
170   bool thread_alive (ptid_t ptid) override;
171
172   const char *thread_name (struct thread_info *) override;
173
174   void update_thread_list () override;
175
176   const char *pid_to_str (ptid_t) override;
177
178   const char *extra_thread_info (struct thread_info *) override;
179
180   ptid_t get_ada_task_ptid (long lwp, long thread) override;
181
182   thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
183                                              int handle_len,
184                                              inferior *inf) override;
185
186   void stop (ptid_t) override;
187
188   void interrupt () override;
189
190   void pass_ctrlc () override;
191
192   enum target_xfer_status xfer_partial (enum target_object object,
193                                         const char *annex,
194                                         gdb_byte *readbuf,
195                                         const gdb_byte *writebuf,
196                                         ULONGEST offset, ULONGEST len,
197                                         ULONGEST *xfered_len) override;
198
199   ULONGEST get_memory_xfer_limit () override;
200
201   void rcmd (const char *command, struct ui_file *output) override;
202
203   char *pid_to_exec_file (int pid) override;
204
205   void log_command (const char *cmd) override
206   {
207     serial_log_command (this, cmd);
208   }
209
210   CORE_ADDR get_thread_local_address (ptid_t ptid,
211                                       CORE_ADDR load_module_addr,
212                                       CORE_ADDR offset) override;
213
214   bool has_all_memory ()  override { return default_child_has_all_memory (); }
215   bool has_memory ()  override { return default_child_has_memory (); }
216   bool has_stack ()  override { return default_child_has_stack (); }
217   bool has_registers ()  override { return default_child_has_registers (); }
218   bool has_execution (ptid_t ptid)  override { return default_child_has_execution (ptid); }
219
220   bool can_execute_reverse () override;
221
222   std::vector<mem_region> memory_map () override;
223
224   void flash_erase (ULONGEST address, LONGEST length) override;
225
226   void flash_done () override;
227
228   const struct target_desc *read_description () override;
229
230   int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
231                      const gdb_byte *pattern, ULONGEST pattern_len,
232                      CORE_ADDR *found_addrp) override;
233
234   bool can_async_p () override;
235
236   bool is_async_p () override;
237
238   void async (int) override;
239
240   void thread_events (int) override;
241
242   int can_do_single_step () override;
243
244   void terminal_inferior () override;
245
246   void terminal_ours () override;
247
248   bool supports_non_stop () override;
249
250   bool supports_multi_process () override;
251
252   bool supports_disable_randomization () override;
253
254   bool filesystem_is_local () override;
255
256
257   int fileio_open (struct inferior *inf, const char *filename,
258                    int flags, int mode, int warn_if_slow,
259                    int *target_errno) override;
260
261   int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
262                      ULONGEST offset, int *target_errno) override;
263
264   int fileio_pread (int fd, gdb_byte *read_buf, int len,
265                     ULONGEST offset, int *target_errno) override;
266
267   int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
268
269   int fileio_close (int fd, int *target_errno) override;
270
271   int fileio_unlink (struct inferior *inf,
272                      const char *filename,
273                      int *target_errno) override;
274
275   gdb::optional<std::string>
276     fileio_readlink (struct inferior *inf,
277                      const char *filename,
278                      int *target_errno) override;
279
280   bool supports_enable_disable_tracepoint () override;
281
282   bool supports_string_tracing () override;
283
284   bool supports_evaluation_of_breakpoint_conditions () override;
285
286   bool can_run_breakpoint_commands () override;
287
288   void trace_init () override;
289
290   void download_tracepoint (struct bp_location *location) override;
291
292   bool can_download_tracepoint () override;
293
294   void download_trace_state_variable (const trace_state_variable &tsv) override;
295
296   void enable_tracepoint (struct bp_location *location) override;
297
298   void disable_tracepoint (struct bp_location *location) override;
299
300   void trace_set_readonly_regions () override;
301
302   void trace_start () override;
303
304   int get_trace_status (struct trace_status *ts) override;
305
306   void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
307     override;
308
309   void trace_stop () override;
310
311   int trace_find (enum trace_find_type type, int num,
312                   CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
313
314   bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
315
316   int save_trace_data (const char *filename) override;
317
318   int upload_tracepoints (struct uploaded_tp **utpp) override;
319
320   int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
321
322   LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
323
324   int get_min_fast_tracepoint_insn_len () override;
325
326   void set_disconnected_tracing (int val) override;
327
328   void set_circular_trace_buffer (int val) override;
329
330   void set_trace_buffer_size (LONGEST val) override;
331
332   bool set_trace_notes (const char *user, const char *notes,
333                         const char *stopnotes) override;
334
335   int core_of_thread (ptid_t ptid) override;
336
337   int verify_memory (const gdb_byte *data,
338                      CORE_ADDR memaddr, ULONGEST size) override;
339
340
341   bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
342
343   void set_permissions () override;
344
345   bool static_tracepoint_marker_at (CORE_ADDR,
346                                     struct static_tracepoint_marker *marker)
347     override;
348
349   std::vector<static_tracepoint_marker>
350     static_tracepoint_markers_by_strid (const char *id) override;
351
352   traceframe_info_up traceframe_info () override;
353
354   bool use_agent (bool use) override;
355   bool can_use_agent () override;
356
357   struct btrace_target_info *enable_btrace (ptid_t ptid,
358                                             const struct btrace_config *conf) override;
359
360   void disable_btrace (struct btrace_target_info *tinfo) override;
361
362   void teardown_btrace (struct btrace_target_info *tinfo) override;
363
364   enum btrace_error read_btrace (struct btrace_data *data,
365                                  struct btrace_target_info *btinfo,
366                                  enum btrace_read_type type) override;
367
368   const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
369   bool augmented_libraries_svr4_read () override;
370   int follow_fork (int, int) override;
371   void follow_exec (struct inferior *, char *) override;
372   int insert_fork_catchpoint (int) override;
373   int remove_fork_catchpoint (int) override;
374   int insert_vfork_catchpoint (int) override;
375   int remove_vfork_catchpoint (int) override;
376   int insert_exec_catchpoint (int) override;
377   int remove_exec_catchpoint (int) override;
378   enum exec_direction_kind execution_direction () override;
379
380 protected:
381   static void open_1 (const char *name, int from_tty, int extended_p);
382   void start_remote (int from_tty, int extended_p);
383 };
384
385 static const target_info extended_remote_target_info = {
386   "extended-remote",
387   N_("Extended remote serial target in gdb-specific protocol"),
388   remote_doc
389 };
390
391 /* Set up the extended remote target by extending the standard remote
392    target and adding to it.  */
393
394 class extended_remote_target final : public remote_target
395 {
396 public:
397   const target_info &info () const override
398   { return extended_remote_target_info; }
399
400   /* Open an extended-remote connection.  */
401   static void open (const char *, int);
402
403   bool can_create_inferior () override { return true; }
404   void create_inferior (const char *, const std::string &,
405                         char **, int) override;
406
407   void detach (inferior *, int) override;
408
409   bool can_attach () override { return true; }
410   void attach (const char *, int) override;
411
412   void post_attach (int) override;
413   bool supports_disable_randomization () override;
414 };
415
416 /* Per-program-space data key.  */
417 static const struct program_space_data *remote_pspace_data;
418
419 /* The variable registered as the control variable used by the
420    remote exec-file commands.  While the remote exec-file setting is
421    per-program-space, the set/show machinery uses this as the 
422    location of the remote exec-file value.  */
423 static char *remote_exec_file_var;
424
425 /* The size to align memory write packets, when practical.  The protocol
426    does not guarantee any alignment, and gdb will generate short
427    writes and unaligned writes, but even as a best-effort attempt this
428    can improve bulk transfers.  For instance, if a write is misaligned
429    relative to the target's data bus, the stub may need to make an extra
430    round trip fetching data from the target.  This doesn't make a
431    huge difference, but it's easy to do, so we try to be helpful.
432
433    The alignment chosen is arbitrary; usually data bus width is
434    important here, not the possibly larger cache line size.  */
435 enum { REMOTE_ALIGN_WRITES = 16 };
436
437 /* Prototypes for local functions.  */
438 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
439 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
440                                  int forever, int *is_notif);
441
442 struct remote_state;
443
444 static int remote_vkill (int pid, struct remote_state *rs);
445
446 static void remote_kill_k (void);
447
448 static int readchar (int timeout);
449
450 static void remote_serial_write (const char *str, int len);
451
452 static void interrupt_query (void);
453
454 static void set_general_thread (ptid_t ptid);
455 static void set_continue_thread (ptid_t ptid);
456
457 static void get_offsets (void);
458
459 static void skip_frame (void);
460
461 static long read_frame (char **buf_p, long *sizeof_buf);
462
463 static int hexnumlen (ULONGEST num);
464
465 static int stubhex (int ch);
466
467 static int hexnumstr (char *, ULONGEST);
468
469 static int hexnumnstr (char *, ULONGEST, int);
470
471 static CORE_ADDR remote_address_masked (CORE_ADDR);
472
473 static void print_packet (const char *);
474
475 static int stub_unpack_int (char *buff, int fieldlength);
476
477 static ptid_t remote_current_thread (ptid_t oldptid);
478
479 static int putpkt_binary (const char *buf, int cnt);
480
481 static void check_binary_download (CORE_ADDR addr);
482
483 struct packet_config;
484
485 static void show_packet_config_cmd (struct packet_config *config);
486
487 static void show_remote_protocol_packet_cmd (struct ui_file *file,
488                                              int from_tty,
489                                              struct cmd_list_element *c,
490                                              const char *value);
491
492 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
493 static ptid_t read_ptid (const char *buf, const char **obuf);
494
495 static void remote_query_supported (void);
496
497 static void remote_check_symbols (void);
498
499 struct stop_reply;
500 static void stop_reply_xfree (struct stop_reply *);
501 static void remote_parse_stop_reply (char *, struct stop_reply *);
502 static void push_stop_reply (struct stop_reply *);
503 static void discard_pending_stop_replies_in_queue (struct remote_state *);
504 static int peek_stop_reply (ptid_t ptid);
505
506 struct threads_listing_context;
507 static void remove_new_fork_children (struct threads_listing_context *);
508
509 static void remote_async_inferior_event_handler (gdb_client_data);
510
511 static int remote_read_description_p (struct target_ops *target);
512
513 static void remote_console_output (char *msg);
514
515 static void remote_btrace_reset (void);
516
517 static void remote_btrace_maybe_reopen (void);
518
519 static int stop_reply_queue_length (void);
520
521 static void remote_unpush_and_throw (void);
522
523 static struct remote_state *get_remote_state (void);
524
525 /* For "remote".  */
526
527 static struct cmd_list_element *remote_cmdlist;
528
529 /* For "set remote" and "show remote".  */
530
531 static struct cmd_list_element *remote_set_cmdlist;
532 static struct cmd_list_element *remote_show_cmdlist;
533
534 /* Stub vCont actions support.
535
536    Each field is a boolean flag indicating whether the stub reports
537    support for the corresponding action.  */
538
539 struct vCont_action_support
540 {
541   /* vCont;t */
542   bool t = false;
543
544   /* vCont;r */
545   bool r = false;
546
547   /* vCont;s */
548   bool s = false;
549
550   /* vCont;S */
551   bool S = false;
552 };
553
554 /* Controls whether GDB is willing to use range stepping.  */
555
556 static int use_range_stepping = 1;
557
558 #define OPAQUETHREADBYTES 8
559
560 /* a 64 bit opaque identifier */
561 typedef unsigned char threadref[OPAQUETHREADBYTES];
562
563 /* About this many threadisds fit in a packet.  */
564
565 #define MAXTHREADLISTRESULTS 32
566
567 /* The max number of chars in debug output.  The rest of chars are
568    omitted.  */
569
570 #define REMOTE_DEBUG_MAX_CHAR 512
571
572 /* Data for the vFile:pread readahead cache.  */
573
574 struct readahead_cache
575 {
576   /* Invalidate the readahead cache.  */
577   void invalidate ();
578
579   /* Invalidate the readahead cache if it is holding data for FD.  */
580   void invalidate_fd (int fd);
581
582   /* Serve pread from the readahead cache.  Returns number of bytes
583      read, or 0 if the request can't be served from the cache.  */
584   int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
585
586   /* The file descriptor for the file that is being cached.  -1 if the
587      cache is invalid.  */
588   int fd = -1;
589
590   /* The offset into the file that the cache buffer corresponds
591      to.  */
592   ULONGEST offset = 0;
593
594   /* The buffer holding the cache contents.  */
595   gdb_byte *buf = nullptr;
596   /* The buffer's size.  We try to read as much as fits into a packet
597      at a time.  */
598   size_t bufsize = 0;
599
600   /* Cache hit and miss counters.  */
601   ULONGEST hit_count = 0;
602   ULONGEST miss_count = 0;
603 };
604
605 /* Description of the remote protocol state for the currently
606    connected target.  This is per-target state, and independent of the
607    selected architecture.  */
608
609 struct remote_state
610 {
611   remote_state ();
612   ~remote_state ();
613
614   /* A buffer to use for incoming packets, and its current size.  The
615      buffer is grown dynamically for larger incoming packets.
616      Outgoing packets may also be constructed in this buffer.
617      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
618      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
619      packets.  */
620   char *buf;
621   long buf_size;
622
623   /* True if we're going through initial connection setup (finding out
624      about the remote side's threads, relocating symbols, etc.).  */
625   bool starting_up = false;
626
627   /* If we negotiated packet size explicitly (and thus can bypass
628      heuristics for the largest packet size that will not overflow
629      a buffer in the stub), this will be set to that packet size.
630      Otherwise zero, meaning to use the guessed size.  */
631   long explicit_packet_size = 0;
632
633   /* remote_wait is normally called when the target is running and
634      waits for a stop reply packet.  But sometimes we need to call it
635      when the target is already stopped.  We can send a "?" packet
636      and have remote_wait read the response.  Or, if we already have
637      the response, we can stash it in BUF and tell remote_wait to
638      skip calling getpkt.  This flag is set when BUF contains a
639      stop reply packet and the target is not waiting.  */
640   int cached_wait_status = 0;
641
642   /* True, if in no ack mode.  That is, neither GDB nor the stub will
643      expect acks from each other.  The connection is assumed to be
644      reliable.  */
645   bool noack_mode = false;
646
647   /* True if we're connected in extended remote mode.  */
648   bool extended = false;
649
650   /* True if we resumed the target and we're waiting for the target to
651      stop.  In the mean time, we can't start another command/query.
652      The remote server wouldn't be ready to process it, so we'd
653      timeout waiting for a reply that would never come and eventually
654      we'd close the connection.  This can happen in asynchronous mode
655      because we allow GDB commands while the target is running.  */
656   bool waiting_for_stop_reply = false;
657
658   /* The status of the stub support for the various vCont actions.  */
659   vCont_action_support supports_vCont;
660
661   /* True if the user has pressed Ctrl-C, but the target hasn't
662      responded to that.  */
663   bool ctrlc_pending_p = false;
664
665   /* True if we saw a Ctrl-C while reading or writing from/to the
666      remote descriptor.  At that point it is not safe to send a remote
667      interrupt packet, so we instead remember we saw the Ctrl-C and
668      process it once we're done with sending/receiving the current
669      packet, which should be shortly.  If however that takes too long,
670      and the user presses Ctrl-C again, we offer to disconnect.  */
671   bool got_ctrlc_during_io = false;
672
673   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
674      remote_open knows that we don't have a file open when the program
675      starts.  */
676   struct serial *remote_desc = nullptr;
677
678   /* These are the threads which we last sent to the remote system.  The
679      TID member will be -1 for all or -2 for not sent yet.  */
680   ptid_t general_thread = null_ptid;
681   ptid_t continue_thread = null_ptid;
682
683   /* This is the traceframe which we last selected on the remote system.
684      It will be -1 if no traceframe is selected.  */
685   int remote_traceframe_number = -1;
686
687   char *last_pass_packet = nullptr;
688
689   /* The last QProgramSignals packet sent to the target.  We bypass
690      sending a new program signals list down to the target if the new
691      packet is exactly the same as the last we sent.  IOW, we only let
692      the target know about program signals list changes.  */
693   char *last_program_signals_packet = nullptr;
694
695   gdb_signal last_sent_signal = GDB_SIGNAL_0;
696
697   bool last_sent_step = false;
698
699   /* The execution direction of the last resume we got.  */
700   exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
701
702   char *finished_object = nullptr;
703   char *finished_annex = nullptr;
704   ULONGEST finished_offset = 0;
705
706   /* Should we try the 'ThreadInfo' query packet?
707
708      This variable (NOT available to the user: auto-detect only!)
709      determines whether GDB will use the new, simpler "ThreadInfo"
710      query or the older, more complex syntax for thread queries.
711      This is an auto-detect variable (set to true at each connect,
712      and set to false when the target fails to recognize it).  */
713   bool use_threadinfo_query = false;
714   bool use_threadextra_query = false;
715
716   threadref echo_nextthread {};
717   threadref nextthread {};
718   threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
719
720   /* The state of remote notification.  */
721   struct remote_notif_state *notif_state = nullptr;
722
723   /* The branch trace configuration.  */
724   struct btrace_config btrace_config {};
725
726   /* The argument to the last "vFile:setfs:" packet we sent, used
727      to avoid sending repeated unnecessary "vFile:setfs:" packets.
728      Initialized to -1 to indicate that no "vFile:setfs:" packet
729      has yet been sent.  */
730   int fs_pid = -1;
731
732   /* A readahead cache for vFile:pread.  Often, reading a binary
733      involves a sequence of small reads.  E.g., when parsing an ELF
734      file.  A readahead cache helps mostly the case of remote
735      debugging on a connection with higher latency, due to the
736      request/reply nature of the RSP.  We only cache data for a single
737      file descriptor at a time.  */
738   struct readahead_cache readahead_cache;
739 };
740
741 /* Private data that we'll store in (struct thread_info)->priv.  */
742 struct remote_thread_info : public private_thread_info
743 {
744   std::string extra;
745   std::string name;
746   int core = -1;
747
748   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
749      sequence of bytes.  */
750   gdb::byte_vector thread_handle;
751
752   /* Whether the target stopped for a breakpoint/watchpoint.  */
753   enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
754
755   /* This is set to the data address of the access causing the target
756      to stop for a watchpoint.  */
757   CORE_ADDR watch_data_address = 0;
758
759   /* Fields used by the vCont action coalescing implemented in
760      remote_resume / remote_commit_resume.  remote_resume stores each
761      thread's last resume request in these fields, so that a later
762      remote_commit_resume knows which is the proper action for this
763      thread to include in the vCont packet.  */
764
765   /* True if the last target_resume call for this thread was a step
766      request, false if a continue request.  */
767   int last_resume_step = 0;
768
769   /* The signal specified in the last target_resume call for this
770      thread.  */
771   gdb_signal last_resume_sig = GDB_SIGNAL_0;
772
773   /* Whether this thread was already vCont-resumed on the remote
774      side.  */
775   int vcont_resumed = 0;
776 };
777
778 remote_state::remote_state ()
779 {
780   /* The default buffer size is unimportant; it will be expanded
781      whenever a larger buffer is needed. */
782   this->buf_size = 400;
783   this->buf = (char *) xmalloc (this->buf_size);
784 }
785
786 remote_state::~remote_state ()
787 {
788   xfree (this->last_pass_packet);
789   xfree (this->last_program_signals_packet);
790   xfree (this->buf);
791   xfree (this->finished_object);
792   xfree (this->finished_annex);
793 }
794
795 /* This data could be associated with a target, but we do not always
796    have access to the current target when we need it, so for now it is
797    static.  This will be fine for as long as only one target is in use
798    at a time.  */
799 static struct remote_state *remote_state;
800
801 static struct remote_state *
802 get_remote_state_raw (void)
803 {
804   return remote_state;
805 }
806
807 /* Description of the remote protocol for a given architecture.  */
808
809 struct packet_reg
810 {
811   long offset; /* Offset into G packet.  */
812   long regnum; /* GDB's internal register number.  */
813   LONGEST pnum; /* Remote protocol register number.  */
814   int in_g_packet; /* Always part of G packet.  */
815   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
816      at present.  */
817   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
818      at present.  */
819 };
820
821 struct remote_arch_state
822 {
823   /* Description of the remote protocol registers.  */
824   long sizeof_g_packet;
825
826   /* Description of the remote protocol registers indexed by REGNUM
827      (making an array gdbarch_num_regs in size).  */
828   struct packet_reg *regs;
829
830   /* This is the size (in chars) of the first response to the ``g''
831      packet.  It is used as a heuristic when determining the maximum
832      size of memory-read and memory-write packets.  A target will
833      typically only reserve a buffer large enough to hold the ``g''
834      packet.  The size does not include packet overhead (headers and
835      trailers).  */
836   long actual_register_packet_size;
837
838   /* This is the maximum size (in chars) of a non read/write packet.
839      It is also used as a cap on the size of read/write packets.  */
840   long remote_packet_size;
841 };
842
843 /* Utility: generate error from an incoming stub packet.  */
844 static void
845 trace_error (char *buf)
846 {
847   if (*buf++ != 'E')
848     return;                     /* not an error msg */
849   switch (*buf)
850     {
851     case '1':                   /* malformed packet error */
852       if (*++buf == '0')        /*   general case: */
853         error (_("remote.c: error in outgoing packet."));
854       else
855         error (_("remote.c: error in outgoing packet at field #%ld."),
856                strtol (buf, NULL, 16));
857     default:
858       error (_("Target returns error code '%s'."), buf);
859     }
860 }
861
862 /* Utility: wait for reply from stub, while accepting "O" packets.  */
863
864 static char *
865 remote_get_noisy_reply ()
866 {
867   struct remote_state *rs = get_remote_state ();
868
869   do                            /* Loop on reply from remote stub.  */
870     {
871       char *buf;
872
873       QUIT;                     /* Allow user to bail out with ^C.  */
874       getpkt (&rs->buf, &rs->buf_size, 0);
875       buf = rs->buf;
876       if (buf[0] == 'E')
877         trace_error (buf);
878       else if (startswith (buf, "qRelocInsn:"))
879         {
880           ULONGEST ul;
881           CORE_ADDR from, to, org_to;
882           const char *p, *pp;
883           int adjusted_size = 0;
884           int relocated = 0;
885
886           p = buf + strlen ("qRelocInsn:");
887           pp = unpack_varlen_hex (p, &ul);
888           if (*pp != ';')
889             error (_("invalid qRelocInsn packet: %s"), buf);
890           from = ul;
891
892           p = pp + 1;
893           unpack_varlen_hex (p, &ul);
894           to = ul;
895
896           org_to = to;
897
898           TRY
899             {
900               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
901               relocated = 1;
902             }
903           CATCH (ex, RETURN_MASK_ALL)
904             {
905               if (ex.error == MEMORY_ERROR)
906                 {
907                   /* Propagate memory errors silently back to the
908                      target.  The stub may have limited the range of
909                      addresses we can write to, for example.  */
910                 }
911               else
912                 {
913                   /* Something unexpectedly bad happened.  Be verbose
914                      so we can tell what, and propagate the error back
915                      to the stub, so it doesn't get stuck waiting for
916                      a response.  */
917                   exception_fprintf (gdb_stderr, ex,
918                                      _("warning: relocating instruction: "));
919                 }
920               putpkt ("E01");
921             }
922           END_CATCH
923
924           if (relocated)
925             {
926               adjusted_size = to - org_to;
927
928               xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
929               putpkt (buf);
930             }
931         }
932       else if (buf[0] == 'O' && buf[1] != 'K')
933         remote_console_output (buf + 1);        /* 'O' message from stub */
934       else
935         return buf;             /* Here's the actual reply.  */
936     }
937   while (1);
938 }
939
940 /* Handle for retreving the remote protocol data from gdbarch.  */
941 static struct gdbarch_data *remote_gdbarch_data_handle;
942
943 static struct remote_arch_state *
944 get_remote_arch_state (struct gdbarch *gdbarch)
945 {
946   gdb_assert (gdbarch != NULL);
947   return ((struct remote_arch_state *)
948           gdbarch_data (gdbarch, remote_gdbarch_data_handle));
949 }
950
951 /* Fetch the global remote target state.  */
952
953 static struct remote_state *
954 get_remote_state (void)
955 {
956   /* Make sure that the remote architecture state has been
957      initialized, because doing so might reallocate rs->buf.  Any
958      function which calls getpkt also needs to be mindful of changes
959      to rs->buf, but this call limits the number of places which run
960      into trouble.  */
961   get_remote_arch_state (target_gdbarch ());
962
963   return get_remote_state_raw ();
964 }
965
966 /* Cleanup routine for the remote module's pspace data.  */
967
968 static void
969 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
970 {
971   char *remote_exec_file = (char *) arg;
972
973   xfree (remote_exec_file);
974 }
975
976 /* Fetch the remote exec-file from the current program space.  */
977
978 static const char *
979 get_remote_exec_file (void)
980 {
981   char *remote_exec_file;
982
983   remote_exec_file
984     = (char *) program_space_data (current_program_space,
985                                    remote_pspace_data);
986   if (remote_exec_file == NULL)
987     return "";
988
989   return remote_exec_file;
990 }
991
992 /* Set the remote exec file for PSPACE.  */
993
994 static void
995 set_pspace_remote_exec_file (struct program_space *pspace,
996                         char *remote_exec_file)
997 {
998   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
999
1000   xfree (old_file);
1001   set_program_space_data (pspace, remote_pspace_data,
1002                           xstrdup (remote_exec_file));
1003 }
1004
1005 /* The "set/show remote exec-file" set command hook.  */
1006
1007 static void
1008 set_remote_exec_file (const char *ignored, int from_tty,
1009                       struct cmd_list_element *c)
1010 {
1011   gdb_assert (remote_exec_file_var != NULL);
1012   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1013 }
1014
1015 /* The "set/show remote exec-file" show command hook.  */
1016
1017 static void
1018 show_remote_exec_file (struct ui_file *file, int from_tty,
1019                        struct cmd_list_element *cmd, const char *value)
1020 {
1021   fprintf_filtered (file, "%s\n", remote_exec_file_var);
1022 }
1023
1024 static int
1025 compare_pnums (const void *lhs_, const void *rhs_)
1026 {
1027   const struct packet_reg * const *lhs
1028     = (const struct packet_reg * const *) lhs_;
1029   const struct packet_reg * const *rhs
1030     = (const struct packet_reg * const *) rhs_;
1031
1032   if ((*lhs)->pnum < (*rhs)->pnum)
1033     return -1;
1034   else if ((*lhs)->pnum == (*rhs)->pnum)
1035     return 0;
1036   else
1037     return 1;
1038 }
1039
1040 static int
1041 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1042 {
1043   int regnum, num_remote_regs, offset;
1044   struct packet_reg **remote_regs;
1045
1046   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1047     {
1048       struct packet_reg *r = &regs[regnum];
1049
1050       if (register_size (gdbarch, regnum) == 0)
1051         /* Do not try to fetch zero-sized (placeholder) registers.  */
1052         r->pnum = -1;
1053       else
1054         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1055
1056       r->regnum = regnum;
1057     }
1058
1059   /* Define the g/G packet format as the contents of each register
1060      with a remote protocol number, in order of ascending protocol
1061      number.  */
1062
1063   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1064   for (num_remote_regs = 0, regnum = 0;
1065        regnum < gdbarch_num_regs (gdbarch);
1066        regnum++)
1067     if (regs[regnum].pnum != -1)
1068       remote_regs[num_remote_regs++] = &regs[regnum];
1069
1070   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1071          compare_pnums);
1072
1073   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1074     {
1075       remote_regs[regnum]->in_g_packet = 1;
1076       remote_regs[regnum]->offset = offset;
1077       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1078     }
1079
1080   return offset;
1081 }
1082
1083 /* Given the architecture described by GDBARCH, return the remote
1084    protocol register's number and the register's offset in the g/G
1085    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1086    If the target does not have a mapping for REGNUM, return false,
1087    otherwise, return true.  */
1088
1089 int
1090 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1091                                    int *pnum, int *poffset)
1092 {
1093   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1094
1095   std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1096
1097   map_regcache_remote_table (gdbarch, regs.data ());
1098
1099   *pnum = regs[regnum].pnum;
1100   *poffset = regs[regnum].offset;
1101
1102   return *pnum != -1;
1103 }
1104
1105 static void *
1106 init_remote_state (struct gdbarch *gdbarch)
1107 {
1108   struct remote_state *rs = get_remote_state_raw ();
1109   struct remote_arch_state *rsa;
1110
1111   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
1112
1113   /* Use the architecture to build a regnum<->pnum table, which will be
1114      1:1 unless a feature set specifies otherwise.  */
1115   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
1116                                       gdbarch_num_regs (gdbarch),
1117                                       struct packet_reg);
1118
1119   /* Record the maximum possible size of the g packet - it may turn out
1120      to be smaller.  */
1121   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
1122
1123   /* Default maximum number of characters in a packet body.  Many
1124      remote stubs have a hardwired buffer size of 400 bytes
1125      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
1126      as the maximum packet-size to ensure that the packet and an extra
1127      NUL character can always fit in the buffer.  This stops GDB
1128      trashing stubs that try to squeeze an extra NUL into what is
1129      already a full buffer (As of 1999-12-04 that was most stubs).  */
1130   rsa->remote_packet_size = 400 - 1;
1131
1132   /* This one is filled in when a ``g'' packet is received.  */
1133   rsa->actual_register_packet_size = 0;
1134
1135   /* Should rsa->sizeof_g_packet needs more space than the
1136      default, adjust the size accordingly.  Remember that each byte is
1137      encoded as two characters.  32 is the overhead for the packet
1138      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
1139      (``$NN:G...#NN'') is a better guess, the below has been padded a
1140      little.  */
1141   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
1142     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
1143
1144   /* Make sure that the packet buffer is plenty big enough for
1145      this architecture.  */
1146   if (rs->buf_size < rsa->remote_packet_size)
1147     {
1148       rs->buf_size = 2 * rsa->remote_packet_size;
1149       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
1150     }
1151
1152   return rsa;
1153 }
1154
1155 /* Return the current allowed size of a remote packet.  This is
1156    inferred from the current architecture, and should be used to
1157    limit the length of outgoing packets.  */
1158 static long
1159 get_remote_packet_size (void)
1160 {
1161   struct remote_state *rs = get_remote_state ();
1162   remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1163
1164   if (rs->explicit_packet_size)
1165     return rs->explicit_packet_size;
1166
1167   return rsa->remote_packet_size;
1168 }
1169
1170 static struct packet_reg *
1171 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1172                         long regnum)
1173 {
1174   if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1175     return NULL;
1176   else
1177     {
1178       struct packet_reg *r = &rsa->regs[regnum];
1179
1180       gdb_assert (r->regnum == regnum);
1181       return r;
1182     }
1183 }
1184
1185 static struct packet_reg *
1186 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1187                       LONGEST pnum)
1188 {
1189   int i;
1190
1191   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1192     {
1193       struct packet_reg *r = &rsa->regs[i];
1194
1195       if (r->pnum == pnum)
1196         return r;
1197     }
1198   return NULL;
1199 }
1200
1201 static remote_target remote_ops;
1202
1203 static extended_remote_target extended_remote_ops;
1204
1205 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
1206    ``forever'' still use the normal timeout mechanism.  This is
1207    currently used by the ASYNC code to guarentee that target reads
1208    during the initial connect always time-out.  Once getpkt has been
1209    modified to return a timeout indication and, in turn
1210    remote_wait()/wait_for_inferior() have gained a timeout parameter
1211    this can go away.  */
1212 static int wait_forever_enabled_p = 1;
1213
1214 /* Allow the user to specify what sequence to send to the remote
1215    when he requests a program interruption: Although ^C is usually
1216    what remote systems expect (this is the default, here), it is
1217    sometimes preferable to send a break.  On other systems such
1218    as the Linux kernel, a break followed by g, which is Magic SysRq g
1219    is required in order to interrupt the execution.  */
1220 const char interrupt_sequence_control_c[] = "Ctrl-C";
1221 const char interrupt_sequence_break[] = "BREAK";
1222 const char interrupt_sequence_break_g[] = "BREAK-g";
1223 static const char *const interrupt_sequence_modes[] =
1224   {
1225     interrupt_sequence_control_c,
1226     interrupt_sequence_break,
1227     interrupt_sequence_break_g,
1228     NULL
1229   };
1230 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1231
1232 static void
1233 show_interrupt_sequence (struct ui_file *file, int from_tty,
1234                          struct cmd_list_element *c,
1235                          const char *value)
1236 {
1237   if (interrupt_sequence_mode == interrupt_sequence_control_c)
1238     fprintf_filtered (file,
1239                       _("Send the ASCII ETX character (Ctrl-c) "
1240                         "to the remote target to interrupt the "
1241                         "execution of the program.\n"));
1242   else if (interrupt_sequence_mode == interrupt_sequence_break)
1243     fprintf_filtered (file,
1244                       _("send a break signal to the remote target "
1245                         "to interrupt the execution of the program.\n"));
1246   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1247     fprintf_filtered (file,
1248                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1249                         "the remote target to interrupt the execution "
1250                         "of Linux kernel.\n"));
1251   else
1252     internal_error (__FILE__, __LINE__,
1253                     _("Invalid value for interrupt_sequence_mode: %s."),
1254                     interrupt_sequence_mode);
1255 }
1256
1257 /* This boolean variable specifies whether interrupt_sequence is sent
1258    to the remote target when gdb connects to it.
1259    This is mostly needed when you debug the Linux kernel: The Linux kernel
1260    expects BREAK g which is Magic SysRq g for connecting gdb.  */
1261 static int interrupt_on_connect = 0;
1262
1263 /* This variable is used to implement the "set/show remotebreak" commands.
1264    Since these commands are now deprecated in favor of "set/show remote
1265    interrupt-sequence", it no longer has any effect on the code.  */
1266 static int remote_break;
1267
1268 static void
1269 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1270 {
1271   if (remote_break)
1272     interrupt_sequence_mode = interrupt_sequence_break;
1273   else
1274     interrupt_sequence_mode = interrupt_sequence_control_c;
1275 }
1276
1277 static void
1278 show_remotebreak (struct ui_file *file, int from_tty,
1279                   struct cmd_list_element *c,
1280                   const char *value)
1281 {
1282 }
1283
1284 /* This variable sets the number of bits in an address that are to be
1285    sent in a memory ("M" or "m") packet.  Normally, after stripping
1286    leading zeros, the entire address would be sent.  This variable
1287    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
1288    initial implementation of remote.c restricted the address sent in
1289    memory packets to ``host::sizeof long'' bytes - (typically 32
1290    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
1291    address was never sent.  Since fixing this bug may cause a break in
1292    some remote targets this variable is principly provided to
1293    facilitate backward compatibility.  */
1294
1295 static unsigned int remote_address_size;
1296
1297 \f
1298 /* User configurable variables for the number of characters in a
1299    memory read/write packet.  MIN (rsa->remote_packet_size,
1300    rsa->sizeof_g_packet) is the default.  Some targets need smaller
1301    values (fifo overruns, et.al.) and some users need larger values
1302    (speed up transfers).  The variables ``preferred_*'' (the user
1303    request), ``current_*'' (what was actually set) and ``forced_*''
1304    (Positive - a soft limit, negative - a hard limit).  */
1305
1306 struct memory_packet_config
1307 {
1308   const char *name;
1309   long size;
1310   int fixed_p;
1311 };
1312
1313 /* The default max memory-write-packet-size.  The 16k is historical.
1314    (It came from older GDB's using alloca for buffers and the
1315    knowledge (folklore?) that some hosts don't cope very well with
1316    large alloca calls.)  */
1317 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1318
1319 /* The minimum remote packet size for memory transfers.  Ensures we
1320    can write at least one byte.  */
1321 #define MIN_MEMORY_PACKET_SIZE 20
1322
1323 /* Compute the current size of a read/write packet.  Since this makes
1324    use of ``actual_register_packet_size'' the computation is dynamic.  */
1325
1326 static long
1327 get_memory_packet_size (struct memory_packet_config *config)
1328 {
1329   struct remote_state *rs = get_remote_state ();
1330   remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1331
1332   long what_they_get;
1333   if (config->fixed_p)
1334     {
1335       if (config->size <= 0)
1336         what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1337       else
1338         what_they_get = config->size;
1339     }
1340   else
1341     {
1342       what_they_get = get_remote_packet_size ();
1343       /* Limit the packet to the size specified by the user.  */
1344       if (config->size > 0
1345           && what_they_get > config->size)
1346         what_they_get = config->size;
1347
1348       /* Limit it to the size of the targets ``g'' response unless we have
1349          permission from the stub to use a larger packet size.  */
1350       if (rs->explicit_packet_size == 0
1351           && rsa->actual_register_packet_size > 0
1352           && what_they_get > rsa->actual_register_packet_size)
1353         what_they_get = rsa->actual_register_packet_size;
1354     }
1355   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1356     what_they_get = MIN_MEMORY_PACKET_SIZE;
1357
1358   /* Make sure there is room in the global buffer for this packet
1359      (including its trailing NUL byte).  */
1360   if (rs->buf_size < what_they_get + 1)
1361     {
1362       rs->buf_size = 2 * what_they_get;
1363       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1364     }
1365
1366   return what_they_get;
1367 }
1368
1369 /* Update the size of a read/write packet.  If they user wants
1370    something really big then do a sanity check.  */
1371
1372 static void
1373 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1374 {
1375   int fixed_p = config->fixed_p;
1376   long size = config->size;
1377
1378   if (args == NULL)
1379     error (_("Argument required (integer, `fixed' or `limited')."));
1380   else if (strcmp (args, "hard") == 0
1381       || strcmp (args, "fixed") == 0)
1382     fixed_p = 1;
1383   else if (strcmp (args, "soft") == 0
1384            || strcmp (args, "limit") == 0)
1385     fixed_p = 0;
1386   else
1387     {
1388       char *end;
1389
1390       size = strtoul (args, &end, 0);
1391       if (args == end)
1392         error (_("Invalid %s (bad syntax)."), config->name);
1393
1394       /* Instead of explicitly capping the size of a packet to or
1395          disallowing it, the user is allowed to set the size to
1396          something arbitrarily large.  */
1397     }
1398
1399   /* So that the query shows the correct value.  */
1400   if (size <= 0)
1401     size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1402
1403   /* Extra checks?  */
1404   if (fixed_p && !config->fixed_p)
1405     {
1406       if (! query (_("The target may not be able to correctly handle a %s\n"
1407                    "of %ld bytes. Change the packet size? "),
1408                    config->name, size))
1409         error (_("Packet size not changed."));
1410     }
1411   /* Update the config.  */
1412   config->fixed_p = fixed_p;
1413   config->size = size;
1414 }
1415
1416 static void
1417 show_memory_packet_size (struct memory_packet_config *config)
1418 {
1419   printf_filtered (_("The %s is %ld. "), config->name, config->size);
1420   if (config->fixed_p)
1421     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1422                      get_memory_packet_size (config));
1423   else
1424     printf_filtered (_("Packets are limited to %ld bytes.\n"),
1425                      get_memory_packet_size (config));
1426 }
1427
1428 static struct memory_packet_config memory_write_packet_config =
1429 {
1430   "memory-write-packet-size",
1431 };
1432
1433 static void
1434 set_memory_write_packet_size (const char *args, int from_tty)
1435 {
1436   set_memory_packet_size (args, &memory_write_packet_config);
1437 }
1438
1439 static void
1440 show_memory_write_packet_size (const char *args, int from_tty)
1441 {
1442   show_memory_packet_size (&memory_write_packet_config);
1443 }
1444
1445 static long
1446 get_memory_write_packet_size (void)
1447 {
1448   return get_memory_packet_size (&memory_write_packet_config);
1449 }
1450
1451 static struct memory_packet_config memory_read_packet_config =
1452 {
1453   "memory-read-packet-size",
1454 };
1455
1456 static void
1457 set_memory_read_packet_size (const char *args, int from_tty)
1458 {
1459   set_memory_packet_size (args, &memory_read_packet_config);
1460 }
1461
1462 static void
1463 show_memory_read_packet_size (const char *args, int from_tty)
1464 {
1465   show_memory_packet_size (&memory_read_packet_config);
1466 }
1467
1468 static long
1469 get_memory_read_packet_size (void)
1470 {
1471   long size = get_memory_packet_size (&memory_read_packet_config);
1472
1473   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1474      extra buffer size argument before the memory read size can be
1475      increased beyond this.  */
1476   if (size > get_remote_packet_size ())
1477     size = get_remote_packet_size ();
1478   return size;
1479 }
1480
1481 \f
1482 /* Generic configuration support for packets the stub optionally
1483    supports.  Allows the user to specify the use of the packet as well
1484    as allowing GDB to auto-detect support in the remote stub.  */
1485
1486 enum packet_support
1487   {
1488     PACKET_SUPPORT_UNKNOWN = 0,
1489     PACKET_ENABLE,
1490     PACKET_DISABLE
1491   };
1492
1493 struct packet_config
1494   {
1495     const char *name;
1496     const char *title;
1497
1498     /* If auto, GDB auto-detects support for this packet or feature,
1499        either through qSupported, or by trying the packet and looking
1500        at the response.  If true, GDB assumes the target supports this
1501        packet.  If false, the packet is disabled.  Configs that don't
1502        have an associated command always have this set to auto.  */
1503     enum auto_boolean detect;
1504
1505     /* Does the target support this packet?  */
1506     enum packet_support support;
1507   };
1508
1509 /* Analyze a packet's return value and update the packet config
1510    accordingly.  */
1511
1512 enum packet_result
1513 {
1514   PACKET_ERROR,
1515   PACKET_OK,
1516   PACKET_UNKNOWN
1517 };
1518
1519 static enum packet_support packet_config_support (struct packet_config *config);
1520 static enum packet_support packet_support (int packet);
1521
1522 static void
1523 show_packet_config_cmd (struct packet_config *config)
1524 {
1525   const char *support = "internal-error";
1526
1527   switch (packet_config_support (config))
1528     {
1529     case PACKET_ENABLE:
1530       support = "enabled";
1531       break;
1532     case PACKET_DISABLE:
1533       support = "disabled";
1534       break;
1535     case PACKET_SUPPORT_UNKNOWN:
1536       support = "unknown";
1537       break;
1538     }
1539   switch (config->detect)
1540     {
1541     case AUTO_BOOLEAN_AUTO:
1542       printf_filtered (_("Support for the `%s' packet "
1543                          "is auto-detected, currently %s.\n"),
1544                        config->name, support);
1545       break;
1546     case AUTO_BOOLEAN_TRUE:
1547     case AUTO_BOOLEAN_FALSE:
1548       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1549                        config->name, support);
1550       break;
1551     }
1552 }
1553
1554 static void
1555 add_packet_config_cmd (struct packet_config *config, const char *name,
1556                        const char *title, int legacy)
1557 {
1558   char *set_doc;
1559   char *show_doc;
1560   char *cmd_name;
1561
1562   config->name = name;
1563   config->title = title;
1564   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1565                         name, title);
1566   show_doc = xstrprintf ("Show current use of remote "
1567                          "protocol `%s' (%s) packet",
1568                          name, title);
1569   /* set/show TITLE-packet {auto,on,off} */
1570   cmd_name = xstrprintf ("%s-packet", title);
1571   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1572                                 &config->detect, set_doc,
1573                                 show_doc, NULL, /* help_doc */
1574                                 NULL,
1575                                 show_remote_protocol_packet_cmd,
1576                                 &remote_set_cmdlist, &remote_show_cmdlist);
1577   /* The command code copies the documentation strings.  */
1578   xfree (set_doc);
1579   xfree (show_doc);
1580   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1581   if (legacy)
1582     {
1583       char *legacy_name;
1584
1585       legacy_name = xstrprintf ("%s-packet", name);
1586       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1587                      &remote_set_cmdlist);
1588       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1589                      &remote_show_cmdlist);
1590     }
1591 }
1592
1593 static enum packet_result
1594 packet_check_result (const char *buf)
1595 {
1596   if (buf[0] != '\0')
1597     {
1598       /* The stub recognized the packet request.  Check that the
1599          operation succeeded.  */
1600       if (buf[0] == 'E'
1601           && isxdigit (buf[1]) && isxdigit (buf[2])
1602           && buf[3] == '\0')
1603         /* "Enn"  - definitly an error.  */
1604         return PACKET_ERROR;
1605
1606       /* Always treat "E." as an error.  This will be used for
1607          more verbose error messages, such as E.memtypes.  */
1608       if (buf[0] == 'E' && buf[1] == '.')
1609         return PACKET_ERROR;
1610
1611       /* The packet may or may not be OK.  Just assume it is.  */
1612       return PACKET_OK;
1613     }
1614   else
1615     /* The stub does not support the packet.  */
1616     return PACKET_UNKNOWN;
1617 }
1618
1619 static enum packet_result
1620 packet_ok (const char *buf, struct packet_config *config)
1621 {
1622   enum packet_result result;
1623
1624   if (config->detect != AUTO_BOOLEAN_TRUE
1625       && config->support == PACKET_DISABLE)
1626     internal_error (__FILE__, __LINE__,
1627                     _("packet_ok: attempt to use a disabled packet"));
1628
1629   result = packet_check_result (buf);
1630   switch (result)
1631     {
1632     case PACKET_OK:
1633     case PACKET_ERROR:
1634       /* The stub recognized the packet request.  */
1635       if (config->support == PACKET_SUPPORT_UNKNOWN)
1636         {
1637           if (remote_debug)
1638             fprintf_unfiltered (gdb_stdlog,
1639                                 "Packet %s (%s) is supported\n",
1640                                 config->name, config->title);
1641           config->support = PACKET_ENABLE;
1642         }
1643       break;
1644     case PACKET_UNKNOWN:
1645       /* The stub does not support the packet.  */
1646       if (config->detect == AUTO_BOOLEAN_AUTO
1647           && config->support == PACKET_ENABLE)
1648         {
1649           /* If the stub previously indicated that the packet was
1650              supported then there is a protocol error.  */
1651           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1652                  config->name, config->title);
1653         }
1654       else if (config->detect == AUTO_BOOLEAN_TRUE)
1655         {
1656           /* The user set it wrong.  */
1657           error (_("Enabled packet %s (%s) not recognized by stub"),
1658                  config->name, config->title);
1659         }
1660
1661       if (remote_debug)
1662         fprintf_unfiltered (gdb_stdlog,
1663                             "Packet %s (%s) is NOT supported\n",
1664                             config->name, config->title);
1665       config->support = PACKET_DISABLE;
1666       break;
1667     }
1668
1669   return result;
1670 }
1671
1672 enum {
1673   PACKET_vCont = 0,
1674   PACKET_X,
1675   PACKET_qSymbol,
1676   PACKET_P,
1677   PACKET_p,
1678   PACKET_Z0,
1679   PACKET_Z1,
1680   PACKET_Z2,
1681   PACKET_Z3,
1682   PACKET_Z4,
1683   PACKET_vFile_setfs,
1684   PACKET_vFile_open,
1685   PACKET_vFile_pread,
1686   PACKET_vFile_pwrite,
1687   PACKET_vFile_close,
1688   PACKET_vFile_unlink,
1689   PACKET_vFile_readlink,
1690   PACKET_vFile_fstat,
1691   PACKET_qXfer_auxv,
1692   PACKET_qXfer_features,
1693   PACKET_qXfer_exec_file,
1694   PACKET_qXfer_libraries,
1695   PACKET_qXfer_libraries_svr4,
1696   PACKET_qXfer_memory_map,
1697   PACKET_qXfer_spu_read,
1698   PACKET_qXfer_spu_write,
1699   PACKET_qXfer_osdata,
1700   PACKET_qXfer_threads,
1701   PACKET_qXfer_statictrace_read,
1702   PACKET_qXfer_traceframe_info,
1703   PACKET_qXfer_uib,
1704   PACKET_qGetTIBAddr,
1705   PACKET_qGetTLSAddr,
1706   PACKET_qSupported,
1707   PACKET_qTStatus,
1708   PACKET_QPassSignals,
1709   PACKET_QCatchSyscalls,
1710   PACKET_QProgramSignals,
1711   PACKET_QSetWorkingDir,
1712   PACKET_QStartupWithShell,
1713   PACKET_QEnvironmentHexEncoded,
1714   PACKET_QEnvironmentReset,
1715   PACKET_QEnvironmentUnset,
1716   PACKET_qCRC,
1717   PACKET_qSearch_memory,
1718   PACKET_vAttach,
1719   PACKET_vRun,
1720   PACKET_QStartNoAckMode,
1721   PACKET_vKill,
1722   PACKET_qXfer_siginfo_read,
1723   PACKET_qXfer_siginfo_write,
1724   PACKET_qAttached,
1725
1726   /* Support for conditional tracepoints.  */
1727   PACKET_ConditionalTracepoints,
1728
1729   /* Support for target-side breakpoint conditions.  */
1730   PACKET_ConditionalBreakpoints,
1731
1732   /* Support for target-side breakpoint commands.  */
1733   PACKET_BreakpointCommands,
1734
1735   /* Support for fast tracepoints.  */
1736   PACKET_FastTracepoints,
1737
1738   /* Support for static tracepoints.  */
1739   PACKET_StaticTracepoints,
1740
1741   /* Support for installing tracepoints while a trace experiment is
1742      running.  */
1743   PACKET_InstallInTrace,
1744
1745   PACKET_bc,
1746   PACKET_bs,
1747   PACKET_TracepointSource,
1748   PACKET_QAllow,
1749   PACKET_qXfer_fdpic,
1750   PACKET_QDisableRandomization,
1751   PACKET_QAgent,
1752   PACKET_QTBuffer_size,
1753   PACKET_Qbtrace_off,
1754   PACKET_Qbtrace_bts,
1755   PACKET_Qbtrace_pt,
1756   PACKET_qXfer_btrace,
1757
1758   /* Support for the QNonStop packet.  */
1759   PACKET_QNonStop,
1760
1761   /* Support for the QThreadEvents packet.  */
1762   PACKET_QThreadEvents,
1763
1764   /* Support for multi-process extensions.  */
1765   PACKET_multiprocess_feature,
1766
1767   /* Support for enabling and disabling tracepoints while a trace
1768      experiment is running.  */
1769   PACKET_EnableDisableTracepoints_feature,
1770
1771   /* Support for collecting strings using the tracenz bytecode.  */
1772   PACKET_tracenz_feature,
1773
1774   /* Support for continuing to run a trace experiment while GDB is
1775      disconnected.  */
1776   PACKET_DisconnectedTracing_feature,
1777
1778   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1779   PACKET_augmented_libraries_svr4_read_feature,
1780
1781   /* Support for the qXfer:btrace-conf:read packet.  */
1782   PACKET_qXfer_btrace_conf,
1783
1784   /* Support for the Qbtrace-conf:bts:size packet.  */
1785   PACKET_Qbtrace_conf_bts_size,
1786
1787   /* Support for swbreak+ feature.  */
1788   PACKET_swbreak_feature,
1789
1790   /* Support for hwbreak+ feature.  */
1791   PACKET_hwbreak_feature,
1792
1793   /* Support for fork events.  */
1794   PACKET_fork_event_feature,
1795
1796   /* Support for vfork events.  */
1797   PACKET_vfork_event_feature,
1798
1799   /* Support for the Qbtrace-conf:pt:size packet.  */
1800   PACKET_Qbtrace_conf_pt_size,
1801
1802   /* Support for exec events.  */
1803   PACKET_exec_event_feature,
1804
1805   /* Support for query supported vCont actions.  */
1806   PACKET_vContSupported,
1807
1808   /* Support remote CTRL-C.  */
1809   PACKET_vCtrlC,
1810
1811   /* Support TARGET_WAITKIND_NO_RESUMED.  */
1812   PACKET_no_resumed,
1813
1814   PACKET_MAX
1815 };
1816
1817 static struct packet_config remote_protocol_packets[PACKET_MAX];
1818
1819 /* Returns the packet's corresponding "set remote foo-packet" command
1820    state.  See struct packet_config for more details.  */
1821
1822 static enum auto_boolean
1823 packet_set_cmd_state (int packet)
1824 {
1825   return remote_protocol_packets[packet].detect;
1826 }
1827
1828 /* Returns whether a given packet or feature is supported.  This takes
1829    into account the state of the corresponding "set remote foo-packet"
1830    command, which may be used to bypass auto-detection.  */
1831
1832 static enum packet_support
1833 packet_config_support (struct packet_config *config)
1834 {
1835   switch (config->detect)
1836     {
1837     case AUTO_BOOLEAN_TRUE:
1838       return PACKET_ENABLE;
1839     case AUTO_BOOLEAN_FALSE:
1840       return PACKET_DISABLE;
1841     case AUTO_BOOLEAN_AUTO:
1842       return config->support;
1843     default:
1844       gdb_assert_not_reached (_("bad switch"));
1845     }
1846 }
1847
1848 /* Same as packet_config_support, but takes the packet's enum value as
1849    argument.  */
1850
1851 static enum packet_support
1852 packet_support (int packet)
1853 {
1854   struct packet_config *config = &remote_protocol_packets[packet];
1855
1856   return packet_config_support (config);
1857 }
1858
1859 static void
1860 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1861                                  struct cmd_list_element *c,
1862                                  const char *value)
1863 {
1864   struct packet_config *packet;
1865
1866   for (packet = remote_protocol_packets;
1867        packet < &remote_protocol_packets[PACKET_MAX];
1868        packet++)
1869     {
1870       if (&packet->detect == c->var)
1871         {
1872           show_packet_config_cmd (packet);
1873           return;
1874         }
1875     }
1876   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1877                   c->name);
1878 }
1879
1880 /* Should we try one of the 'Z' requests?  */
1881
1882 enum Z_packet_type
1883 {
1884   Z_PACKET_SOFTWARE_BP,
1885   Z_PACKET_HARDWARE_BP,
1886   Z_PACKET_WRITE_WP,
1887   Z_PACKET_READ_WP,
1888   Z_PACKET_ACCESS_WP,
1889   NR_Z_PACKET_TYPES
1890 };
1891
1892 /* For compatibility with older distributions.  Provide a ``set remote
1893    Z-packet ...'' command that updates all the Z packet types.  */
1894
1895 static enum auto_boolean remote_Z_packet_detect;
1896
1897 static void
1898 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
1899                                   struct cmd_list_element *c)
1900 {
1901   int i;
1902
1903   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1904     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1905 }
1906
1907 static void
1908 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1909                                    struct cmd_list_element *c,
1910                                    const char *value)
1911 {
1912   int i;
1913
1914   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1915     {
1916       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1917     }
1918 }
1919
1920 /* Returns true if the multi-process extensions are in effect.  */
1921
1922 static int
1923 remote_multi_process_p (struct remote_state *rs)
1924 {
1925   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1926 }
1927
1928 /* Returns true if fork events are supported.  */
1929
1930 static int
1931 remote_fork_event_p (struct remote_state *rs)
1932 {
1933   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1934 }
1935
1936 /* Returns true if vfork events are supported.  */
1937
1938 static int
1939 remote_vfork_event_p (struct remote_state *rs)
1940 {
1941   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1942 }
1943
1944 /* Returns true if exec events are supported.  */
1945
1946 static int
1947 remote_exec_event_p (struct remote_state *rs)
1948 {
1949   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1950 }
1951
1952 /* Insert fork catchpoint target routine.  If fork events are enabled
1953    then return success, nothing more to do.  */
1954
1955 int
1956 remote_target::insert_fork_catchpoint (int pid)
1957 {
1958   struct remote_state *rs = get_remote_state ();
1959
1960   return !remote_fork_event_p (rs);
1961 }
1962
1963 /* Remove fork catchpoint target routine.  Nothing to do, just
1964    return success.  */
1965
1966 int
1967 remote_target::remove_fork_catchpoint (int pid)
1968 {
1969   return 0;
1970 }
1971
1972 /* Insert vfork catchpoint target routine.  If vfork events are enabled
1973    then return success, nothing more to do.  */
1974
1975 int
1976 remote_target::insert_vfork_catchpoint (int pid)
1977 {
1978   struct remote_state *rs = get_remote_state ();
1979
1980   return !remote_vfork_event_p (rs);
1981 }
1982
1983 /* Remove vfork catchpoint target routine.  Nothing to do, just
1984    return success.  */
1985
1986 int
1987 remote_target::remove_vfork_catchpoint (int pid)
1988 {
1989   return 0;
1990 }
1991
1992 /* Insert exec catchpoint target routine.  If exec events are
1993    enabled, just return success.  */
1994
1995 int
1996 remote_target::insert_exec_catchpoint (int pid)
1997 {
1998   struct remote_state *rs = get_remote_state ();
1999
2000   return !remote_exec_event_p (rs);
2001 }
2002
2003 /* Remove exec catchpoint target routine.  Nothing to do, just
2004    return success.  */
2005
2006 int
2007 remote_target::remove_exec_catchpoint (int pid)
2008 {
2009   return 0;
2010 }
2011
2012 \f
2013 /* Asynchronous signal handle registered as event loop source for
2014    when we have pending events ready to be passed to the core.  */
2015
2016 static struct async_event_handler *remote_async_inferior_event_token;
2017
2018 \f
2019
2020 static ptid_t magic_null_ptid;
2021 static ptid_t not_sent_ptid;
2022 static ptid_t any_thread_ptid;
2023
2024 /* Find out if the stub attached to PID (and hence GDB should offer to
2025    detach instead of killing it when bailing out).  */
2026
2027 static int
2028 remote_query_attached (int pid)
2029 {
2030   struct remote_state *rs = get_remote_state ();
2031   size_t size = get_remote_packet_size ();
2032
2033   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2034     return 0;
2035
2036   if (remote_multi_process_p (rs))
2037     xsnprintf (rs->buf, size, "qAttached:%x", pid);
2038   else
2039     xsnprintf (rs->buf, size, "qAttached");
2040
2041   putpkt (rs->buf);
2042   getpkt (&rs->buf, &rs->buf_size, 0);
2043
2044   switch (packet_ok (rs->buf,
2045                      &remote_protocol_packets[PACKET_qAttached]))
2046     {
2047     case PACKET_OK:
2048       if (strcmp (rs->buf, "1") == 0)
2049         return 1;
2050       break;
2051     case PACKET_ERROR:
2052       warning (_("Remote failure reply: %s"), rs->buf);
2053       break;
2054     case PACKET_UNKNOWN:
2055       break;
2056     }
2057
2058   return 0;
2059 }
2060
2061 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
2062    has been invented by GDB, instead of reported by the target.  Since
2063    we can be connected to a remote system before before knowing about
2064    any inferior, mark the target with execution when we find the first
2065    inferior.  If ATTACHED is 1, then we had just attached to this
2066    inferior.  If it is 0, then we just created this inferior.  If it
2067    is -1, then try querying the remote stub to find out if it had
2068    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
2069    attempt to open this inferior's executable as the main executable
2070    if no main executable is open already.  */
2071
2072 static struct inferior *
2073 remote_add_inferior (int fake_pid_p, int pid, int attached,
2074                      int try_open_exec)
2075 {
2076   struct inferior *inf;
2077
2078   /* Check whether this process we're learning about is to be
2079      considered attached, or if is to be considered to have been
2080      spawned by the stub.  */
2081   if (attached == -1)
2082     attached = remote_query_attached (pid);
2083
2084   if (gdbarch_has_global_solist (target_gdbarch ()))
2085     {
2086       /* If the target shares code across all inferiors, then every
2087          attach adds a new inferior.  */
2088       inf = add_inferior (pid);
2089
2090       /* ... and every inferior is bound to the same program space.
2091          However, each inferior may still have its own address
2092          space.  */
2093       inf->aspace = maybe_new_address_space ();
2094       inf->pspace = current_program_space;
2095     }
2096   else
2097     {
2098       /* In the traditional debugging scenario, there's a 1-1 match
2099          between program/address spaces.  We simply bind the inferior
2100          to the program space's address space.  */
2101       inf = current_inferior ();
2102       inferior_appeared (inf, pid);
2103     }
2104
2105   inf->attach_flag = attached;
2106   inf->fake_pid_p = fake_pid_p;
2107
2108   /* If no main executable is currently open then attempt to
2109      open the file that was executed to create this inferior.  */
2110   if (try_open_exec && get_exec_file (0) == NULL)
2111     exec_file_locate_attach (pid, 0, 1);
2112
2113   return inf;
2114 }
2115
2116 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2117
2118 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
2119    according to RUNNING.  */
2120
2121 static void
2122 remote_add_thread (ptid_t ptid, int running, int executing)
2123 {
2124   struct remote_state *rs = get_remote_state ();
2125   struct thread_info *thread;
2126
2127   /* GDB historically didn't pull threads in the initial connection
2128      setup.  If the remote target doesn't even have a concept of
2129      threads (e.g., a bare-metal target), even if internally we
2130      consider that a single-threaded target, mentioning a new thread
2131      might be confusing to the user.  Be silent then, preserving the
2132      age old behavior.  */
2133   if (rs->starting_up)
2134     thread = add_thread_silent (ptid);
2135   else
2136     thread = add_thread (ptid);
2137
2138   get_remote_thread_info (thread)->vcont_resumed = executing;
2139   set_executing (ptid, executing);
2140   set_running (ptid, running);
2141 }
2142
2143 /* Come here when we learn about a thread id from the remote target.
2144    It may be the first time we hear about such thread, so take the
2145    opportunity to add it to GDB's thread list.  In case this is the
2146    first time we're noticing its corresponding inferior, add it to
2147    GDB's inferior list as well.  EXECUTING indicates whether the
2148    thread is (internally) executing or stopped.  */
2149
2150 static void
2151 remote_notice_new_inferior (ptid_t currthread, int executing)
2152 {
2153   /* In non-stop mode, we assume new found threads are (externally)
2154      running until proven otherwise with a stop reply.  In all-stop,
2155      we can only get here if all threads are stopped.  */
2156   int running = target_is_non_stop_p () ? 1 : 0;
2157
2158   /* If this is a new thread, add it to GDB's thread list.
2159      If we leave it up to WFI to do this, bad things will happen.  */
2160
2161   if (in_thread_list (currthread) && is_exited (currthread))
2162     {
2163       /* We're seeing an event on a thread id we knew had exited.
2164          This has to be a new thread reusing the old id.  Add it.  */
2165       remote_add_thread (currthread, running, executing);
2166       return;
2167     }
2168
2169   if (!in_thread_list (currthread))
2170     {
2171       struct inferior *inf = NULL;
2172       int pid = ptid_get_pid (currthread);
2173
2174       if (ptid_is_pid (inferior_ptid)
2175           && pid == ptid_get_pid (inferior_ptid))
2176         {
2177           /* inferior_ptid has no thread member yet.  This can happen
2178              with the vAttach -> remote_wait,"TAAthread:" path if the
2179              stub doesn't support qC.  This is the first stop reported
2180              after an attach, so this is the main thread.  Update the
2181              ptid in the thread list.  */
2182           if (in_thread_list (pid_to_ptid (pid)))
2183             thread_change_ptid (inferior_ptid, currthread);
2184           else
2185             {
2186               remote_add_thread (currthread, running, executing);
2187               inferior_ptid = currthread;
2188             }
2189           return;
2190         }
2191
2192       if (ptid_equal (magic_null_ptid, inferior_ptid))
2193         {
2194           /* inferior_ptid is not set yet.  This can happen with the
2195              vRun -> remote_wait,"TAAthread:" path if the stub
2196              doesn't support qC.  This is the first stop reported
2197              after an attach, so this is the main thread.  Update the
2198              ptid in the thread list.  */
2199           thread_change_ptid (inferior_ptid, currthread);
2200           return;
2201         }
2202
2203       /* When connecting to a target remote, or to a target
2204          extended-remote which already was debugging an inferior, we
2205          may not know about it yet.  Add it before adding its child
2206          thread, so notifications are emitted in a sensible order.  */
2207       if (!in_inferior_list (ptid_get_pid (currthread)))
2208         {
2209           struct remote_state *rs = get_remote_state ();
2210           int fake_pid_p = !remote_multi_process_p (rs);
2211
2212           inf = remote_add_inferior (fake_pid_p,
2213                                      ptid_get_pid (currthread), -1, 1);
2214         }
2215
2216       /* This is really a new thread.  Add it.  */
2217       remote_add_thread (currthread, running, executing);
2218
2219       /* If we found a new inferior, let the common code do whatever
2220          it needs to with it (e.g., read shared libraries, insert
2221          breakpoints), unless we're just setting up an all-stop
2222          connection.  */
2223       if (inf != NULL)
2224         {
2225           struct remote_state *rs = get_remote_state ();
2226
2227           if (!rs->starting_up)
2228             notice_new_inferior (currthread, executing, 0);
2229         }
2230     }
2231 }
2232
2233 /* Return THREAD's private thread data, creating it if necessary.  */
2234
2235 static remote_thread_info *
2236 get_remote_thread_info (thread_info *thread)
2237 {
2238   gdb_assert (thread != NULL);
2239
2240   if (thread->priv == NULL)
2241     thread->priv.reset (new remote_thread_info);
2242
2243   return static_cast<remote_thread_info *> (thread->priv.get ());
2244 }
2245
2246 /* Return PTID's private thread data, creating it if necessary.  */
2247
2248 static remote_thread_info *
2249 get_remote_thread_info (ptid_t ptid)
2250 {
2251   struct thread_info *info = find_thread_ptid (ptid);
2252
2253   return get_remote_thread_info (info);
2254 }
2255
2256 /* Call this function as a result of
2257    1) A halt indication (T packet) containing a thread id
2258    2) A direct query of currthread
2259    3) Successful execution of set thread */
2260
2261 static void
2262 record_currthread (struct remote_state *rs, ptid_t currthread)
2263 {
2264   rs->general_thread = currthread;
2265 }
2266
2267 /* If 'QPassSignals' is supported, tell the remote stub what signals
2268    it can simply pass through to the inferior without reporting.  */
2269
2270 void
2271 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2272 {
2273   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2274     {
2275       char *pass_packet, *p;
2276       int count = 0, i;
2277       struct remote_state *rs = get_remote_state ();
2278
2279       gdb_assert (numsigs < 256);
2280       for (i = 0; i < numsigs; i++)
2281         {
2282           if (pass_signals[i])
2283             count++;
2284         }
2285       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2286       strcpy (pass_packet, "QPassSignals:");
2287       p = pass_packet + strlen (pass_packet);
2288       for (i = 0; i < numsigs; i++)
2289         {
2290           if (pass_signals[i])
2291             {
2292               if (i >= 16)
2293                 *p++ = tohex (i >> 4);
2294               *p++ = tohex (i & 15);
2295               if (count)
2296                 *p++ = ';';
2297               else
2298                 break;
2299               count--;
2300             }
2301         }
2302       *p = 0;
2303       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2304         {
2305           putpkt (pass_packet);
2306           getpkt (&rs->buf, &rs->buf_size, 0);
2307           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2308           if (rs->last_pass_packet)
2309             xfree (rs->last_pass_packet);
2310           rs->last_pass_packet = pass_packet;
2311         }
2312       else
2313         xfree (pass_packet);
2314     }
2315 }
2316
2317 /* If 'QCatchSyscalls' is supported, tell the remote stub
2318    to report syscalls to GDB.  */
2319
2320 int
2321 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2322                                        gdb::array_view<const int> syscall_counts)
2323 {
2324   const char *catch_packet;
2325   enum packet_result result;
2326   int n_sysno = 0;
2327
2328   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2329     {
2330       /* Not supported.  */
2331       return 1;
2332     }
2333
2334   if (needed && any_count == 0)
2335     {
2336       /* Count how many syscalls are to be caught.  */
2337       for (size_t i = 0; i < syscall_counts.size (); i++)
2338         {
2339           if (syscall_counts[i] != 0)
2340             n_sysno++;
2341         }
2342     }
2343
2344   if (remote_debug)
2345     {
2346       fprintf_unfiltered (gdb_stdlog,
2347                           "remote_set_syscall_catchpoint "
2348                           "pid %d needed %d any_count %d n_sysno %d\n",
2349                           pid, needed, any_count, n_sysno);
2350     }
2351
2352   std::string built_packet;
2353   if (needed)
2354     {
2355       /* Prepare a packet with the sysno list, assuming max 8+1
2356          characters for a sysno.  If the resulting packet size is too
2357          big, fallback on the non-selective packet.  */
2358       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2359       built_packet.reserve (maxpktsz);
2360       built_packet = "QCatchSyscalls:1";
2361       if (any_count == 0)
2362         {
2363           /* Add in each syscall to be caught.  */
2364           for (size_t i = 0; i < syscall_counts.size (); i++)
2365             {
2366               if (syscall_counts[i] != 0)
2367                 string_appendf (built_packet, ";%zx", i);
2368             }
2369         }
2370       if (built_packet.size () > get_remote_packet_size ())
2371         {
2372           /* catch_packet too big.  Fallback to less efficient
2373              non selective mode, with GDB doing the filtering.  */
2374           catch_packet = "QCatchSyscalls:1";
2375         }
2376       else
2377         catch_packet = built_packet.c_str ();
2378     }
2379   else
2380     catch_packet = "QCatchSyscalls:0";
2381
2382   struct remote_state *rs = get_remote_state ();
2383
2384   putpkt (catch_packet);
2385   getpkt (&rs->buf, &rs->buf_size, 0);
2386   result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2387   if (result == PACKET_OK)
2388     return 0;
2389   else
2390     return -1;
2391 }
2392
2393 /* If 'QProgramSignals' is supported, tell the remote stub what
2394    signals it should pass through to the inferior when detaching.  */
2395
2396 void
2397 remote_target::program_signals (int numsigs, unsigned char *signals)
2398 {
2399   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2400     {
2401       char *packet, *p;
2402       int count = 0, i;
2403       struct remote_state *rs = get_remote_state ();
2404
2405       gdb_assert (numsigs < 256);
2406       for (i = 0; i < numsigs; i++)
2407         {
2408           if (signals[i])
2409             count++;
2410         }
2411       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2412       strcpy (packet, "QProgramSignals:");
2413       p = packet + strlen (packet);
2414       for (i = 0; i < numsigs; i++)
2415         {
2416           if (signal_pass_state (i))
2417             {
2418               if (i >= 16)
2419                 *p++ = tohex (i >> 4);
2420               *p++ = tohex (i & 15);
2421               if (count)
2422                 *p++ = ';';
2423               else
2424                 break;
2425               count--;
2426             }
2427         }
2428       *p = 0;
2429       if (!rs->last_program_signals_packet
2430           || strcmp (rs->last_program_signals_packet, packet) != 0)
2431         {
2432           putpkt (packet);
2433           getpkt (&rs->buf, &rs->buf_size, 0);
2434           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2435           xfree (rs->last_program_signals_packet);
2436           rs->last_program_signals_packet = packet;
2437         }
2438       else
2439         xfree (packet);
2440     }
2441 }
2442
2443 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2444    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2445    thread.  If GEN is set, set the general thread, if not, then set
2446    the step/continue thread.  */
2447 static void
2448 set_thread (ptid_t ptid, int gen)
2449 {
2450   struct remote_state *rs = get_remote_state ();
2451   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2452   char *buf = rs->buf;
2453   char *endbuf = rs->buf + get_remote_packet_size ();
2454
2455   if (ptid_equal (state, ptid))
2456     return;
2457
2458   *buf++ = 'H';
2459   *buf++ = gen ? 'g' : 'c';
2460   if (ptid_equal (ptid, magic_null_ptid))
2461     xsnprintf (buf, endbuf - buf, "0");
2462   else if (ptid_equal (ptid, any_thread_ptid))
2463     xsnprintf (buf, endbuf - buf, "0");
2464   else if (ptid_equal (ptid, minus_one_ptid))
2465     xsnprintf (buf, endbuf - buf, "-1");
2466   else
2467     write_ptid (buf, endbuf, ptid);
2468   putpkt (rs->buf);
2469   getpkt (&rs->buf, &rs->buf_size, 0);
2470   if (gen)
2471     rs->general_thread = ptid;
2472   else
2473     rs->continue_thread = ptid;
2474 }
2475
2476 static void
2477 set_general_thread (ptid_t ptid)
2478 {
2479   set_thread (ptid, 1);
2480 }
2481
2482 static void
2483 set_continue_thread (ptid_t ptid)
2484 {
2485   set_thread (ptid, 0);
2486 }
2487
2488 /* Change the remote current process.  Which thread within the process
2489    ends up selected isn't important, as long as it is the same process
2490    as what INFERIOR_PTID points to.
2491
2492    This comes from that fact that there is no explicit notion of
2493    "selected process" in the protocol.  The selected process for
2494    general operations is the process the selected general thread
2495    belongs to.  */
2496
2497 static void
2498 set_general_process (void)
2499 {
2500   struct remote_state *rs = get_remote_state ();
2501
2502   /* If the remote can't handle multiple processes, don't bother.  */
2503   if (!remote_multi_process_p (rs))
2504     return;
2505
2506   /* We only need to change the remote current thread if it's pointing
2507      at some other process.  */
2508   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2509     set_general_thread (inferior_ptid);
2510 }
2511
2512 \f
2513 /* Return nonzero if this is the main thread that we made up ourselves
2514    to model non-threaded targets as single-threaded.  */
2515
2516 static int
2517 remote_thread_always_alive (ptid_t ptid)
2518 {
2519   if (ptid_equal (ptid, magic_null_ptid))
2520     /* The main thread is always alive.  */
2521     return 1;
2522
2523   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2524     /* The main thread is always alive.  This can happen after a
2525        vAttach, if the remote side doesn't support
2526        multi-threading.  */
2527     return 1;
2528
2529   return 0;
2530 }
2531
2532 /* Return nonzero if the thread PTID is still alive on the remote
2533    system.  */
2534
2535 bool
2536 remote_target::thread_alive (ptid_t ptid)
2537 {
2538   struct remote_state *rs = get_remote_state ();
2539   char *p, *endp;
2540
2541   /* Check if this is a thread that we made up ourselves to model
2542      non-threaded targets as single-threaded.  */
2543   if (remote_thread_always_alive (ptid))
2544     return 1;
2545
2546   p = rs->buf;
2547   endp = rs->buf + get_remote_packet_size ();
2548
2549   *p++ = 'T';
2550   write_ptid (p, endp, ptid);
2551
2552   putpkt (rs->buf);
2553   getpkt (&rs->buf, &rs->buf_size, 0);
2554   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2555 }
2556
2557 /* Return a pointer to a thread name if we know it and NULL otherwise.
2558    The thread_info object owns the memory for the name.  */
2559
2560 const char *
2561 remote_target::thread_name (struct thread_info *info)
2562 {
2563   if (info->priv != NULL)
2564     {
2565       const std::string &name = get_remote_thread_info (info)->name;
2566       return !name.empty () ? name.c_str () : NULL;
2567     }
2568
2569   return NULL;
2570 }
2571
2572 /* About these extended threadlist and threadinfo packets.  They are
2573    variable length packets but, the fields within them are often fixed
2574    length.  They are redundent enough to send over UDP as is the
2575    remote protocol in general.  There is a matching unit test module
2576    in libstub.  */
2577
2578 /* WARNING: This threadref data structure comes from the remote O.S.,
2579    libstub protocol encoding, and remote.c.  It is not particularly
2580    changable.  */
2581
2582 /* Right now, the internal structure is int. We want it to be bigger.
2583    Plan to fix this.  */
2584
2585 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2586
2587 /* gdb_ext_thread_info is an internal GDB data structure which is
2588    equivalent to the reply of the remote threadinfo packet.  */
2589
2590 struct gdb_ext_thread_info
2591   {
2592     threadref threadid;         /* External form of thread reference.  */
2593     int active;                 /* Has state interesting to GDB?
2594                                    regs, stack.  */
2595     char display[256];          /* Brief state display, name,
2596                                    blocked/suspended.  */
2597     char shortname[32];         /* To be used to name threads.  */
2598     char more_display[256];     /* Long info, statistics, queue depth,
2599                                    whatever.  */
2600   };
2601
2602 /* The volume of remote transfers can be limited by submitting
2603    a mask containing bits specifying the desired information.
2604    Use a union of these values as the 'selection' parameter to
2605    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2606
2607 #define TAG_THREADID 1
2608 #define TAG_EXISTS 2
2609 #define TAG_DISPLAY 4
2610 #define TAG_THREADNAME 8
2611 #define TAG_MOREDISPLAY 16
2612
2613 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2614
2615 static char *unpack_nibble (char *buf, int *val);
2616
2617 static char *unpack_byte (char *buf, int *value);
2618
2619 static char *pack_int (char *buf, int value);
2620
2621 static char *unpack_int (char *buf, int *value);
2622
2623 static char *unpack_string (char *src, char *dest, int length);
2624
2625 static char *pack_threadid (char *pkt, threadref *id);
2626
2627 static char *unpack_threadid (char *inbuf, threadref *id);
2628
2629 void int_to_threadref (threadref *id, int value);
2630
2631 static int threadref_to_int (threadref *ref);
2632
2633 static void copy_threadref (threadref *dest, threadref *src);
2634
2635 static int threadmatch (threadref *dest, threadref *src);
2636
2637 static char *pack_threadinfo_request (char *pkt, int mode,
2638                                       threadref *id);
2639
2640 static int remote_unpack_thread_info_response (char *pkt,
2641                                                threadref *expectedref,
2642                                                struct gdb_ext_thread_info
2643                                                *info);
2644
2645
2646 static int remote_get_threadinfo (threadref *threadid,
2647                                   int fieldset, /*TAG mask */
2648                                   struct gdb_ext_thread_info *info);
2649
2650 static char *pack_threadlist_request (char *pkt, int startflag,
2651                                       int threadcount,
2652                                       threadref *nextthread);
2653
2654 static int parse_threadlist_response (char *pkt,
2655                                       int result_limit,
2656                                       threadref *original_echo,
2657                                       threadref *resultlist,
2658                                       int *doneflag);
2659
2660 static int remote_get_threadlist (int startflag,
2661                                   threadref *nextthread,
2662                                   int result_limit,
2663                                   int *done,
2664                                   int *result_count,
2665                                   threadref *threadlist);
2666
2667 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2668
2669 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2670                                        void *context, int looplimit);
2671
2672 static int remote_newthread_step (threadref *ref, void *context);
2673
2674
2675 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2676    buffer we're allowed to write to.  Returns
2677    BUF+CHARACTERS_WRITTEN.  */
2678
2679 static char *
2680 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2681 {
2682   int pid, tid;
2683   struct remote_state *rs = get_remote_state ();
2684
2685   if (remote_multi_process_p (rs))
2686     {
2687       pid = ptid_get_pid (ptid);
2688       if (pid < 0)
2689         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2690       else
2691         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2692     }
2693   tid = ptid_get_lwp (ptid);
2694   if (tid < 0)
2695     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2696   else
2697     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2698
2699   return buf;
2700 }
2701
2702 /* Extract a PTID from BUF.  If non-null, OBUF is set to one past the
2703    last parsed char.  Returns null_ptid if no thread id is found, and
2704    throws an error if the thread id has an invalid format.  */
2705
2706 static ptid_t
2707 read_ptid (const char *buf, const char **obuf)
2708 {
2709   const char *p = buf;
2710   const char *pp;
2711   ULONGEST pid = 0, tid = 0;
2712
2713   if (*p == 'p')
2714     {
2715       /* Multi-process ptid.  */
2716       pp = unpack_varlen_hex (p + 1, &pid);
2717       if (*pp != '.')
2718         error (_("invalid remote ptid: %s"), p);
2719
2720       p = pp;
2721       pp = unpack_varlen_hex (p + 1, &tid);
2722       if (obuf)
2723         *obuf = pp;
2724       return ptid_build (pid, tid, 0);
2725     }
2726
2727   /* No multi-process.  Just a tid.  */
2728   pp = unpack_varlen_hex (p, &tid);
2729
2730   /* Return null_ptid when no thread id is found.  */
2731   if (p == pp)
2732     {
2733       if (obuf)
2734         *obuf = pp;
2735       return null_ptid;
2736     }
2737
2738   /* Since the stub is not sending a process id, then default to
2739      what's in inferior_ptid, unless it's null at this point.  If so,
2740      then since there's no way to know the pid of the reported
2741      threads, use the magic number.  */
2742   if (ptid_equal (inferior_ptid, null_ptid))
2743     pid = ptid_get_pid (magic_null_ptid);
2744   else
2745     pid = ptid_get_pid (inferior_ptid);
2746
2747   if (obuf)
2748     *obuf = pp;
2749   return ptid_build (pid, tid, 0);
2750 }
2751
2752 static int
2753 stubhex (int ch)
2754 {
2755   if (ch >= 'a' && ch <= 'f')
2756     return ch - 'a' + 10;
2757   if (ch >= '0' && ch <= '9')
2758     return ch - '0';
2759   if (ch >= 'A' && ch <= 'F')
2760     return ch - 'A' + 10;
2761   return -1;
2762 }
2763
2764 static int
2765 stub_unpack_int (char *buff, int fieldlength)
2766 {
2767   int nibble;
2768   int retval = 0;
2769
2770   while (fieldlength)
2771     {
2772       nibble = stubhex (*buff++);
2773       retval |= nibble;
2774       fieldlength--;
2775       if (fieldlength)
2776         retval = retval << 4;
2777     }
2778   return retval;
2779 }
2780
2781 static char *
2782 unpack_nibble (char *buf, int *val)
2783 {
2784   *val = fromhex (*buf++);
2785   return buf;
2786 }
2787
2788 static char *
2789 unpack_byte (char *buf, int *value)
2790 {
2791   *value = stub_unpack_int (buf, 2);
2792   return buf + 2;
2793 }
2794
2795 static char *
2796 pack_int (char *buf, int value)
2797 {
2798   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2799   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2800   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2801   buf = pack_hex_byte (buf, (value & 0xff));
2802   return buf;
2803 }
2804
2805 static char *
2806 unpack_int (char *buf, int *value)
2807 {
2808   *value = stub_unpack_int (buf, 8);
2809   return buf + 8;
2810 }
2811
2812 #if 0                   /* Currently unused, uncomment when needed.  */
2813 static char *pack_string (char *pkt, char *string);
2814
2815 static char *
2816 pack_string (char *pkt, char *string)
2817 {
2818   char ch;
2819   int len;
2820
2821   len = strlen (string);
2822   if (len > 200)
2823     len = 200;          /* Bigger than most GDB packets, junk???  */
2824   pkt = pack_hex_byte (pkt, len);
2825   while (len-- > 0)
2826     {
2827       ch = *string++;
2828       if ((ch == '\0') || (ch == '#'))
2829         ch = '*';               /* Protect encapsulation.  */
2830       *pkt++ = ch;
2831     }
2832   return pkt;
2833 }
2834 #endif /* 0 (unused) */
2835
2836 static char *
2837 unpack_string (char *src, char *dest, int length)
2838 {
2839   while (length--)
2840     *dest++ = *src++;
2841   *dest = '\0';
2842   return src;
2843 }
2844
2845 static char *
2846 pack_threadid (char *pkt, threadref *id)
2847 {
2848   char *limit;
2849   unsigned char *altid;
2850
2851   altid = (unsigned char *) id;
2852   limit = pkt + BUF_THREAD_ID_SIZE;
2853   while (pkt < limit)
2854     pkt = pack_hex_byte (pkt, *altid++);
2855   return pkt;
2856 }
2857
2858
2859 static char *
2860 unpack_threadid (char *inbuf, threadref *id)
2861 {
2862   char *altref;
2863   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2864   int x, y;
2865
2866   altref = (char *) id;
2867
2868   while (inbuf < limit)
2869     {
2870       x = stubhex (*inbuf++);
2871       y = stubhex (*inbuf++);
2872       *altref++ = (x << 4) | y;
2873     }
2874   return inbuf;
2875 }
2876
2877 /* Externally, threadrefs are 64 bits but internally, they are still
2878    ints.  This is due to a mismatch of specifications.  We would like
2879    to use 64bit thread references internally.  This is an adapter
2880    function.  */
2881
2882 void
2883 int_to_threadref (threadref *id, int value)
2884 {
2885   unsigned char *scan;
2886
2887   scan = (unsigned char *) id;
2888   {
2889     int i = 4;
2890     while (i--)
2891       *scan++ = 0;
2892   }
2893   *scan++ = (value >> 24) & 0xff;
2894   *scan++ = (value >> 16) & 0xff;
2895   *scan++ = (value >> 8) & 0xff;
2896   *scan++ = (value & 0xff);
2897 }
2898
2899 static int
2900 threadref_to_int (threadref *ref)
2901 {
2902   int i, value = 0;
2903   unsigned char *scan;
2904
2905   scan = *ref;
2906   scan += 4;
2907   i = 4;
2908   while (i-- > 0)
2909     value = (value << 8) | ((*scan++) & 0xff);
2910   return value;
2911 }
2912
2913 static void
2914 copy_threadref (threadref *dest, threadref *src)
2915 {
2916   int i;
2917   unsigned char *csrc, *cdest;
2918
2919   csrc = (unsigned char *) src;
2920   cdest = (unsigned char *) dest;
2921   i = 8;
2922   while (i--)
2923     *cdest++ = *csrc++;
2924 }
2925
2926 static int
2927 threadmatch (threadref *dest, threadref *src)
2928 {
2929   /* Things are broken right now, so just assume we got a match.  */
2930 #if 0
2931   unsigned char *srcp, *destp;
2932   int i, result;
2933   srcp = (char *) src;
2934   destp = (char *) dest;
2935
2936   result = 1;
2937   while (i-- > 0)
2938     result &= (*srcp++ == *destp++) ? 1 : 0;
2939   return result;
2940 #endif
2941   return 1;
2942 }
2943
2944 /*
2945    threadid:1,        # always request threadid
2946    context_exists:2,
2947    display:4,
2948    unique_name:8,
2949    more_display:16
2950  */
2951
2952 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2953
2954 static char *
2955 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2956 {
2957   *pkt++ = 'q';                         /* Info Query */
2958   *pkt++ = 'P';                         /* process or thread info */
2959   pkt = pack_int (pkt, mode);           /* mode */
2960   pkt = pack_threadid (pkt, id);        /* threadid */
2961   *pkt = '\0';                          /* terminate */
2962   return pkt;
2963 }
2964
2965 /* These values tag the fields in a thread info response packet.  */
2966 /* Tagging the fields allows us to request specific fields and to
2967    add more fields as time goes by.  */
2968
2969 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2970 #define TAG_EXISTS 2            /* Is this process defined enough to
2971                                    fetch registers and its stack?  */
2972 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2973 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2974 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2975                                    the process.  */
2976
2977 static int
2978 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2979                                     struct gdb_ext_thread_info *info)
2980 {
2981   struct remote_state *rs = get_remote_state ();
2982   int mask, length;
2983   int tag;
2984   threadref ref;
2985   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2986   int retval = 1;
2987
2988   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2989   info->active = 0;
2990   info->display[0] = '\0';
2991   info->shortname[0] = '\0';
2992   info->more_display[0] = '\0';
2993
2994   /* Assume the characters indicating the packet type have been
2995      stripped.  */
2996   pkt = unpack_int (pkt, &mask);        /* arg mask */
2997   pkt = unpack_threadid (pkt, &ref);
2998
2999   if (mask == 0)
3000     warning (_("Incomplete response to threadinfo request."));
3001   if (!threadmatch (&ref, expectedref))
3002     {                   /* This is an answer to a different request.  */
3003       warning (_("ERROR RMT Thread info mismatch."));
3004       return 0;
3005     }
3006   copy_threadref (&info->threadid, &ref);
3007
3008   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
3009
3010   /* Packets are terminated with nulls.  */
3011   while ((pkt < limit) && mask && *pkt)
3012     {
3013       pkt = unpack_int (pkt, &tag);     /* tag */
3014       pkt = unpack_byte (pkt, &length); /* length */
3015       if (!(tag & mask))                /* Tags out of synch with mask.  */
3016         {
3017           warning (_("ERROR RMT: threadinfo tag mismatch."));
3018           retval = 0;
3019           break;
3020         }
3021       if (tag == TAG_THREADID)
3022         {
3023           if (length != 16)
3024             {
3025               warning (_("ERROR RMT: length of threadid is not 16."));
3026               retval = 0;
3027               break;
3028             }
3029           pkt = unpack_threadid (pkt, &ref);
3030           mask = mask & ~TAG_THREADID;
3031           continue;
3032         }
3033       if (tag == TAG_EXISTS)
3034         {
3035           info->active = stub_unpack_int (pkt, length);
3036           pkt += length;
3037           mask = mask & ~(TAG_EXISTS);
3038           if (length > 8)
3039             {
3040               warning (_("ERROR RMT: 'exists' length too long."));
3041               retval = 0;
3042               break;
3043             }
3044           continue;
3045         }
3046       if (tag == TAG_THREADNAME)
3047         {
3048           pkt = unpack_string (pkt, &info->shortname[0], length);
3049           mask = mask & ~TAG_THREADNAME;
3050           continue;
3051         }
3052       if (tag == TAG_DISPLAY)
3053         {
3054           pkt = unpack_string (pkt, &info->display[0], length);
3055           mask = mask & ~TAG_DISPLAY;
3056           continue;
3057         }
3058       if (tag == TAG_MOREDISPLAY)
3059         {
3060           pkt = unpack_string (pkt, &info->more_display[0], length);
3061           mask = mask & ~TAG_MOREDISPLAY;
3062           continue;
3063         }
3064       warning (_("ERROR RMT: unknown thread info tag."));
3065       break;                    /* Not a tag we know about.  */
3066     }
3067   return retval;
3068 }
3069
3070 static int
3071 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
3072                        struct gdb_ext_thread_info *info)
3073 {
3074   struct remote_state *rs = get_remote_state ();
3075   int result;
3076
3077   pack_threadinfo_request (rs->buf, fieldset, threadid);
3078   putpkt (rs->buf);
3079   getpkt (&rs->buf, &rs->buf_size, 0);
3080
3081   if (rs->buf[0] == '\0')
3082     return 0;
3083
3084   result = remote_unpack_thread_info_response (rs->buf + 2,
3085                                                threadid, info);
3086   return result;
3087 }
3088
3089 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
3090
3091 static char *
3092 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3093                          threadref *nextthread)
3094 {
3095   *pkt++ = 'q';                 /* info query packet */
3096   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
3097   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
3098   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
3099   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
3100   *pkt = '\0';
3101   return pkt;
3102 }
3103
3104 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3105
3106 static int
3107 parse_threadlist_response (char *pkt, int result_limit,
3108                            threadref *original_echo, threadref *resultlist,
3109                            int *doneflag)
3110 {
3111   struct remote_state *rs = get_remote_state ();
3112   char *limit;
3113   int count, resultcount, done;
3114
3115   resultcount = 0;
3116   /* Assume the 'q' and 'M chars have been stripped.  */
3117   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3118   /* done parse past here */
3119   pkt = unpack_byte (pkt, &count);      /* count field */
3120   pkt = unpack_nibble (pkt, &done);
3121   /* The first threadid is the argument threadid.  */
3122   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
3123   while ((count-- > 0) && (pkt < limit))
3124     {
3125       pkt = unpack_threadid (pkt, resultlist++);
3126       if (resultcount++ >= result_limit)
3127         break;
3128     }
3129   if (doneflag)
3130     *doneflag = done;
3131   return resultcount;
3132 }
3133
3134 /* Fetch the next batch of threads from the remote.  Returns -1 if the
3135    qL packet is not supported, 0 on error and 1 on success.  */
3136
3137 static int
3138 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
3139                        int *done, int *result_count, threadref *threadlist)
3140 {
3141   struct remote_state *rs = get_remote_state ();
3142   int result = 1;
3143
3144   /* Trancate result limit to be smaller than the packet size.  */
3145   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3146       >= get_remote_packet_size ())
3147     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3148
3149   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3150   putpkt (rs->buf);
3151   getpkt (&rs->buf, &rs->buf_size, 0);
3152   if (*rs->buf == '\0')
3153     {
3154       /* Packet not supported.  */
3155       return -1;
3156     }
3157
3158   *result_count =
3159     parse_threadlist_response (rs->buf + 2, result_limit,
3160                                &rs->echo_nextthread, threadlist, done);
3161
3162   if (!threadmatch (&rs->echo_nextthread, nextthread))
3163     {
3164       /* FIXME: This is a good reason to drop the packet.  */
3165       /* Possably, there is a duplicate response.  */
3166       /* Possabilities :
3167          retransmit immediatly - race conditions
3168          retransmit after timeout - yes
3169          exit
3170          wait for packet, then exit
3171        */
3172       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3173       return 0;                 /* I choose simply exiting.  */
3174     }
3175   if (*result_count <= 0)
3176     {
3177       if (*done != 1)
3178         {
3179           warning (_("RMT ERROR : failed to get remote thread list."));
3180           result = 0;
3181         }
3182       return result;            /* break; */
3183     }
3184   if (*result_count > result_limit)
3185     {
3186       *result_count = 0;
3187       warning (_("RMT ERROR: threadlist response longer than requested."));
3188       return 0;
3189     }
3190   return result;
3191 }
3192
3193 /* Fetch the list of remote threads, with the qL packet, and call
3194    STEPFUNCTION for each thread found.  Stops iterating and returns 1
3195    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
3196    STEPFUNCTION returns false.  If the packet is not supported,
3197    returns -1.  */
3198
3199 static int
3200 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
3201                             int looplimit)
3202 {
3203   struct remote_state *rs = get_remote_state ();
3204   int done, i, result_count;
3205   int startflag = 1;
3206   int result = 1;
3207   int loopcount = 0;
3208
3209   done = 0;
3210   while (!done)
3211     {
3212       if (loopcount++ > looplimit)
3213         {
3214           result = 0;
3215           warning (_("Remote fetch threadlist -infinite loop-."));
3216           break;
3217         }
3218       result = remote_get_threadlist (startflag, &rs->nextthread,
3219                                       MAXTHREADLISTRESULTS,
3220                                       &done, &result_count,
3221                                       rs->resultthreadlist);
3222       if (result <= 0)
3223         break;
3224       /* Clear for later iterations.  */
3225       startflag = 0;
3226       /* Setup to resume next batch of thread references, set nextthread.  */
3227       if (result_count >= 1)
3228         copy_threadref (&rs->nextthread,
3229                         &rs->resultthreadlist[result_count - 1]);
3230       i = 0;
3231       while (result_count--)
3232         {
3233           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3234             {
3235               result = 0;
3236               break;
3237             }
3238         }
3239     }
3240   return result;
3241 }
3242
3243 /* A thread found on the remote target.  */
3244
3245 struct thread_item
3246 {
3247   explicit thread_item (ptid_t ptid_)
3248   : ptid (ptid_)
3249   {}
3250
3251   thread_item (thread_item &&other) = default;
3252   thread_item &operator= (thread_item &&other) = default;
3253
3254   DISABLE_COPY_AND_ASSIGN (thread_item);
3255
3256   /* The thread's PTID.  */
3257   ptid_t ptid;
3258
3259   /* The thread's extra info.  */
3260   std::string extra;
3261
3262   /* The thread's name.  */
3263   std::string name;
3264
3265   /* The core the thread was running on.  -1 if not known.  */
3266   int core = -1;
3267
3268   /* The thread handle associated with the thread.  */
3269   gdb::byte_vector thread_handle;
3270 };
3271
3272 /* Context passed around to the various methods listing remote
3273    threads.  As new threads are found, they're added to the ITEMS
3274    vector.  */
3275
3276 struct threads_listing_context
3277 {
3278   /* Return true if this object contains an entry for a thread with ptid
3279      PTID.  */
3280
3281   bool contains_thread (ptid_t ptid) const
3282   {
3283     auto match_ptid = [&] (const thread_item &item)
3284       {
3285         return item.ptid == ptid;
3286       };
3287
3288     auto it = std::find_if (this->items.begin (),
3289                             this->items.end (),
3290                             match_ptid);
3291
3292     return it != this->items.end ();
3293   }
3294
3295   /* Remove the thread with ptid PTID.  */
3296
3297   void remove_thread (ptid_t ptid)
3298   {
3299     auto match_ptid = [&] (const thread_item &item)
3300       {
3301         return item.ptid == ptid;
3302       };
3303
3304     auto it = std::remove_if (this->items.begin (),
3305                               this->items.end (),
3306                               match_ptid);
3307
3308     if (it != this->items.end ())
3309       this->items.erase (it);
3310   }
3311
3312   /* The threads found on the remote target.  */
3313   std::vector<thread_item> items;
3314 };
3315
3316 static int
3317 remote_newthread_step (threadref *ref, void *data)
3318 {
3319   struct threads_listing_context *context
3320     = (struct threads_listing_context *) data;
3321   int pid = inferior_ptid.pid ();
3322   int lwp = threadref_to_int (ref);
3323   ptid_t ptid (pid, lwp);
3324
3325   context->items.emplace_back (ptid);
3326
3327   return 1;                     /* continue iterator */
3328 }
3329
3330 #define CRAZY_MAX_THREADS 1000
3331
3332 static ptid_t
3333 remote_current_thread (ptid_t oldpid)
3334 {
3335   struct remote_state *rs = get_remote_state ();
3336
3337   putpkt ("qC");
3338   getpkt (&rs->buf, &rs->buf_size, 0);
3339   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3340     {
3341       const char *obuf;
3342       ptid_t result;
3343
3344       result = read_ptid (&rs->buf[2], &obuf);
3345       if (*obuf != '\0' && remote_debug)
3346         fprintf_unfiltered (gdb_stdlog,
3347                             "warning: garbage in qC reply\n");
3348
3349       return result;
3350     }
3351   else
3352     return oldpid;
3353 }
3354
3355 /* List remote threads using the deprecated qL packet.  */
3356
3357 static int
3358 remote_get_threads_with_ql (struct target_ops *ops,
3359                             struct threads_listing_context *context)
3360 {
3361   if (remote_threadlist_iterator (remote_newthread_step, context,
3362                                   CRAZY_MAX_THREADS) >= 0)
3363     return 1;
3364
3365   return 0;
3366 }
3367
3368 #if defined(HAVE_LIBEXPAT)
3369
3370 static void
3371 start_thread (struct gdb_xml_parser *parser,
3372               const struct gdb_xml_element *element,
3373               void *user_data,
3374               std::vector<gdb_xml_value> &attributes)
3375 {
3376   struct threads_listing_context *data
3377     = (struct threads_listing_context *) user_data;
3378   struct gdb_xml_value *attr;
3379
3380   char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3381   ptid_t ptid = read_ptid (id, NULL);
3382
3383   data->items.emplace_back (ptid);
3384   thread_item &item = data->items.back ();
3385
3386   attr = xml_find_attribute (attributes, "core");
3387   if (attr != NULL)
3388     item.core = *(ULONGEST *) attr->value.get ();
3389
3390   attr = xml_find_attribute (attributes, "name");
3391   if (attr != NULL)
3392     item.name = (const char *) attr->value.get ();
3393
3394   attr = xml_find_attribute (attributes, "handle");
3395   if (attr != NULL)
3396     item.thread_handle = hex2bin ((const char *) attr->value.get ());
3397 }
3398
3399 static void
3400 end_thread (struct gdb_xml_parser *parser,
3401             const struct gdb_xml_element *element,
3402             void *user_data, const char *body_text)
3403 {
3404   struct threads_listing_context *data
3405     = (struct threads_listing_context *) user_data;
3406
3407   if (body_text != NULL && *body_text != '\0')
3408     data->items.back ().extra = body_text;
3409 }
3410
3411 const struct gdb_xml_attribute thread_attributes[] = {
3412   { "id", GDB_XML_AF_NONE, NULL, NULL },
3413   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3414   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3415   { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3416   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3417 };
3418
3419 const struct gdb_xml_element thread_children[] = {
3420   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3421 };
3422
3423 const struct gdb_xml_element threads_children[] = {
3424   { "thread", thread_attributes, thread_children,
3425     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3426     start_thread, end_thread },
3427   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3428 };
3429
3430 const struct gdb_xml_element threads_elements[] = {
3431   { "threads", NULL, threads_children,
3432     GDB_XML_EF_NONE, NULL, NULL },
3433   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3434 };
3435
3436 #endif
3437
3438 /* List remote threads using qXfer:threads:read.  */
3439
3440 static int
3441 remote_get_threads_with_qxfer (struct target_ops *ops,
3442                                struct threads_listing_context *context)
3443 {
3444 #if defined(HAVE_LIBEXPAT)
3445   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3446     {
3447       gdb::optional<gdb::char_vector> xml
3448         = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3449
3450       if (xml && (*xml)[0] != '\0')
3451         {
3452           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3453                                threads_elements, xml->data (), context);
3454         }
3455
3456       return 1;
3457     }
3458 #endif
3459
3460   return 0;
3461 }
3462
3463 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3464
3465 static int
3466 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3467                                      struct threads_listing_context *context)
3468 {
3469   struct remote_state *rs = get_remote_state ();
3470
3471   if (rs->use_threadinfo_query)
3472     {
3473       const char *bufp;
3474
3475       putpkt ("qfThreadInfo");
3476       getpkt (&rs->buf, &rs->buf_size, 0);
3477       bufp = rs->buf;
3478       if (bufp[0] != '\0')              /* q packet recognized */
3479         {
3480           while (*bufp++ == 'm')        /* reply contains one or more TID */
3481             {
3482               do
3483                 {
3484                   ptid_t ptid = read_ptid (bufp, &bufp);
3485                   context->items.emplace_back (ptid);
3486                 }
3487               while (*bufp++ == ',');   /* comma-separated list */
3488               putpkt ("qsThreadInfo");
3489               getpkt (&rs->buf, &rs->buf_size, 0);
3490               bufp = rs->buf;
3491             }
3492           return 1;
3493         }
3494       else
3495         {
3496           /* Packet not recognized.  */
3497           rs->use_threadinfo_query = 0;
3498         }
3499     }
3500
3501   return 0;
3502 }
3503
3504 /* Implement the to_update_thread_list function for the remote
3505    targets.  */
3506
3507 void
3508 remote_target::update_thread_list ()
3509 {
3510   struct threads_listing_context context;
3511   int got_list = 0;
3512
3513   /* We have a few different mechanisms to fetch the thread list.  Try
3514      them all, starting with the most preferred one first, falling
3515      back to older methods.  */
3516   if (remote_get_threads_with_qxfer (this, &context)
3517       || remote_get_threads_with_qthreadinfo (this, &context)
3518       || remote_get_threads_with_ql (this, &context))
3519     {
3520       struct thread_info *tp, *tmp;
3521
3522       got_list = 1;
3523
3524       if (context.items.empty ()
3525           && remote_thread_always_alive (inferior_ptid))
3526         {
3527           /* Some targets don't really support threads, but still
3528              reply an (empty) thread list in response to the thread
3529              listing packets, instead of replying "packet not
3530              supported".  Exit early so we don't delete the main
3531              thread.  */
3532           return;
3533         }
3534
3535       /* CONTEXT now holds the current thread list on the remote
3536          target end.  Delete GDB-side threads no longer found on the
3537          target.  */
3538       ALL_THREADS_SAFE (tp, tmp)
3539         {
3540           if (!context.contains_thread (tp->ptid))
3541             {
3542               /* Not found.  */
3543               delete_thread (tp->ptid);
3544             }
3545         }
3546
3547       /* Remove any unreported fork child threads from CONTEXT so
3548          that we don't interfere with follow fork, which is where
3549          creation of such threads is handled.  */
3550       remove_new_fork_children (&context);
3551
3552       /* And now add threads we don't know about yet to our list.  */
3553       for (thread_item &item : context.items)
3554         {
3555           if (item.ptid != null_ptid)
3556             {
3557               /* In non-stop mode, we assume new found threads are
3558                  executing until proven otherwise with a stop reply.
3559                  In all-stop, we can only get here if all threads are
3560                  stopped.  */
3561               int executing = target_is_non_stop_p () ? 1 : 0;
3562
3563               remote_notice_new_inferior (item.ptid, executing);
3564
3565               remote_thread_info *info = get_remote_thread_info (item.ptid);
3566               info->core = item.core;
3567               info->extra = std::move (item.extra);
3568               info->name = std::move (item.name);
3569               info->thread_handle = std::move (item.thread_handle);
3570             }
3571         }
3572     }
3573
3574   if (!got_list)
3575     {
3576       /* If no thread listing method is supported, then query whether
3577          each known thread is alive, one by one, with the T packet.
3578          If the target doesn't support threads at all, then this is a
3579          no-op.  See remote_thread_alive.  */
3580       prune_threads ();
3581     }
3582 }
3583
3584 /*
3585  * Collect a descriptive string about the given thread.
3586  * The target may say anything it wants to about the thread
3587  * (typically info about its blocked / runnable state, name, etc.).
3588  * This string will appear in the info threads display.
3589  *
3590  * Optional: targets are not required to implement this function.
3591  */
3592
3593 const char *
3594 remote_target::extra_thread_info (thread_info *tp)
3595 {
3596   struct remote_state *rs = get_remote_state ();
3597   int result;
3598   int set;
3599   threadref id;
3600   struct gdb_ext_thread_info threadinfo;
3601   static char display_buf[100]; /* arbitrary...  */
3602   int n = 0;                    /* position in display_buf */
3603
3604   if (rs->remote_desc == 0)             /* paranoia */
3605     internal_error (__FILE__, __LINE__,
3606                     _("remote_threads_extra_info"));
3607
3608   if (ptid_equal (tp->ptid, magic_null_ptid)
3609       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3610     /* This is the main thread which was added by GDB.  The remote
3611        server doesn't know about it.  */
3612     return NULL;
3613
3614   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3615     {
3616       struct thread_info *info = find_thread_ptid (tp->ptid);
3617
3618       if (info != NULL && info->priv != NULL)
3619         {
3620           const std::string &extra = get_remote_thread_info (info)->extra;
3621           return !extra.empty () ? extra.c_str () : NULL;
3622         }
3623       else
3624         return NULL;
3625     }
3626
3627   if (rs->use_threadextra_query)
3628     {
3629       char *b = rs->buf;
3630       char *endb = rs->buf + get_remote_packet_size ();
3631
3632       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3633       b += strlen (b);
3634       write_ptid (b, endb, tp->ptid);
3635
3636       putpkt (rs->buf);
3637       getpkt (&rs->buf, &rs->buf_size, 0);
3638       if (rs->buf[0] != 0)
3639         {
3640           n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3641           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3642           display_buf [result] = '\0';
3643           return display_buf;
3644         }
3645     }
3646
3647   /* If the above query fails, fall back to the old method.  */
3648   rs->use_threadextra_query = 0;
3649   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3650     | TAG_MOREDISPLAY | TAG_DISPLAY;
3651   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3652   if (remote_get_threadinfo (&id, set, &threadinfo))
3653     if (threadinfo.active)
3654       {
3655         if (*threadinfo.shortname)
3656           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3657                           " Name: %s,", threadinfo.shortname);
3658         if (*threadinfo.display)
3659           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3660                           " State: %s,", threadinfo.display);
3661         if (*threadinfo.more_display)
3662           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3663                           " Priority: %s", threadinfo.more_display);
3664
3665         if (n > 0)
3666           {
3667             /* For purely cosmetic reasons, clear up trailing commas.  */
3668             if (',' == display_buf[n-1])
3669               display_buf[n-1] = ' ';
3670             return display_buf;
3671           }
3672       }
3673   return NULL;
3674 }
3675 \f
3676
3677 bool
3678 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3679                                             struct static_tracepoint_marker *marker)
3680 {
3681   struct remote_state *rs = get_remote_state ();
3682   char *p = rs->buf;
3683
3684   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3685   p += strlen (p);
3686   p += hexnumstr (p, addr);
3687   putpkt (rs->buf);
3688   getpkt (&rs->buf, &rs->buf_size, 0);
3689   p = rs->buf;
3690
3691   if (*p == 'E')
3692     error (_("Remote failure reply: %s"), p);
3693
3694   if (*p++ == 'm')
3695     {
3696       parse_static_tracepoint_marker_definition (p, NULL, marker);
3697       return true;
3698     }
3699
3700   return false;
3701 }
3702
3703 std::vector<static_tracepoint_marker>
3704 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3705 {
3706   struct remote_state *rs = get_remote_state ();
3707   std::vector<static_tracepoint_marker> markers;
3708   const char *p;
3709   static_tracepoint_marker marker;
3710
3711   /* Ask for a first packet of static tracepoint marker
3712      definition.  */
3713   putpkt ("qTfSTM");
3714   getpkt (&rs->buf, &rs->buf_size, 0);
3715   p = rs->buf;
3716   if (*p == 'E')
3717     error (_("Remote failure reply: %s"), p);
3718
3719   while (*p++ == 'm')
3720     {
3721       do
3722         {
3723           parse_static_tracepoint_marker_definition (p, &p, &marker);
3724
3725           if (strid == NULL || marker.str_id == strid)
3726             markers.push_back (std::move (marker));
3727         }
3728       while (*p++ == ',');      /* comma-separated list */
3729       /* Ask for another packet of static tracepoint definition.  */
3730       putpkt ("qTsSTM");
3731       getpkt (&rs->buf, &rs->buf_size, 0);
3732       p = rs->buf;
3733     }
3734
3735   return markers;
3736 }
3737
3738 \f
3739 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3740
3741 ptid_t
3742 remote_target::get_ada_task_ptid (long lwp, long thread)
3743 {
3744   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3745 }
3746 \f
3747
3748 /* Restart the remote side; this is an extended protocol operation.  */
3749
3750 static void
3751 extended_remote_restart (void)
3752 {
3753   struct remote_state *rs = get_remote_state ();
3754
3755   /* Send the restart command; for reasons I don't understand the
3756      remote side really expects a number after the "R".  */
3757   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3758   putpkt (rs->buf);
3759
3760   remote_fileio_reset ();
3761 }
3762 \f
3763 /* Clean up connection to a remote debugger.  */
3764
3765 void
3766 remote_target::close ()
3767 {
3768   struct remote_state *rs = get_remote_state ();
3769
3770   if (rs->remote_desc == NULL)
3771     return; /* already closed */
3772
3773   /* Make sure we leave stdin registered in the event loop.  */
3774   terminal_ours ();
3775
3776   serial_close (rs->remote_desc);
3777   rs->remote_desc = NULL;
3778
3779   /* We don't have a connection to the remote stub anymore.  Get rid
3780      of all the inferiors and their threads we were controlling.
3781      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3782      will be unable to find the thread corresponding to (pid, 0, 0).  */
3783   inferior_ptid = null_ptid;
3784   discard_all_inferiors ();
3785
3786   /* We are closing the remote target, so we should discard
3787      everything of this target.  */
3788   discard_pending_stop_replies_in_queue (rs);
3789
3790   if (remote_async_inferior_event_token)
3791     delete_async_event_handler (&remote_async_inferior_event_token);
3792
3793   remote_notif_state_xfree (rs->notif_state);
3794
3795   trace_reset_local_state ();
3796 }
3797
3798 /* Query the remote side for the text, data and bss offsets.  */
3799
3800 static void
3801 get_offsets (void)
3802 {
3803   struct remote_state *rs = get_remote_state ();
3804   char *buf;
3805   char *ptr;
3806   int lose, num_segments = 0, do_sections, do_segments;
3807   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3808   struct section_offsets *offs;
3809   struct symfile_segment_data *data;
3810
3811   if (symfile_objfile == NULL)
3812     return;
3813
3814   putpkt ("qOffsets");
3815   getpkt (&rs->buf, &rs->buf_size, 0);
3816   buf = rs->buf;
3817
3818   if (buf[0] == '\000')
3819     return;                     /* Return silently.  Stub doesn't support
3820                                    this command.  */
3821   if (buf[0] == 'E')
3822     {
3823       warning (_("Remote failure reply: %s"), buf);
3824       return;
3825     }
3826
3827   /* Pick up each field in turn.  This used to be done with scanf, but
3828      scanf will make trouble if CORE_ADDR size doesn't match
3829      conversion directives correctly.  The following code will work
3830      with any size of CORE_ADDR.  */
3831   text_addr = data_addr = bss_addr = 0;
3832   ptr = buf;
3833   lose = 0;
3834
3835   if (startswith (ptr, "Text="))
3836     {
3837       ptr += 5;
3838       /* Don't use strtol, could lose on big values.  */
3839       while (*ptr && *ptr != ';')
3840         text_addr = (text_addr << 4) + fromhex (*ptr++);
3841
3842       if (startswith (ptr, ";Data="))
3843         {
3844           ptr += 6;
3845           while (*ptr && *ptr != ';')
3846             data_addr = (data_addr << 4) + fromhex (*ptr++);
3847         }
3848       else
3849         lose = 1;
3850
3851       if (!lose && startswith (ptr, ";Bss="))
3852         {
3853           ptr += 5;
3854           while (*ptr && *ptr != ';')
3855             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3856
3857           if (bss_addr != data_addr)
3858             warning (_("Target reported unsupported offsets: %s"), buf);
3859         }
3860       else
3861         lose = 1;
3862     }
3863   else if (startswith (ptr, "TextSeg="))
3864     {
3865       ptr += 8;
3866       /* Don't use strtol, could lose on big values.  */
3867       while (*ptr && *ptr != ';')
3868         text_addr = (text_addr << 4) + fromhex (*ptr++);
3869       num_segments = 1;
3870
3871       if (startswith (ptr, ";DataSeg="))
3872         {
3873           ptr += 9;
3874           while (*ptr && *ptr != ';')
3875             data_addr = (data_addr << 4) + fromhex (*ptr++);
3876           num_segments++;
3877         }
3878     }
3879   else
3880     lose = 1;
3881
3882   if (lose)
3883     error (_("Malformed response to offset query, %s"), buf);
3884   else if (*ptr != '\0')
3885     warning (_("Target reported unsupported offsets: %s"), buf);
3886
3887   offs = ((struct section_offsets *)
3888           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3889   memcpy (offs, symfile_objfile->section_offsets,
3890           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3891
3892   data = get_symfile_segment_data (symfile_objfile->obfd);
3893   do_segments = (data != NULL);
3894   do_sections = num_segments == 0;
3895
3896   if (num_segments > 0)
3897     {
3898       segments[0] = text_addr;
3899       segments[1] = data_addr;
3900     }
3901   /* If we have two segments, we can still try to relocate everything
3902      by assuming that the .text and .data offsets apply to the whole
3903      text and data segments.  Convert the offsets given in the packet
3904      to base addresses for symfile_map_offsets_to_segments.  */
3905   else if (data && data->num_segments == 2)
3906     {
3907       segments[0] = data->segment_bases[0] + text_addr;
3908       segments[1] = data->segment_bases[1] + data_addr;
3909       num_segments = 2;
3910     }
3911   /* If the object file has only one segment, assume that it is text
3912      rather than data; main programs with no writable data are rare,
3913      but programs with no code are useless.  Of course the code might
3914      have ended up in the data segment... to detect that we would need
3915      the permissions here.  */
3916   else if (data && data->num_segments == 1)
3917     {
3918       segments[0] = data->segment_bases[0] + text_addr;
3919       num_segments = 1;
3920     }
3921   /* There's no way to relocate by segment.  */
3922   else
3923     do_segments = 0;
3924
3925   if (do_segments)
3926     {
3927       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3928                                                  offs, num_segments, segments);
3929
3930       if (ret == 0 && !do_sections)
3931         error (_("Can not handle qOffsets TextSeg "
3932                  "response with this symbol file"));
3933
3934       if (ret > 0)
3935         do_sections = 0;
3936     }
3937
3938   if (data)
3939     free_symfile_segment_data (data);
3940
3941   if (do_sections)
3942     {
3943       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3944
3945       /* This is a temporary kludge to force data and bss to use the
3946          same offsets because that's what nlmconv does now.  The real
3947          solution requires changes to the stub and remote.c that I
3948          don't have time to do right now.  */
3949
3950       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3951       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3952     }
3953
3954   objfile_relocate (symfile_objfile, offs);
3955 }
3956
3957 /* Send interrupt_sequence to remote target.  */
3958 static void
3959 send_interrupt_sequence (void)
3960 {
3961   struct remote_state *rs = get_remote_state ();
3962
3963   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3964     remote_serial_write ("\x03", 1);
3965   else if (interrupt_sequence_mode == interrupt_sequence_break)
3966     serial_send_break (rs->remote_desc);
3967   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3968     {
3969       serial_send_break (rs->remote_desc);
3970       remote_serial_write ("g", 1);
3971     }
3972   else
3973     internal_error (__FILE__, __LINE__,
3974                     _("Invalid value for interrupt_sequence_mode: %s."),
3975                     interrupt_sequence_mode);
3976 }
3977
3978
3979 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3980    and extract the PTID.  Returns NULL_PTID if not found.  */
3981
3982 static ptid_t
3983 stop_reply_extract_thread (char *stop_reply)
3984 {
3985   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3986     {
3987       const char *p;
3988
3989       /* Txx r:val ; r:val (...)  */
3990       p = &stop_reply[3];
3991
3992       /* Look for "register" named "thread".  */
3993       while (*p != '\0')
3994         {
3995           const char *p1;
3996
3997           p1 = strchr (p, ':');
3998           if (p1 == NULL)
3999             return null_ptid;
4000
4001           if (strncmp (p, "thread", p1 - p) == 0)
4002             return read_ptid (++p1, &p);
4003
4004           p1 = strchr (p, ';');
4005           if (p1 == NULL)
4006             return null_ptid;
4007           p1++;
4008
4009           p = p1;
4010         }
4011     }
4012
4013   return null_ptid;
4014 }
4015
4016 /* Determine the remote side's current thread.  If we have a stop
4017    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4018    "thread" register we can extract the current thread from.  If not,
4019    ask the remote which is the current thread with qC.  The former
4020    method avoids a roundtrip.  */
4021
4022 static ptid_t
4023 get_current_thread (char *wait_status)
4024 {
4025   ptid_t ptid = null_ptid;
4026
4027   /* Note we don't use remote_parse_stop_reply as that makes use of
4028      the target architecture, which we haven't yet fully determined at
4029      this point.  */
4030   if (wait_status != NULL)
4031     ptid = stop_reply_extract_thread (wait_status);
4032   if (ptid_equal (ptid, null_ptid))
4033     ptid = remote_current_thread (inferior_ptid);
4034
4035   return ptid;
4036 }
4037
4038 /* Query the remote target for which is the current thread/process,
4039    add it to our tables, and update INFERIOR_PTID.  The caller is
4040    responsible for setting the state such that the remote end is ready
4041    to return the current thread.
4042
4043    This function is called after handling the '?' or 'vRun' packets,
4044    whose response is a stop reply from which we can also try
4045    extracting the thread.  If the target doesn't support the explicit
4046    qC query, we infer the current thread from that stop reply, passed
4047    in in WAIT_STATUS, which may be NULL.  */
4048
4049 static void
4050 add_current_inferior_and_thread (char *wait_status)
4051 {
4052   struct remote_state *rs = get_remote_state ();
4053   int fake_pid_p = 0;
4054
4055   inferior_ptid = null_ptid;
4056
4057   /* Now, if we have thread information, update inferior_ptid.  */
4058   ptid_t curr_ptid = get_current_thread (wait_status);
4059
4060   if (curr_ptid != null_ptid)
4061     {
4062       if (!remote_multi_process_p (rs))
4063         fake_pid_p = 1;
4064     }
4065   else
4066     {
4067       /* Without this, some commands which require an active target
4068          (such as kill) won't work.  This variable serves (at least)
4069          double duty as both the pid of the target process (if it has
4070          such), and as a flag indicating that a target is active.  */
4071       curr_ptid = magic_null_ptid;
4072       fake_pid_p = 1;
4073     }
4074
4075   remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
4076
4077   /* Add the main thread and switch to it.  Don't try reading
4078      registers yet, since we haven't fetched the target description
4079      yet.  */
4080   thread_info *tp = add_thread_silent (curr_ptid);
4081   switch_to_thread_no_regs (tp);
4082 }
4083
4084 /* Print info about a thread that was found already stopped on
4085    connection.  */
4086
4087 static void
4088 print_one_stopped_thread (struct thread_info *thread)
4089 {
4090   struct target_waitstatus *ws = &thread->suspend.waitstatus;
4091
4092   switch_to_thread (thread->ptid);
4093   stop_pc = get_frame_pc (get_current_frame ());
4094   set_current_sal_from_frame (get_current_frame ());
4095
4096   thread->suspend.waitstatus_pending_p = 0;
4097
4098   if (ws->kind == TARGET_WAITKIND_STOPPED)
4099     {
4100       enum gdb_signal sig = ws->value.sig;
4101
4102       if (signal_print_state (sig))
4103         gdb::observers::signal_received.notify (sig);
4104     }
4105   gdb::observers::normal_stop.notify (NULL, 1);
4106 }
4107
4108 /* Process all initial stop replies the remote side sent in response
4109    to the ? packet.  These indicate threads that were already stopped
4110    on initial connection.  We mark these threads as stopped and print
4111    their current frame before giving the user the prompt.  */
4112
4113 static void
4114 process_initial_stop_replies (int from_tty)
4115 {
4116   int pending_stop_replies = stop_reply_queue_length ();
4117   struct inferior *inf;
4118   struct thread_info *thread;
4119   struct thread_info *selected = NULL;
4120   struct thread_info *lowest_stopped = NULL;
4121   struct thread_info *first = NULL;
4122
4123   /* Consume the initial pending events.  */
4124   while (pending_stop_replies-- > 0)
4125     {
4126       ptid_t waiton_ptid = minus_one_ptid;
4127       ptid_t event_ptid;
4128       struct target_waitstatus ws;
4129       int ignore_event = 0;
4130       struct thread_info *thread;
4131
4132       memset (&ws, 0, sizeof (ws));
4133       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4134       if (remote_debug)
4135         print_target_wait_results (waiton_ptid, event_ptid, &ws);
4136
4137       switch (ws.kind)
4138         {
4139         case TARGET_WAITKIND_IGNORE:
4140         case TARGET_WAITKIND_NO_RESUMED:
4141         case TARGET_WAITKIND_SIGNALLED:
4142         case TARGET_WAITKIND_EXITED:
4143           /* We shouldn't see these, but if we do, just ignore.  */
4144           if (remote_debug)
4145             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4146           ignore_event = 1;
4147           break;
4148
4149         case TARGET_WAITKIND_EXECD:
4150           xfree (ws.value.execd_pathname);
4151           break;
4152         default:
4153           break;
4154         }
4155
4156       if (ignore_event)
4157         continue;
4158
4159       thread = find_thread_ptid (event_ptid);
4160
4161       if (ws.kind == TARGET_WAITKIND_STOPPED)
4162         {
4163           enum gdb_signal sig = ws.value.sig;
4164
4165           /* Stubs traditionally report SIGTRAP as initial signal,
4166              instead of signal 0.  Suppress it.  */
4167           if (sig == GDB_SIGNAL_TRAP)
4168             sig = GDB_SIGNAL_0;
4169           thread->suspend.stop_signal = sig;
4170           ws.value.sig = sig;
4171         }
4172
4173       thread->suspend.waitstatus = ws;
4174
4175       if (ws.kind != TARGET_WAITKIND_STOPPED
4176           || ws.value.sig != GDB_SIGNAL_0)
4177         thread->suspend.waitstatus_pending_p = 1;
4178
4179       set_executing (event_ptid, 0);
4180       set_running (event_ptid, 0);
4181       get_remote_thread_info (thread)->vcont_resumed = 0;
4182     }
4183
4184   /* "Notice" the new inferiors before anything related to
4185      registers/memory.  */
4186   ALL_INFERIORS (inf)
4187     {
4188       if (inf->pid == 0)
4189         continue;
4190
4191       inf->needs_setup = 1;
4192
4193       if (non_stop)
4194         {
4195           thread = any_live_thread_of_process (inf->pid);
4196           notice_new_inferior (thread->ptid,
4197                                thread->state == THREAD_RUNNING,
4198                                from_tty);
4199         }
4200     }
4201
4202   /* If all-stop on top of non-stop, pause all threads.  Note this
4203      records the threads' stop pc, so must be done after "noticing"
4204      the inferiors.  */
4205   if (!non_stop)
4206     {
4207       stop_all_threads ();
4208
4209       /* If all threads of an inferior were already stopped, we
4210          haven't setup the inferior yet.  */
4211       ALL_INFERIORS (inf)
4212         {
4213           if (inf->pid == 0)
4214             continue;
4215
4216           if (inf->needs_setup)
4217             {
4218               thread = any_live_thread_of_process (inf->pid);
4219               switch_to_thread_no_regs (thread);
4220               setup_inferior (0);
4221             }
4222         }
4223     }
4224
4225   /* Now go over all threads that are stopped, and print their current
4226      frame.  If all-stop, then if there's a signalled thread, pick
4227      that as current.  */
4228   ALL_NON_EXITED_THREADS (thread)
4229     {
4230       if (first == NULL)
4231         first = thread;
4232
4233       if (!non_stop)
4234         set_running (thread->ptid, 0);
4235       else if (thread->state != THREAD_STOPPED)
4236         continue;
4237
4238       if (selected == NULL
4239           && thread->suspend.waitstatus_pending_p)
4240         selected = thread;
4241
4242       if (lowest_stopped == NULL
4243           || thread->inf->num < lowest_stopped->inf->num
4244           || thread->per_inf_num < lowest_stopped->per_inf_num)
4245         lowest_stopped = thread;
4246
4247       if (non_stop)
4248         print_one_stopped_thread (thread);
4249     }
4250
4251   /* In all-stop, we only print the status of one thread, and leave
4252      others with their status pending.  */
4253   if (!non_stop)
4254     {
4255       thread = selected;
4256       if (thread == NULL)
4257         thread = lowest_stopped;
4258       if (thread == NULL)
4259         thread = first;
4260
4261       print_one_stopped_thread (thread);
4262     }
4263
4264   /* For "info program".  */
4265   thread = inferior_thread ();
4266   if (thread->state == THREAD_STOPPED)
4267     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4268 }
4269
4270 /* Start the remote connection and sync state.  */
4271
4272 void
4273 remote_target::start_remote (int from_tty, int extended_p)
4274 {
4275   struct remote_state *rs = get_remote_state ();
4276   struct packet_config *noack_config;
4277   char *wait_status = NULL;
4278
4279   /* Signal other parts that we're going through the initial setup,
4280      and so things may not be stable yet.  E.g., we don't try to
4281      install tracepoints until we've relocated symbols.  Also, a
4282      Ctrl-C before we're connected and synced up can't interrupt the
4283      target.  Instead, it offers to drop the (potentially wedged)
4284      connection.  */
4285   rs->starting_up = 1;
4286
4287   QUIT;
4288
4289   if (interrupt_on_connect)
4290     send_interrupt_sequence ();
4291
4292   /* Ack any packet which the remote side has already sent.  */
4293   remote_serial_write ("+", 1);
4294
4295   /* The first packet we send to the target is the optional "supported
4296      packets" request.  If the target can answer this, it will tell us
4297      which later probes to skip.  */
4298   remote_query_supported ();
4299
4300   /* If the stub wants to get a QAllow, compose one and send it.  */
4301   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4302     set_permissions ();
4303
4304   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4305      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
4306      as a reply to known packet.  For packet "vFile:setfs:" it is an
4307      invalid reply and GDB would return error in
4308      remote_hostio_set_filesystem, making remote files access impossible.
4309      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
4310      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
4311   {
4312     const char v_mustreplyempty[] = "vMustReplyEmpty";
4313
4314     putpkt (v_mustreplyempty);
4315     getpkt (&rs->buf, &rs->buf_size, 0);
4316     if (strcmp (rs->buf, "OK") == 0)
4317       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4318     else if (strcmp (rs->buf, "") != 0)
4319       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4320              rs->buf);
4321   }
4322
4323   /* Next, we possibly activate noack mode.
4324
4325      If the QStartNoAckMode packet configuration is set to AUTO,
4326      enable noack mode if the stub reported a wish for it with
4327      qSupported.
4328
4329      If set to TRUE, then enable noack mode even if the stub didn't
4330      report it in qSupported.  If the stub doesn't reply OK, the
4331      session ends with an error.
4332
4333      If FALSE, then don't activate noack mode, regardless of what the
4334      stub claimed should be the default with qSupported.  */
4335
4336   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4337   if (packet_config_support (noack_config) != PACKET_DISABLE)
4338     {
4339       putpkt ("QStartNoAckMode");
4340       getpkt (&rs->buf, &rs->buf_size, 0);
4341       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4342         rs->noack_mode = 1;
4343     }
4344
4345   if (extended_p)
4346     {
4347       /* Tell the remote that we are using the extended protocol.  */
4348       putpkt ("!");
4349       getpkt (&rs->buf, &rs->buf_size, 0);
4350     }
4351
4352   /* Let the target know which signals it is allowed to pass down to
4353      the program.  */
4354   update_signals_program_target ();
4355
4356   /* Next, if the target can specify a description, read it.  We do
4357      this before anything involving memory or registers.  */
4358   target_find_description ();
4359
4360   /* Next, now that we know something about the target, update the
4361      address spaces in the program spaces.  */
4362   update_address_spaces ();
4363
4364   /* On OSs where the list of libraries is global to all
4365      processes, we fetch them early.  */
4366   if (gdbarch_has_global_solist (target_gdbarch ()))
4367     solib_add (NULL, from_tty, auto_solib_add);
4368
4369   if (target_is_non_stop_p ())
4370     {
4371       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4372         error (_("Non-stop mode requested, but remote "
4373                  "does not support non-stop"));
4374
4375       putpkt ("QNonStop:1");
4376       getpkt (&rs->buf, &rs->buf_size, 0);
4377
4378       if (strcmp (rs->buf, "OK") != 0)
4379         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4380
4381       /* Find about threads and processes the stub is already
4382          controlling.  We default to adding them in the running state.
4383          The '?' query below will then tell us about which threads are
4384          stopped.  */
4385       this->update_thread_list ();
4386     }
4387   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4388     {
4389       /* Don't assume that the stub can operate in all-stop mode.
4390          Request it explicitly.  */
4391       putpkt ("QNonStop:0");
4392       getpkt (&rs->buf, &rs->buf_size, 0);
4393
4394       if (strcmp (rs->buf, "OK") != 0)
4395         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4396     }
4397
4398   /* Upload TSVs regardless of whether the target is running or not.  The
4399      remote stub, such as GDBserver, may have some predefined or builtin
4400      TSVs, even if the target is not running.  */
4401   if (get_trace_status (current_trace_status ()) != -1)
4402     {
4403       struct uploaded_tsv *uploaded_tsvs = NULL;
4404
4405       upload_trace_state_variables (&uploaded_tsvs);
4406       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4407     }
4408
4409   /* Check whether the target is running now.  */
4410   putpkt ("?");
4411   getpkt (&rs->buf, &rs->buf_size, 0);
4412
4413   if (!target_is_non_stop_p ())
4414     {
4415       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4416         {
4417           if (!extended_p)
4418             error (_("The target is not running (try extended-remote?)"));
4419
4420           /* We're connected, but not running.  Drop out before we
4421              call start_remote.  */
4422           rs->starting_up = 0;
4423           return;
4424         }
4425       else
4426         {
4427           /* Save the reply for later.  */
4428           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4429           strcpy (wait_status, rs->buf);
4430         }
4431
4432       /* Fetch thread list.  */
4433       target_update_thread_list ();
4434
4435       /* Let the stub know that we want it to return the thread.  */
4436       set_continue_thread (minus_one_ptid);
4437
4438       if (thread_count () == 0)
4439         {
4440           /* Target has no concept of threads at all.  GDB treats
4441              non-threaded target as single-threaded; add a main
4442              thread.  */
4443           add_current_inferior_and_thread (wait_status);
4444         }
4445       else
4446         {
4447           /* We have thread information; select the thread the target
4448              says should be current.  If we're reconnecting to a
4449              multi-threaded program, this will ideally be the thread
4450              that last reported an event before GDB disconnected.  */
4451           inferior_ptid = get_current_thread (wait_status);
4452           if (ptid_equal (inferior_ptid, null_ptid))
4453             {
4454               /* Odd... The target was able to list threads, but not
4455                  tell us which thread was current (no "thread"
4456                  register in T stop reply?).  Just pick the first
4457                  thread in the thread list then.  */
4458               
4459               if (remote_debug)
4460                 fprintf_unfiltered (gdb_stdlog,
4461                                     "warning: couldn't determine remote "
4462                                     "current thread; picking first in list.\n");
4463
4464               inferior_ptid = thread_list->ptid;
4465             }
4466         }
4467
4468       /* init_wait_for_inferior should be called before get_offsets in order
4469          to manage `inserted' flag in bp loc in a correct state.
4470          breakpoint_init_inferior, called from init_wait_for_inferior, set
4471          `inserted' flag to 0, while before breakpoint_re_set, called from
4472          start_remote, set `inserted' flag to 1.  In the initialization of
4473          inferior, breakpoint_init_inferior should be called first, and then
4474          breakpoint_re_set can be called.  If this order is broken, state of
4475          `inserted' flag is wrong, and cause some problems on breakpoint
4476          manipulation.  */
4477       init_wait_for_inferior ();
4478
4479       get_offsets ();           /* Get text, data & bss offsets.  */
4480
4481       /* If we could not find a description using qXfer, and we know
4482          how to do it some other way, try again.  This is not
4483          supported for non-stop; it could be, but it is tricky if
4484          there are no stopped threads when we connect.  */
4485       if (remote_read_description_p (this)
4486           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4487         {
4488           target_clear_description ();
4489           target_find_description ();
4490         }
4491
4492       /* Use the previously fetched status.  */
4493       gdb_assert (wait_status != NULL);
4494       strcpy (rs->buf, wait_status);
4495       rs->cached_wait_status = 1;
4496
4497       ::start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4498     }
4499   else
4500     {
4501       /* Clear WFI global state.  Do this before finding about new
4502          threads and inferiors, and setting the current inferior.
4503          Otherwise we would clear the proceed status of the current
4504          inferior when we want its stop_soon state to be preserved
4505          (see notice_new_inferior).  */
4506       init_wait_for_inferior ();
4507
4508       /* In non-stop, we will either get an "OK", meaning that there
4509          are no stopped threads at this time; or, a regular stop
4510          reply.  In the latter case, there may be more than one thread
4511          stopped --- we pull them all out using the vStopped
4512          mechanism.  */
4513       if (strcmp (rs->buf, "OK") != 0)
4514         {
4515           struct notif_client *notif = &notif_client_stop;
4516
4517           /* remote_notif_get_pending_replies acks this one, and gets
4518              the rest out.  */
4519           rs->notif_state->pending_event[notif_client_stop.id]
4520             = remote_notif_parse (notif, rs->buf);
4521           remote_notif_get_pending_events (notif);
4522         }
4523
4524       if (thread_count () == 0)
4525         {
4526           if (!extended_p)
4527             error (_("The target is not running (try extended-remote?)"));
4528
4529           /* We're connected, but not running.  Drop out before we
4530              call start_remote.  */
4531           rs->starting_up = 0;
4532           return;
4533         }
4534
4535       /* In non-stop mode, any cached wait status will be stored in
4536          the stop reply queue.  */
4537       gdb_assert (wait_status == NULL);
4538
4539       /* Report all signals during attach/startup.  */
4540       pass_signals (0, NULL);
4541
4542       /* If there are already stopped threads, mark them stopped and
4543          report their stops before giving the prompt to the user.  */
4544       process_initial_stop_replies (from_tty);
4545
4546       if (target_can_async_p ())
4547         target_async (1);
4548     }
4549
4550   /* If we connected to a live target, do some additional setup.  */
4551   if (target_has_execution)
4552     {
4553       if (symfile_objfile)      /* No use without a symbol-file.  */
4554         remote_check_symbols ();
4555     }
4556
4557   /* Possibly the target has been engaged in a trace run started
4558      previously; find out where things are at.  */
4559   if (get_trace_status (current_trace_status ()) != -1)
4560     {
4561       struct uploaded_tp *uploaded_tps = NULL;
4562
4563       if (current_trace_status ()->running)
4564         printf_filtered (_("Trace is already running on the target.\n"));
4565
4566       upload_tracepoints (&uploaded_tps);
4567
4568       merge_uploaded_tracepoints (&uploaded_tps);
4569     }
4570
4571   /* Possibly the target has been engaged in a btrace record started
4572      previously; find out where things are at.  */
4573   remote_btrace_maybe_reopen ();
4574
4575   /* The thread and inferior lists are now synchronized with the
4576      target, our symbols have been relocated, and we're merged the
4577      target's tracepoints with ours.  We're done with basic start
4578      up.  */
4579   rs->starting_up = 0;
4580
4581   /* Maybe breakpoints are global and need to be inserted now.  */
4582   if (breakpoints_should_be_inserted_now ())
4583     insert_breakpoints ();
4584 }
4585
4586 /* Open a connection to a remote debugger.
4587    NAME is the filename used for communication.  */
4588
4589 void
4590 remote_target::open (const char *name, int from_tty)
4591 {
4592   open_1 (name, from_tty, 0);
4593 }
4594
4595 /* Open a connection to a remote debugger using the extended
4596    remote gdb protocol.  NAME is the filename used for communication.  */
4597
4598 void
4599 extended_remote_target::open (const char *name, int from_tty)
4600 {
4601   open_1 (name, from_tty, 1 /*extended_p */);
4602 }
4603
4604 /* Reset all packets back to "unknown support".  Called when opening a
4605    new connection to a remote target.  */
4606
4607 static void
4608 reset_all_packet_configs_support (void)
4609 {
4610   int i;
4611
4612   for (i = 0; i < PACKET_MAX; i++)
4613     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4614 }
4615
4616 /* Initialize all packet configs.  */
4617
4618 static void
4619 init_all_packet_configs (void)
4620 {
4621   int i;
4622
4623   for (i = 0; i < PACKET_MAX; i++)
4624     {
4625       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4626       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4627     }
4628 }
4629
4630 /* Symbol look-up.  */
4631
4632 static void
4633 remote_check_symbols (void)
4634 {
4635   char *msg, *reply, *tmp;
4636   int end;
4637   long reply_size;
4638   struct cleanup *old_chain;
4639
4640   /* The remote side has no concept of inferiors that aren't running
4641      yet, it only knows about running processes.  If we're connected
4642      but our current inferior is not running, we should not invite the
4643      remote target to request symbol lookups related to its
4644      (unrelated) current process.  */
4645   if (!target_has_execution)
4646     return;
4647
4648   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4649     return;
4650
4651   /* Make sure the remote is pointing at the right process.  Note
4652      there's no way to select "no process".  */
4653   set_general_process ();
4654
4655   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4656      because we need both at the same time.  */
4657   msg = (char *) xmalloc (get_remote_packet_size ());
4658   old_chain = make_cleanup (xfree, msg);
4659   reply = (char *) xmalloc (get_remote_packet_size ());
4660   make_cleanup (free_current_contents, &reply);
4661   reply_size = get_remote_packet_size ();
4662
4663   /* Invite target to request symbol lookups.  */
4664
4665   putpkt ("qSymbol::");
4666   getpkt (&reply, &reply_size, 0);
4667   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4668
4669   while (startswith (reply, "qSymbol:"))
4670     {
4671       struct bound_minimal_symbol sym;
4672
4673       tmp = &reply[8];
4674       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4675       msg[end] = '\0';
4676       sym = lookup_minimal_symbol (msg, NULL, NULL);
4677       if (sym.minsym == NULL)
4678         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4679       else
4680         {
4681           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4682           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4683
4684           /* If this is a function address, return the start of code
4685              instead of any data function descriptor.  */
4686           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4687                                                          sym_addr,
4688                                                          target_stack);
4689
4690           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4691                      phex_nz (sym_addr, addr_size), &reply[8]);
4692         }
4693   
4694       putpkt (msg);
4695       getpkt (&reply, &reply_size, 0);
4696     }
4697
4698   do_cleanups (old_chain);
4699 }
4700
4701 static struct serial *
4702 remote_serial_open (const char *name)
4703 {
4704   static int udp_warning = 0;
4705
4706   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4707      of in ser-tcp.c, because it is the remote protocol assuming that the
4708      serial connection is reliable and not the serial connection promising
4709      to be.  */
4710   if (!udp_warning && startswith (name, "udp:"))
4711     {
4712       warning (_("The remote protocol may be unreliable over UDP.\n"
4713                  "Some events may be lost, rendering further debugging "
4714                  "impossible."));
4715       udp_warning = 1;
4716     }
4717
4718   return serial_open (name);
4719 }
4720
4721 /* Inform the target of our permission settings.  The permission flags
4722    work without this, but if the target knows the settings, it can do
4723    a couple things.  First, it can add its own check, to catch cases
4724    that somehow manage to get by the permissions checks in target
4725    methods.  Second, if the target is wired to disallow particular
4726    settings (for instance, a system in the field that is not set up to
4727    be able to stop at a breakpoint), it can object to any unavailable
4728    permissions.  */
4729
4730 void
4731 remote_target::set_permissions ()
4732 {
4733   struct remote_state *rs = get_remote_state ();
4734
4735   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4736              "WriteReg:%x;WriteMem:%x;"
4737              "InsertBreak:%x;InsertTrace:%x;"
4738              "InsertFastTrace:%x;Stop:%x",
4739              may_write_registers, may_write_memory,
4740              may_insert_breakpoints, may_insert_tracepoints,
4741              may_insert_fast_tracepoints, may_stop);
4742   putpkt (rs->buf);
4743   getpkt (&rs->buf, &rs->buf_size, 0);
4744
4745   /* If the target didn't like the packet, warn the user.  Do not try
4746      to undo the user's settings, that would just be maddening.  */
4747   if (strcmp (rs->buf, "OK") != 0)
4748     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4749 }
4750
4751 /* This type describes each known response to the qSupported
4752    packet.  */
4753 struct protocol_feature
4754 {
4755   /* The name of this protocol feature.  */
4756   const char *name;
4757
4758   /* The default for this protocol feature.  */
4759   enum packet_support default_support;
4760
4761   /* The function to call when this feature is reported, or after
4762      qSupported processing if the feature is not supported.
4763      The first argument points to this structure.  The second
4764      argument indicates whether the packet requested support be
4765      enabled, disabled, or probed (or the default, if this function
4766      is being called at the end of processing and this feature was
4767      not reported).  The third argument may be NULL; if not NULL, it
4768      is a NUL-terminated string taken from the packet following
4769      this feature's name and an equals sign.  */
4770   void (*func) (const struct protocol_feature *, enum packet_support,
4771                 const char *);
4772
4773   /* The corresponding packet for this feature.  Only used if
4774      FUNC is remote_supported_packet.  */
4775   int packet;
4776 };
4777
4778 static void
4779 remote_supported_packet (const struct protocol_feature *feature,
4780                          enum packet_support support,
4781                          const char *argument)
4782 {
4783   if (argument)
4784     {
4785       warning (_("Remote qSupported response supplied an unexpected value for"
4786                  " \"%s\"."), feature->name);
4787       return;
4788     }
4789
4790   remote_protocol_packets[feature->packet].support = support;
4791 }
4792
4793 static void
4794 remote_packet_size (const struct protocol_feature *feature,
4795                     enum packet_support support, const char *value)
4796 {
4797   struct remote_state *rs = get_remote_state ();
4798
4799   int packet_size;
4800   char *value_end;
4801
4802   if (support != PACKET_ENABLE)
4803     return;
4804
4805   if (value == NULL || *value == '\0')
4806     {
4807       warning (_("Remote target reported \"%s\" without a size."),
4808                feature->name);
4809       return;
4810     }
4811
4812   errno = 0;
4813   packet_size = strtol (value, &value_end, 16);
4814   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4815     {
4816       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4817                feature->name, value);
4818       return;
4819     }
4820
4821   /* Record the new maximum packet size.  */
4822   rs->explicit_packet_size = packet_size;
4823 }
4824
4825 static const struct protocol_feature remote_protocol_features[] = {
4826   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4827   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4828     PACKET_qXfer_auxv },
4829   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4830     PACKET_qXfer_exec_file },
4831   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4832     PACKET_qXfer_features },
4833   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4834     PACKET_qXfer_libraries },
4835   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4836     PACKET_qXfer_libraries_svr4 },
4837   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4838     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4839   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4840     PACKET_qXfer_memory_map },
4841   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4842     PACKET_qXfer_spu_read },
4843   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4844     PACKET_qXfer_spu_write },
4845   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4846     PACKET_qXfer_osdata },
4847   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4848     PACKET_qXfer_threads },
4849   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4850     PACKET_qXfer_traceframe_info },
4851   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4852     PACKET_QPassSignals },
4853   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4854     PACKET_QCatchSyscalls },
4855   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4856     PACKET_QProgramSignals },
4857   { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4858     PACKET_QSetWorkingDir },
4859   { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4860     PACKET_QStartupWithShell },
4861   { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4862     PACKET_QEnvironmentHexEncoded },
4863   { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4864     PACKET_QEnvironmentReset },
4865   { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4866     PACKET_QEnvironmentUnset },
4867   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4868     PACKET_QStartNoAckMode },
4869   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4870     PACKET_multiprocess_feature },
4871   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4872   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4873     PACKET_qXfer_siginfo_read },
4874   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4875     PACKET_qXfer_siginfo_write },
4876   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4877     PACKET_ConditionalTracepoints },
4878   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4879     PACKET_ConditionalBreakpoints },
4880   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4881     PACKET_BreakpointCommands },
4882   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4883     PACKET_FastTracepoints },
4884   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4885     PACKET_StaticTracepoints },
4886   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4887    PACKET_InstallInTrace},
4888   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4889     PACKET_DisconnectedTracing_feature },
4890   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4891     PACKET_bc },
4892   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4893     PACKET_bs },
4894   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4895     PACKET_TracepointSource },
4896   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4897     PACKET_QAllow },
4898   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4899     PACKET_EnableDisableTracepoints_feature },
4900   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4901     PACKET_qXfer_fdpic },
4902   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4903     PACKET_qXfer_uib },
4904   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4905     PACKET_QDisableRandomization },
4906   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4907   { "QTBuffer:size", PACKET_DISABLE,
4908     remote_supported_packet, PACKET_QTBuffer_size},
4909   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4910   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4911   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4912   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4913   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4914     PACKET_qXfer_btrace },
4915   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4916     PACKET_qXfer_btrace_conf },
4917   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4918     PACKET_Qbtrace_conf_bts_size },
4919   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4920   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4921   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4922     PACKET_fork_event_feature },
4923   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4924     PACKET_vfork_event_feature },
4925   { "exec-events", PACKET_DISABLE, remote_supported_packet,
4926     PACKET_exec_event_feature },
4927   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4928     PACKET_Qbtrace_conf_pt_size },
4929   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4930   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4931   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4932 };
4933
4934 static char *remote_support_xml;
4935
4936 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4937
4938 void
4939 register_remote_support_xml (const char *xml)
4940 {
4941 #if defined(HAVE_LIBEXPAT)
4942   if (remote_support_xml == NULL)
4943     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4944   else
4945     {
4946       char *copy = xstrdup (remote_support_xml + 13);
4947       char *p = strtok (copy, ",");
4948
4949       do
4950         {
4951           if (strcmp (p, xml) == 0)
4952             {
4953               /* already there */
4954               xfree (copy);
4955               return;
4956             }
4957         }
4958       while ((p = strtok (NULL, ",")) != NULL);
4959       xfree (copy);
4960
4961       remote_support_xml = reconcat (remote_support_xml,
4962                                      remote_support_xml, ",", xml,
4963                                      (char *) NULL);
4964     }
4965 #endif
4966 }
4967
4968 static void
4969 remote_query_supported_append (std::string *msg, const char *append)
4970 {
4971   if (!msg->empty ())
4972     msg->append (";");
4973   msg->append (append);
4974 }
4975
4976 static void
4977 remote_query_supported (void)
4978 {
4979   struct remote_state *rs = get_remote_state ();
4980   char *next;
4981   int i;
4982   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4983
4984   /* The packet support flags are handled differently for this packet
4985      than for most others.  We treat an error, a disabled packet, and
4986      an empty response identically: any features which must be reported
4987      to be used will be automatically disabled.  An empty buffer
4988      accomplishes this, since that is also the representation for a list
4989      containing no features.  */
4990
4991   rs->buf[0] = 0;
4992   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4993     {
4994       std::string q;
4995
4996       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4997         remote_query_supported_append (&q, "multiprocess+");
4998
4999       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5000         remote_query_supported_append (&q, "swbreak+");
5001       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5002         remote_query_supported_append (&q, "hwbreak+");
5003
5004       remote_query_supported_append (&q, "qRelocInsn+");
5005
5006       if (packet_set_cmd_state (PACKET_fork_event_feature)
5007           != AUTO_BOOLEAN_FALSE)
5008         remote_query_supported_append (&q, "fork-events+");
5009       if (packet_set_cmd_state (PACKET_vfork_event_feature)
5010           != AUTO_BOOLEAN_FALSE)
5011         remote_query_supported_append (&q, "vfork-events+");
5012       if (packet_set_cmd_state (PACKET_exec_event_feature)
5013           != AUTO_BOOLEAN_FALSE)
5014         remote_query_supported_append (&q, "exec-events+");
5015
5016       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5017         remote_query_supported_append (&q, "vContSupported+");
5018
5019       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5020         remote_query_supported_append (&q, "QThreadEvents+");
5021
5022       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5023         remote_query_supported_append (&q, "no-resumed+");
5024
5025       /* Keep this one last to work around a gdbserver <= 7.10 bug in
5026          the qSupported:xmlRegisters=i386 handling.  */
5027       if (remote_support_xml != NULL
5028           && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5029         remote_query_supported_append (&q, remote_support_xml);
5030
5031       q = "qSupported:" + q;
5032       putpkt (q.c_str ());
5033
5034       getpkt (&rs->buf, &rs->buf_size, 0);
5035
5036       /* If an error occured, warn, but do not return - just reset the
5037          buffer to empty and go on to disable features.  */
5038       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5039           == PACKET_ERROR)
5040         {
5041           warning (_("Remote failure reply: %s"), rs->buf);
5042           rs->buf[0] = 0;
5043         }
5044     }
5045
5046   memset (seen, 0, sizeof (seen));
5047
5048   next = rs->buf;
5049   while (*next)
5050     {
5051       enum packet_support is_supported;
5052       char *p, *end, *name_end, *value;
5053
5054       /* First separate out this item from the rest of the packet.  If
5055          there's another item after this, we overwrite the separator
5056          (terminated strings are much easier to work with).  */
5057       p = next;
5058       end = strchr (p, ';');
5059       if (end == NULL)
5060         {
5061           end = p + strlen (p);
5062           next = end;
5063         }
5064       else
5065         {
5066           *end = '\0';
5067           next = end + 1;
5068
5069           if (end == p)
5070             {
5071               warning (_("empty item in \"qSupported\" response"));
5072               continue;
5073             }
5074         }
5075
5076       name_end = strchr (p, '=');
5077       if (name_end)
5078         {
5079           /* This is a name=value entry.  */
5080           is_supported = PACKET_ENABLE;
5081           value = name_end + 1;
5082           *name_end = '\0';
5083         }
5084       else
5085         {
5086           value = NULL;
5087           switch (end[-1])
5088             {
5089             case '+':
5090               is_supported = PACKET_ENABLE;
5091               break;
5092
5093             case '-':
5094               is_supported = PACKET_DISABLE;
5095               break;
5096
5097             case '?':
5098               is_supported = PACKET_SUPPORT_UNKNOWN;
5099               break;
5100
5101             default:
5102               warning (_("unrecognized item \"%s\" "
5103                          "in \"qSupported\" response"), p);
5104               continue;
5105             }
5106           end[-1] = '\0';
5107         }
5108
5109       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5110         if (strcmp (remote_protocol_features[i].name, p) == 0)
5111           {
5112             const struct protocol_feature *feature;
5113
5114             seen[i] = 1;
5115             feature = &remote_protocol_features[i];
5116             feature->func (feature, is_supported, value);
5117             break;
5118           }
5119     }
5120
5121   /* If we increased the packet size, make sure to increase the global
5122      buffer size also.  We delay this until after parsing the entire
5123      qSupported packet, because this is the same buffer we were
5124      parsing.  */
5125   if (rs->buf_size < rs->explicit_packet_size)
5126     {
5127       rs->buf_size = rs->explicit_packet_size;
5128       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5129     }
5130
5131   /* Handle the defaults for unmentioned features.  */
5132   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5133     if (!seen[i])
5134       {
5135         const struct protocol_feature *feature;
5136
5137         feature = &remote_protocol_features[i];
5138         feature->func (feature, feature->default_support, NULL);
5139       }
5140 }
5141
5142 /* Serial QUIT handler for the remote serial descriptor.
5143
5144    Defers handling a Ctrl-C until we're done with the current
5145    command/response packet sequence, unless:
5146
5147    - We're setting up the connection.  Don't send a remote interrupt
5148      request, as we're not fully synced yet.  Quit immediately
5149      instead.
5150
5151    - The target has been resumed in the foreground
5152      (target_terminal::is_ours is false) with a synchronous resume
5153      packet, and we're blocked waiting for the stop reply, thus a
5154      Ctrl-C should be immediately sent to the target.
5155
5156    - We get a second Ctrl-C while still within the same serial read or
5157      write.  In that case the serial is seemingly wedged --- offer to
5158      quit/disconnect.
5159
5160    - We see a second Ctrl-C without target response, after having
5161      previously interrupted the target.  In that case the target/stub
5162      is probably wedged --- offer to quit/disconnect.
5163 */
5164
5165 static void
5166 remote_serial_quit_handler (void)
5167 {
5168   struct remote_state *rs = get_remote_state ();
5169
5170   if (check_quit_flag ())
5171     {
5172       /* If we're starting up, we're not fully synced yet.  Quit
5173          immediately.  */
5174       if (rs->starting_up)
5175         quit ();
5176       else if (rs->got_ctrlc_during_io)
5177         {
5178           if (query (_("The target is not responding to GDB commands.\n"
5179                        "Stop debugging it? ")))
5180             remote_unpush_and_throw ();
5181         }
5182       /* If ^C has already been sent once, offer to disconnect.  */
5183       else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5184         interrupt_query ();
5185       /* All-stop protocol, and blocked waiting for stop reply.  Send
5186          an interrupt request.  */
5187       else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5188         target_interrupt ();
5189       else
5190         rs->got_ctrlc_during_io = 1;
5191     }
5192 }
5193
5194 /* Remove any of the remote.c targets from target stack.  Upper targets depend
5195    on it so remove them first.  */
5196
5197 static void
5198 remote_unpush_target (void)
5199 {
5200   pop_all_targets_at_and_above (process_stratum);
5201 }
5202
5203 static void
5204 remote_unpush_and_throw (void)
5205 {
5206   remote_unpush_target ();
5207   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5208 }
5209
5210 void
5211 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5212 {
5213   struct remote_state *rs = get_remote_state ();
5214
5215   if (name == 0)
5216     error (_("To open a remote debug connection, you need to specify what\n"
5217            "serial device is attached to the remote system\n"
5218            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5219
5220   /* See FIXME above.  */
5221   if (!target_async_permitted)
5222     wait_forever_enabled_p = 1;
5223
5224   /* If we're connected to a running target, target_preopen will kill it.
5225      Ask this question first, before target_preopen has a chance to kill
5226      anything.  */
5227   if (rs->remote_desc != NULL && !have_inferiors ())
5228     {
5229       if (from_tty
5230           && !query (_("Already connected to a remote target.  Disconnect? ")))
5231         error (_("Still connected."));
5232     }
5233
5234   /* Here the possibly existing remote target gets unpushed.  */
5235   target_preopen (from_tty);
5236
5237   /* Make sure we send the passed signals list the next time we resume.  */
5238   xfree (rs->last_pass_packet);
5239   rs->last_pass_packet = NULL;
5240
5241   /* Make sure we send the program signals list the next time we
5242      resume.  */
5243   xfree (rs->last_program_signals_packet);
5244   rs->last_program_signals_packet = NULL;
5245
5246   remote_fileio_reset ();
5247   reopen_exec_file ();
5248   reread_symbols ();
5249
5250   rs->remote_desc = remote_serial_open (name);
5251   if (!rs->remote_desc)
5252     perror_with_name (name);
5253
5254   if (baud_rate != -1)
5255     {
5256       if (serial_setbaudrate (rs->remote_desc, baud_rate))
5257         {
5258           /* The requested speed could not be set.  Error out to
5259              top level after closing remote_desc.  Take care to
5260              set remote_desc to NULL to avoid closing remote_desc
5261              more than once.  */
5262           serial_close (rs->remote_desc);
5263           rs->remote_desc = NULL;
5264           perror_with_name (name);
5265         }
5266     }
5267
5268   serial_setparity (rs->remote_desc, serial_parity);
5269   serial_raw (rs->remote_desc);
5270
5271   /* If there is something sitting in the buffer we might take it as a
5272      response to a command, which would be bad.  */
5273   serial_flush_input (rs->remote_desc);
5274
5275   if (from_tty)
5276     {
5277       puts_filtered ("Remote debugging using ");
5278       puts_filtered (name);
5279       puts_filtered ("\n");
5280     }
5281
5282   remote_target *target
5283     = extended_p ? &extended_remote_ops : &remote_ops;
5284   push_target (target);         /* Switch to using remote target now.  */
5285
5286   /* Register extra event sources in the event loop.  */
5287   remote_async_inferior_event_token
5288     = create_async_event_handler (remote_async_inferior_event_handler,
5289                                   NULL);
5290   rs->notif_state = remote_notif_state_allocate ();
5291
5292   /* Reset the target state; these things will be queried either by
5293      remote_query_supported or as they are needed.  */
5294   reset_all_packet_configs_support ();
5295   rs->cached_wait_status = 0;
5296   rs->explicit_packet_size = 0;
5297   rs->noack_mode = 0;
5298   rs->extended = extended_p;
5299   rs->waiting_for_stop_reply = 0;
5300   rs->ctrlc_pending_p = 0;
5301   rs->got_ctrlc_during_io = 0;
5302
5303   rs->general_thread = not_sent_ptid;
5304   rs->continue_thread = not_sent_ptid;
5305   rs->remote_traceframe_number = -1;
5306
5307   rs->last_resume_exec_dir = EXEC_FORWARD;
5308
5309   /* Probe for ability to use "ThreadInfo" query, as required.  */
5310   rs->use_threadinfo_query = 1;
5311   rs->use_threadextra_query = 1;
5312
5313   rs->readahead_cache.invalidate ();
5314
5315   if (target_async_permitted)
5316     {
5317       /* FIXME: cagney/1999-09-23: During the initial connection it is
5318          assumed that the target is already ready and able to respond to
5319          requests.  Unfortunately remote_start_remote() eventually calls
5320          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
5321          around this.  Eventually a mechanism that allows
5322          wait_for_inferior() to expect/get timeouts will be
5323          implemented.  */
5324       wait_forever_enabled_p = 0;
5325     }
5326
5327   /* First delete any symbols previously loaded from shared libraries.  */
5328   no_shared_libraries (NULL, 0);
5329
5330   /* Start afresh.  */
5331   init_thread_list ();
5332
5333   /* Start the remote connection.  If error() or QUIT, discard this
5334      target (we'd otherwise be in an inconsistent state) and then
5335      propogate the error on up the exception chain.  This ensures that
5336      the caller doesn't stumble along blindly assuming that the
5337      function succeeded.  The CLI doesn't have this problem but other
5338      UI's, such as MI do.
5339
5340      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5341      this function should return an error indication letting the
5342      caller restore the previous state.  Unfortunately the command
5343      ``target remote'' is directly wired to this function making that
5344      impossible.  On a positive note, the CLI side of this problem has
5345      been fixed - the function set_cmd_context() makes it possible for
5346      all the ``target ....'' commands to share a common callback
5347      function.  See cli-dump.c.  */
5348   {
5349
5350     TRY
5351       {
5352         target->start_remote (from_tty, extended_p);
5353       }
5354     CATCH (ex, RETURN_MASK_ALL)
5355       {
5356         /* Pop the partially set up target - unless something else did
5357            already before throwing the exception.  */
5358         if (rs->remote_desc != NULL)
5359           remote_unpush_target ();
5360         if (target_async_permitted)
5361           wait_forever_enabled_p = 1;
5362         throw_exception (ex);
5363       }
5364     END_CATCH
5365   }
5366
5367   remote_btrace_reset ();
5368
5369   if (target_async_permitted)
5370     wait_forever_enabled_p = 1;
5371 }
5372
5373 /* Detach the specified process.  */
5374
5375 static void
5376 remote_detach_pid (int pid)
5377 {
5378   struct remote_state *rs = get_remote_state ();
5379
5380   if (remote_multi_process_p (rs))
5381     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5382   else
5383     strcpy (rs->buf, "D");
5384
5385   putpkt (rs->buf);
5386   getpkt (&rs->buf, &rs->buf_size, 0);
5387
5388   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5389     ;
5390   else if (rs->buf[0] == '\0')
5391     error (_("Remote doesn't know how to detach"));
5392   else
5393     error (_("Can't detach process."));
5394 }
5395
5396 /* This detaches a program to which we previously attached, using
5397    inferior_ptid to identify the process.  After this is done, GDB
5398    can be used to debug some other program.  We better not have left
5399    any breakpoints in the target program or it'll die when it hits
5400    one.  */
5401
5402 static void
5403 remote_detach_1 (int from_tty, inferior *inf)
5404 {
5405   int pid = ptid_get_pid (inferior_ptid);
5406   struct remote_state *rs = get_remote_state ();
5407   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5408   int is_fork_parent;
5409
5410   if (!target_has_execution)
5411     error (_("No process to detach from."));
5412
5413   target_announce_detach (from_tty);
5414
5415   /* Tell the remote target to detach.  */
5416   remote_detach_pid (pid);
5417
5418   /* Exit only if this is the only active inferior.  */
5419   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5420     puts_filtered (_("Ending remote debugging.\n"));
5421
5422   /* Check to see if we are detaching a fork parent.  Note that if we
5423      are detaching a fork child, tp == NULL.  */
5424   is_fork_parent = (tp != NULL
5425                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5426
5427   /* If doing detach-on-fork, we don't mourn, because that will delete
5428      breakpoints that should be available for the followed inferior.  */
5429   if (!is_fork_parent)
5430     {
5431       /* Save the pid as a string before mourning, since that will
5432          unpush the remote target, and we need the string after.  */
5433       std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5434
5435       target_mourn_inferior (inferior_ptid);
5436       if (print_inferior_events)
5437         printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5438                            inf->num, infpid.c_str ());
5439     }
5440   else
5441     {
5442       inferior_ptid = null_ptid;
5443       detach_inferior (pid);
5444     }
5445 }
5446
5447 void
5448 remote_target::detach (inferior *inf, int from_tty)
5449 {
5450   remote_detach_1 (from_tty, inf);
5451 }
5452
5453 void
5454 extended_remote_target::detach (inferior *inf, int from_tty)
5455 {
5456   remote_detach_1 (from_tty, inf);
5457 }
5458
5459 /* Target follow-fork function for remote targets.  On entry, and
5460    at return, the current inferior is the fork parent.
5461
5462    Note that although this is currently only used for extended-remote,
5463    it is named remote_follow_fork in anticipation of using it for the
5464    remote target as well.  */
5465
5466 int
5467 remote_target::follow_fork (int follow_child, int detach_fork)
5468 {
5469   struct remote_state *rs = get_remote_state ();
5470   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5471
5472   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5473       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5474     {
5475       /* When following the parent and detaching the child, we detach
5476          the child here.  For the case of following the child and
5477          detaching the parent, the detach is done in the target-
5478          independent follow fork code in infrun.c.  We can't use
5479          target_detach when detaching an unfollowed child because
5480          the client side doesn't know anything about the child.  */
5481       if (detach_fork && !follow_child)
5482         {
5483           /* Detach the fork child.  */
5484           ptid_t child_ptid;
5485           pid_t child_pid;
5486
5487           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5488           child_pid = ptid_get_pid (child_ptid);
5489
5490           remote_detach_pid (child_pid);
5491         }
5492     }
5493   return 0;
5494 }
5495
5496 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5497    in the program space of the new inferior.  On entry and at return the
5498    current inferior is the exec'ing inferior.  INF is the new exec'd
5499    inferior, which may be the same as the exec'ing inferior unless
5500    follow-exec-mode is "new".  */
5501
5502 void
5503 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5504 {
5505   /* We know that this is a target file name, so if it has the "target:"
5506      prefix we strip it off before saving it in the program space.  */
5507   if (is_target_filename (execd_pathname))
5508     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5509
5510   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5511 }
5512
5513 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5514
5515 void
5516 remote_target::disconnect (const char *args, int from_tty)
5517 {
5518   if (args)
5519     error (_("Argument given to \"disconnect\" when remotely debugging."));
5520
5521   /* Make sure we unpush even the extended remote targets.  Calling
5522      target_mourn_inferior won't unpush, and remote_mourn won't
5523      unpush if there is more than one inferior left.  */
5524   unpush_target (this);
5525   generic_mourn_inferior ();
5526
5527   if (from_tty)
5528     puts_filtered ("Ending remote debugging.\n");
5529 }
5530
5531 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5532    be chatty about it.  */
5533
5534 void
5535 extended_remote_target::attach (const char *args, int from_tty)
5536 {
5537   struct remote_state *rs = get_remote_state ();
5538   int pid;
5539   char *wait_status = NULL;
5540
5541   pid = parse_pid_to_attach (args);
5542
5543   /* Remote PID can be freely equal to getpid, do not check it here the same
5544      way as in other targets.  */
5545
5546   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5547     error (_("This target does not support attaching to a process"));
5548
5549   if (from_tty)
5550     {
5551       char *exec_file = get_exec_file (0);
5552
5553       if (exec_file)
5554         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5555                            target_pid_to_str (pid_to_ptid (pid)));
5556       else
5557         printf_unfiltered (_("Attaching to %s\n"),
5558                            target_pid_to_str (pid_to_ptid (pid)));
5559
5560       gdb_flush (gdb_stdout);
5561     }
5562
5563   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5564   putpkt (rs->buf);
5565   getpkt (&rs->buf, &rs->buf_size, 0);
5566
5567   switch (packet_ok (rs->buf,
5568                      &remote_protocol_packets[PACKET_vAttach]))
5569     {
5570     case PACKET_OK:
5571       if (!target_is_non_stop_p ())
5572         {
5573           /* Save the reply for later.  */
5574           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5575           strcpy (wait_status, rs->buf);
5576         }
5577       else if (strcmp (rs->buf, "OK") != 0)
5578         error (_("Attaching to %s failed with: %s"),
5579                target_pid_to_str (pid_to_ptid (pid)),
5580                rs->buf);
5581       break;
5582     case PACKET_UNKNOWN:
5583       error (_("This target does not support attaching to a process"));
5584     default:
5585       error (_("Attaching to %s failed"),
5586              target_pid_to_str (pid_to_ptid (pid)));
5587     }
5588
5589   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5590
5591   inferior_ptid = pid_to_ptid (pid);
5592
5593   if (target_is_non_stop_p ())
5594     {
5595       struct thread_info *thread;
5596
5597       /* Get list of threads.  */
5598       update_thread_list ();
5599
5600       thread = first_thread_of_process (pid);
5601       if (thread)
5602         inferior_ptid = thread->ptid;
5603       else
5604         inferior_ptid = pid_to_ptid (pid);
5605
5606       /* Invalidate our notion of the remote current thread.  */
5607       record_currthread (rs, minus_one_ptid);
5608     }
5609   else
5610     {
5611       /* Now, if we have thread information, update inferior_ptid.  */
5612       inferior_ptid = remote_current_thread (inferior_ptid);
5613
5614       /* Add the main thread to the thread list.  */
5615       thread_info *thr = add_thread_silent (inferior_ptid);
5616       /* Don't consider the thread stopped until we've processed the
5617          saved stop reply.  */
5618       set_executing (thr->ptid, true);
5619     }
5620
5621   /* Next, if the target can specify a description, read it.  We do
5622      this before anything involving memory or registers.  */
5623   target_find_description ();
5624
5625   if (!target_is_non_stop_p ())
5626     {
5627       /* Use the previously fetched status.  */
5628       gdb_assert (wait_status != NULL);
5629
5630       if (target_can_async_p ())
5631         {
5632           struct notif_event *reply
5633             =  remote_notif_parse (&notif_client_stop, wait_status);
5634
5635           push_stop_reply ((struct stop_reply *) reply);
5636
5637           target_async (1);
5638         }
5639       else
5640         {
5641           gdb_assert (wait_status != NULL);
5642           strcpy (rs->buf, wait_status);
5643           rs->cached_wait_status = 1;
5644         }
5645     }
5646   else
5647     gdb_assert (wait_status == NULL);
5648 }
5649
5650 /* Implementation of the to_post_attach method.  */
5651
5652 void
5653 extended_remote_target::post_attach (int pid)
5654 {
5655   /* Get text, data & bss offsets.  */
5656   get_offsets ();
5657
5658   /* In certain cases GDB might not have had the chance to start
5659      symbol lookup up until now.  This could happen if the debugged
5660      binary is not using shared libraries, the vsyscall page is not
5661      present (on Linux) and the binary itself hadn't changed since the
5662      debugging process was started.  */
5663   if (symfile_objfile != NULL)
5664     remote_check_symbols();
5665 }
5666
5667 \f
5668 /* Check for the availability of vCont.  This function should also check
5669    the response.  */
5670
5671 static void
5672 remote_vcont_probe (struct remote_state *rs)
5673 {
5674   char *buf;
5675
5676   strcpy (rs->buf, "vCont?");
5677   putpkt (rs->buf);
5678   getpkt (&rs->buf, &rs->buf_size, 0);
5679   buf = rs->buf;
5680
5681   /* Make sure that the features we assume are supported.  */
5682   if (startswith (buf, "vCont"))
5683     {
5684       char *p = &buf[5];
5685       int support_c, support_C;
5686
5687       rs->supports_vCont.s = 0;
5688       rs->supports_vCont.S = 0;
5689       support_c = 0;
5690       support_C = 0;
5691       rs->supports_vCont.t = 0;
5692       rs->supports_vCont.r = 0;
5693       while (p && *p == ';')
5694         {
5695           p++;
5696           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5697             rs->supports_vCont.s = 1;
5698           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5699             rs->supports_vCont.S = 1;
5700           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5701             support_c = 1;
5702           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5703             support_C = 1;
5704           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5705             rs->supports_vCont.t = 1;
5706           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5707             rs->supports_vCont.r = 1;
5708
5709           p = strchr (p, ';');
5710         }
5711
5712       /* If c, and C are not all supported, we can't use vCont.  Clearing
5713          BUF will make packet_ok disable the packet.  */
5714       if (!support_c || !support_C)
5715         buf[0] = 0;
5716     }
5717
5718   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5719 }
5720
5721 /* Helper function for building "vCont" resumptions.  Write a
5722    resumption to P.  ENDP points to one-passed-the-end of the buffer
5723    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5724    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5725    resumed thread should be single-stepped and/or signalled.  If PTID
5726    equals minus_one_ptid, then all threads are resumed; if PTID
5727    represents a process, then all threads of the process are resumed;
5728    the thread to be stepped and/or signalled is given in the global
5729    INFERIOR_PTID.  */
5730
5731 static char *
5732 append_resumption (char *p, char *endp,
5733                    ptid_t ptid, int step, enum gdb_signal siggnal)
5734 {
5735   struct remote_state *rs = get_remote_state ();
5736
5737   if (step && siggnal != GDB_SIGNAL_0)
5738     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5739   else if (step
5740            /* GDB is willing to range step.  */
5741            && use_range_stepping
5742            /* Target supports range stepping.  */
5743            && rs->supports_vCont.r
5744            /* We don't currently support range stepping multiple
5745               threads with a wildcard (though the protocol allows it,
5746               so stubs shouldn't make an active effort to forbid
5747               it).  */
5748            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5749     {
5750       struct thread_info *tp;
5751
5752       if (ptid_equal (ptid, minus_one_ptid))
5753         {
5754           /* If we don't know about the target thread's tid, then
5755              we're resuming magic_null_ptid (see caller).  */
5756           tp = find_thread_ptid (magic_null_ptid);
5757         }
5758       else
5759         tp = find_thread_ptid (ptid);
5760       gdb_assert (tp != NULL);
5761
5762       if (tp->control.may_range_step)
5763         {
5764           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5765
5766           p += xsnprintf (p, endp - p, ";r%s,%s",
5767                           phex_nz (tp->control.step_range_start,
5768                                    addr_size),
5769                           phex_nz (tp->control.step_range_end,
5770                                    addr_size));
5771         }
5772       else
5773         p += xsnprintf (p, endp - p, ";s");
5774     }
5775   else if (step)
5776     p += xsnprintf (p, endp - p, ";s");
5777   else if (siggnal != GDB_SIGNAL_0)
5778     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5779   else
5780     p += xsnprintf (p, endp - p, ";c");
5781
5782   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5783     {
5784       ptid_t nptid;
5785
5786       /* All (-1) threads of process.  */
5787       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5788
5789       p += xsnprintf (p, endp - p, ":");
5790       p = write_ptid (p, endp, nptid);
5791     }
5792   else if (!ptid_equal (ptid, minus_one_ptid))
5793     {
5794       p += xsnprintf (p, endp - p, ":");
5795       p = write_ptid (p, endp, ptid);
5796     }
5797
5798   return p;
5799 }
5800
5801 /* Clear the thread's private info on resume.  */
5802
5803 static void
5804 resume_clear_thread_private_info (struct thread_info *thread)
5805 {
5806   if (thread->priv != NULL)
5807     {
5808       remote_thread_info *priv = get_remote_thread_info (thread);
5809
5810       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5811       priv->watch_data_address = 0;
5812     }
5813 }
5814
5815 /* Append a vCont continue-with-signal action for threads that have a
5816    non-zero stop signal.  */
5817
5818 static char *
5819 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5820 {
5821   struct thread_info *thread;
5822
5823   ALL_NON_EXITED_THREADS (thread)
5824     if (ptid_match (thread->ptid, ptid)
5825         && !ptid_equal (inferior_ptid, thread->ptid)
5826         && thread->suspend.stop_signal != GDB_SIGNAL_0)
5827       {
5828         p = append_resumption (p, endp, thread->ptid,
5829                                0, thread->suspend.stop_signal);
5830         thread->suspend.stop_signal = GDB_SIGNAL_0;
5831         resume_clear_thread_private_info (thread);
5832       }
5833
5834   return p;
5835 }
5836
5837 /* Set the target running, using the packets that use Hc
5838    (c/s/C/S).  */
5839
5840 static void
5841 remote_resume_with_hc (struct target_ops *ops,
5842                        ptid_t ptid, int step, enum gdb_signal siggnal)
5843 {
5844   struct remote_state *rs = get_remote_state ();
5845   struct thread_info *thread;
5846   char *buf;
5847
5848   rs->last_sent_signal = siggnal;
5849   rs->last_sent_step = step;
5850
5851   /* The c/s/C/S resume packets use Hc, so set the continue
5852      thread.  */
5853   if (ptid_equal (ptid, minus_one_ptid))
5854     set_continue_thread (any_thread_ptid);
5855   else
5856     set_continue_thread (ptid);
5857
5858   ALL_NON_EXITED_THREADS (thread)
5859     resume_clear_thread_private_info (thread);
5860
5861   buf = rs->buf;
5862   if (execution_direction == EXEC_REVERSE)
5863     {
5864       /* We don't pass signals to the target in reverse exec mode.  */
5865       if (info_verbose && siggnal != GDB_SIGNAL_0)
5866         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5867                  siggnal);
5868
5869       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5870         error (_("Remote reverse-step not supported."));
5871       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5872         error (_("Remote reverse-continue not supported."));
5873
5874       strcpy (buf, step ? "bs" : "bc");
5875     }
5876   else if (siggnal != GDB_SIGNAL_0)
5877     {
5878       buf[0] = step ? 'S' : 'C';
5879       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5880       buf[2] = tohex (((int) siggnal) & 0xf);
5881       buf[3] = '\0';
5882     }
5883   else
5884     strcpy (buf, step ? "s" : "c");
5885
5886   putpkt (buf);
5887 }
5888
5889 /* Resume the remote inferior by using a "vCont" packet.  The thread
5890    to be resumed is PTID; STEP and SIGGNAL indicate whether the
5891    resumed thread should be single-stepped and/or signalled.  If PTID
5892    equals minus_one_ptid, then all threads are resumed; the thread to
5893    be stepped and/or signalled is given in the global INFERIOR_PTID.
5894    This function returns non-zero iff it resumes the inferior.
5895
5896    This function issues a strict subset of all possible vCont commands
5897    at the moment.  */
5898
5899 static int
5900 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5901 {
5902   struct remote_state *rs = get_remote_state ();
5903   char *p;
5904   char *endp;
5905
5906   /* No reverse execution actions defined for vCont.  */
5907   if (execution_direction == EXEC_REVERSE)
5908     return 0;
5909
5910   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5911     remote_vcont_probe (rs);
5912
5913   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5914     return 0;
5915
5916   p = rs->buf;
5917   endp = rs->buf + get_remote_packet_size ();
5918
5919   /* If we could generate a wider range of packets, we'd have to worry
5920      about overflowing BUF.  Should there be a generic
5921      "multi-part-packet" packet?  */
5922
5923   p += xsnprintf (p, endp - p, "vCont");
5924
5925   if (ptid_equal (ptid, magic_null_ptid))
5926     {
5927       /* MAGIC_NULL_PTID means that we don't have any active threads,
5928          so we don't have any TID numbers the inferior will
5929          understand.  Make sure to only send forms that do not specify
5930          a TID.  */
5931       append_resumption (p, endp, minus_one_ptid, step, siggnal);
5932     }
5933   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5934     {
5935       /* Resume all threads (of all processes, or of a single
5936          process), with preference for INFERIOR_PTID.  This assumes
5937          inferior_ptid belongs to the set of all threads we are about
5938          to resume.  */
5939       if (step || siggnal != GDB_SIGNAL_0)
5940         {
5941           /* Step inferior_ptid, with or without signal.  */
5942           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5943         }
5944
5945       /* Also pass down any pending signaled resumption for other
5946          threads not the current.  */
5947       p = append_pending_thread_resumptions (p, endp, ptid);
5948
5949       /* And continue others without a signal.  */
5950       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5951     }
5952   else
5953     {
5954       /* Scheduler locking; resume only PTID.  */
5955       append_resumption (p, endp, ptid, step, siggnal);
5956     }
5957
5958   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5959   putpkt (rs->buf);
5960
5961   if (target_is_non_stop_p ())
5962     {
5963       /* In non-stop, the stub replies to vCont with "OK".  The stop
5964          reply will be reported asynchronously by means of a `%Stop'
5965          notification.  */
5966       getpkt (&rs->buf, &rs->buf_size, 0);
5967       if (strcmp (rs->buf, "OK") != 0)
5968         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5969     }
5970
5971   return 1;
5972 }
5973
5974 /* Tell the remote machine to resume.  */
5975
5976 void
5977 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5978 {
5979   struct remote_state *rs = get_remote_state ();
5980
5981   /* When connected in non-stop mode, the core resumes threads
5982      individually.  Resuming remote threads directly in target_resume
5983      would thus result in sending one packet per thread.  Instead, to
5984      minimize roundtrip latency, here we just store the resume
5985      request; the actual remote resumption will be done in
5986      target_commit_resume / remote_commit_resume, where we'll be able
5987      to do vCont action coalescing.  */
5988   if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
5989     {
5990       remote_thread_info *remote_thr;
5991
5992       if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5993         remote_thr = get_remote_thread_info (inferior_ptid);
5994       else
5995         remote_thr = get_remote_thread_info (ptid);
5996
5997       remote_thr->last_resume_step = step;
5998       remote_thr->last_resume_sig = siggnal;
5999       return;
6000     }
6001
6002   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6003      (explained in remote-notif.c:handle_notification) so
6004      remote_notif_process is not called.  We need find a place where
6005      it is safe to start a 'vNotif' sequence.  It is good to do it
6006      before resuming inferior, because inferior was stopped and no RSP
6007      traffic at that moment.  */
6008   if (!target_is_non_stop_p ())
6009     remote_notif_process (rs->notif_state, &notif_client_stop);
6010
6011   rs->last_resume_exec_dir = ::execution_direction;
6012
6013   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
6014   if (!remote_resume_with_vcont (ptid, step, siggnal))
6015     remote_resume_with_hc (this, ptid, step, siggnal);
6016
6017   /* We are about to start executing the inferior, let's register it
6018      with the event loop.  NOTE: this is the one place where all the
6019      execution commands end up.  We could alternatively do this in each
6020      of the execution commands in infcmd.c.  */
6021   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6022      into infcmd.c in order to allow inferior function calls to work
6023      NOT asynchronously.  */
6024   if (target_can_async_p ())
6025     target_async (1);
6026
6027   /* We've just told the target to resume.  The remote server will
6028      wait for the inferior to stop, and then send a stop reply.  In
6029      the mean time, we can't start another command/query ourselves
6030      because the stub wouldn't be ready to process it.  This applies
6031      only to the base all-stop protocol, however.  In non-stop (which
6032      only supports vCont), the stub replies with an "OK", and is
6033      immediate able to process further serial input.  */
6034   if (!target_is_non_stop_p ())
6035     rs->waiting_for_stop_reply = 1;
6036 }
6037
6038 static void check_pending_events_prevent_wildcard_vcont
6039   (int *may_global_wildcard_vcont);
6040 static int is_pending_fork_parent_thread (struct thread_info *thread);
6041
6042 /* Private per-inferior info for target remote processes.  */
6043
6044 struct remote_inferior : public private_inferior
6045 {
6046   /* Whether we can send a wildcard vCont for this process.  */
6047   bool may_wildcard_vcont = true;
6048 };
6049
6050 /* Get the remote private inferior data associated to INF.  */
6051
6052 static remote_inferior *
6053 get_remote_inferior (inferior *inf)
6054 {
6055   if (inf->priv == NULL)
6056     inf->priv.reset (new remote_inferior);
6057
6058   return static_cast<remote_inferior *> (inf->priv.get ());
6059 }
6060
6061 /* Structure used to track the construction of a vCont packet in the
6062    outgoing packet buffer.  This is used to send multiple vCont
6063    packets if we have more actions than would fit a single packet.  */
6064
6065 struct vcont_builder
6066 {
6067   /* Pointer to the first action.  P points here if no action has been
6068      appended yet.  */
6069   char *first_action;
6070
6071   /* Where the next action will be appended.  */
6072   char *p;
6073
6074   /* The end of the buffer.  Must never write past this.  */
6075   char *endp;
6076 };
6077
6078 /* Prepare the outgoing buffer for a new vCont packet.  */
6079
6080 static void
6081 vcont_builder_restart (struct vcont_builder *builder)
6082 {
6083   struct remote_state *rs = get_remote_state ();
6084
6085   builder->p = rs->buf;
6086   builder->endp = rs->buf + get_remote_packet_size ();
6087   builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
6088   builder->first_action = builder->p;
6089 }
6090
6091 /* If the vCont packet being built has any action, send it to the
6092    remote end.  */
6093
6094 static void
6095 vcont_builder_flush (struct vcont_builder *builder)
6096 {
6097   struct remote_state *rs;
6098
6099   if (builder->p == builder->first_action)
6100     return;
6101
6102   rs = get_remote_state ();
6103   putpkt (rs->buf);
6104   getpkt (&rs->buf, &rs->buf_size, 0);
6105   if (strcmp (rs->buf, "OK") != 0)
6106     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6107 }
6108
6109 /* The largest action is range-stepping, with its two addresses.  This
6110    is more than sufficient.  If a new, bigger action is created, it'll
6111    quickly trigger a failed assertion in append_resumption (and we'll
6112    just bump this).  */
6113 #define MAX_ACTION_SIZE 200
6114
6115 /* Append a new vCont action in the outgoing packet being built.  If
6116    the action doesn't fit the packet along with previous actions, push
6117    what we've got so far to the remote end and start over a new vCont
6118    packet (with the new action).  */
6119
6120 static void
6121 vcont_builder_push_action (struct vcont_builder *builder,
6122                            ptid_t ptid, int step, enum gdb_signal siggnal)
6123 {
6124   char buf[MAX_ACTION_SIZE + 1];
6125   char *endp;
6126   size_t rsize;
6127
6128   endp = append_resumption (buf, buf + sizeof (buf),
6129                             ptid, step, siggnal);
6130
6131   /* Check whether this new action would fit in the vCont packet along
6132      with previous actions.  If not, send what we've got so far and
6133      start a new vCont packet.  */
6134   rsize = endp - buf;
6135   if (rsize > builder->endp - builder->p)
6136     {
6137       vcont_builder_flush (builder);
6138       vcont_builder_restart (builder);
6139
6140       /* Should now fit.  */
6141       gdb_assert (rsize <= builder->endp - builder->p);
6142     }
6143
6144   memcpy (builder->p, buf, rsize);
6145   builder->p += rsize;
6146   *builder->p = '\0';
6147 }
6148
6149 /* to_commit_resume implementation.  */
6150
6151 void
6152 remote_target::commit_resume ()
6153 {
6154   struct inferior *inf;
6155   struct thread_info *tp;
6156   int any_process_wildcard;
6157   int may_global_wildcard_vcont;
6158   struct vcont_builder vcont_builder;
6159
6160   /* If connected in all-stop mode, we'd send the remote resume
6161      request directly from remote_resume.  Likewise if
6162      reverse-debugging, as there are no defined vCont actions for
6163      reverse execution.  */
6164   if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6165     return;
6166
6167   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6168      instead of resuming all threads of each process individually.
6169      However, if any thread of a process must remain halted, we can't
6170      send wildcard resumes and must send one action per thread.
6171
6172      Care must be taken to not resume threads/processes the server
6173      side already told us are stopped, but the core doesn't know about
6174      yet, because the events are still in the vStopped notification
6175      queue.  For example:
6176
6177        #1 => vCont s:p1.1;c
6178        #2 <= OK
6179        #3 <= %Stopped T05 p1.1
6180        #4 => vStopped
6181        #5 <= T05 p1.2
6182        #6 => vStopped
6183        #7 <= OK
6184        #8 (infrun handles the stop for p1.1 and continues stepping)
6185        #9 => vCont s:p1.1;c
6186
6187      The last vCont above would resume thread p1.2 by mistake, because
6188      the server has no idea that the event for p1.2 had not been
6189      handled yet.
6190
6191      The server side must similarly ignore resume actions for the
6192      thread that has a pending %Stopped notification (and any other
6193      threads with events pending), until GDB acks the notification
6194      with vStopped.  Otherwise, e.g., the following case is
6195      mishandled:
6196
6197        #1 => g  (or any other packet)
6198        #2 <= [registers]
6199        #3 <= %Stopped T05 p1.2
6200        #4 => vCont s:p1.1;c
6201        #5 <= OK
6202
6203      Above, the server must not resume thread p1.2.  GDB can't know
6204      that p1.2 stopped until it acks the %Stopped notification, and
6205      since from GDB's perspective all threads should be running, it
6206      sends a "c" action.
6207
6208      Finally, special care must also be given to handling fork/vfork
6209      events.  A (v)fork event actually tells us that two processes
6210      stopped -- the parent and the child.  Until we follow the fork,
6211      we must not resume the child.  Therefore, if we have a pending
6212      fork follow, we must not send a global wildcard resume action
6213      (vCont;c).  We can still send process-wide wildcards though.  */
6214
6215   /* Start by assuming a global wildcard (vCont;c) is possible.  */
6216   may_global_wildcard_vcont = 1;
6217
6218   /* And assume every process is individually wildcard-able too.  */
6219   ALL_NON_EXITED_INFERIORS (inf)
6220     {
6221       remote_inferior *priv = get_remote_inferior (inf);
6222
6223       priv->may_wildcard_vcont = true;
6224     }
6225
6226   /* Check for any pending events (not reported or processed yet) and
6227      disable process and global wildcard resumes appropriately.  */
6228   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6229
6230   ALL_NON_EXITED_THREADS (tp)
6231     {
6232       /* If a thread of a process is not meant to be resumed, then we
6233          can't wildcard that process.  */
6234       if (!tp->executing)
6235         {
6236           get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6237
6238           /* And if we can't wildcard a process, we can't wildcard
6239              everything either.  */
6240           may_global_wildcard_vcont = 0;
6241           continue;
6242         }
6243
6244       /* If a thread is the parent of an unfollowed fork, then we
6245          can't do a global wildcard, as that would resume the fork
6246          child.  */
6247       if (is_pending_fork_parent_thread (tp))
6248         may_global_wildcard_vcont = 0;
6249     }
6250
6251   /* Now let's build the vCont packet(s).  Actions must be appended
6252      from narrower to wider scopes (thread -> process -> global).  If
6253      we end up with too many actions for a single packet vcont_builder
6254      flushes the current vCont packet to the remote side and starts a
6255      new one.  */
6256   vcont_builder_restart (&vcont_builder);
6257
6258   /* Threads first.  */
6259   ALL_NON_EXITED_THREADS (tp)
6260     {
6261       remote_thread_info *remote_thr = get_remote_thread_info (tp);
6262
6263       if (!tp->executing || remote_thr->vcont_resumed)
6264         continue;
6265
6266       gdb_assert (!thread_is_in_step_over_chain (tp));
6267
6268       if (!remote_thr->last_resume_step
6269           && remote_thr->last_resume_sig == GDB_SIGNAL_0
6270           && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6271         {
6272           /* We'll send a wildcard resume instead.  */
6273           remote_thr->vcont_resumed = 1;
6274           continue;
6275         }
6276
6277       vcont_builder_push_action (&vcont_builder, tp->ptid,
6278                                  remote_thr->last_resume_step,
6279                                  remote_thr->last_resume_sig);
6280       remote_thr->vcont_resumed = 1;
6281     }
6282
6283   /* Now check whether we can send any process-wide wildcard.  This is
6284      to avoid sending a global wildcard in the case nothing is
6285      supposed to be resumed.  */
6286   any_process_wildcard = 0;
6287
6288   ALL_NON_EXITED_INFERIORS (inf)
6289     {
6290       if (get_remote_inferior (inf)->may_wildcard_vcont)
6291         {
6292           any_process_wildcard = 1;
6293           break;
6294         }
6295     }
6296
6297   if (any_process_wildcard)
6298     {
6299       /* If all processes are wildcard-able, then send a single "c"
6300          action, otherwise, send an "all (-1) threads of process"
6301          continue action for each running process, if any.  */
6302       if (may_global_wildcard_vcont)
6303         {
6304           vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6305                                      0, GDB_SIGNAL_0);
6306         }
6307       else
6308         {
6309           ALL_NON_EXITED_INFERIORS (inf)
6310             {
6311               if (get_remote_inferior (inf)->may_wildcard_vcont)
6312                 {
6313                   vcont_builder_push_action (&vcont_builder,
6314                                              pid_to_ptid (inf->pid),
6315                                              0, GDB_SIGNAL_0);
6316                 }
6317             }
6318         }
6319     }
6320
6321   vcont_builder_flush (&vcont_builder);
6322 }
6323
6324 \f
6325
6326 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
6327    thread, all threads of a remote process, or all threads of all
6328    processes.  */
6329
6330 static void
6331 remote_stop_ns (ptid_t ptid)
6332 {
6333   struct remote_state *rs = get_remote_state ();
6334   char *p = rs->buf;
6335   char *endp = rs->buf + get_remote_packet_size ();
6336
6337   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6338     remote_vcont_probe (rs);
6339
6340   if (!rs->supports_vCont.t)
6341     error (_("Remote server does not support stopping threads"));
6342
6343   if (ptid_equal (ptid, minus_one_ptid)
6344       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6345     p += xsnprintf (p, endp - p, "vCont;t");
6346   else
6347     {
6348       ptid_t nptid;
6349
6350       p += xsnprintf (p, endp - p, "vCont;t:");
6351
6352       if (ptid_is_pid (ptid))
6353           /* All (-1) threads of process.  */
6354         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6355       else
6356         {
6357           /* Small optimization: if we already have a stop reply for
6358              this thread, no use in telling the stub we want this
6359              stopped.  */
6360           if (peek_stop_reply (ptid))
6361             return;
6362
6363           nptid = ptid;
6364         }
6365
6366       write_ptid (p, endp, nptid);
6367     }
6368
6369   /* In non-stop, we get an immediate OK reply.  The stop reply will
6370      come in asynchronously by notification.  */
6371   putpkt (rs->buf);
6372   getpkt (&rs->buf, &rs->buf_size, 0);
6373   if (strcmp (rs->buf, "OK") != 0)
6374     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6375 }
6376
6377 /* All-stop version of target_interrupt.  Sends a break or a ^C to
6378    interrupt the remote target.  It is undefined which thread of which
6379    process reports the interrupt.  */
6380
6381 static void
6382 remote_interrupt_as (void)
6383 {
6384   struct remote_state *rs = get_remote_state ();
6385
6386   rs->ctrlc_pending_p = 1;
6387
6388   /* If the inferior is stopped already, but the core didn't know
6389      about it yet, just ignore the request.  The cached wait status
6390      will be collected in remote_wait.  */
6391   if (rs->cached_wait_status)
6392     return;
6393
6394   /* Send interrupt_sequence to remote target.  */
6395   send_interrupt_sequence ();
6396 }
6397
6398 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
6399    the remote target.  It is undefined which thread of which process
6400    reports the interrupt.  Throws an error if the packet is not
6401    supported by the server.  */
6402
6403 static void
6404 remote_interrupt_ns (void)
6405 {
6406   struct remote_state *rs = get_remote_state ();
6407   char *p = rs->buf;
6408   char *endp = rs->buf + get_remote_packet_size ();
6409
6410   xsnprintf (p, endp - p, "vCtrlC");
6411
6412   /* In non-stop, we get an immediate OK reply.  The stop reply will
6413      come in asynchronously by notification.  */
6414   putpkt (rs->buf);
6415   getpkt (&rs->buf, &rs->buf_size, 0);
6416
6417   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6418     {
6419     case PACKET_OK:
6420       break;
6421     case PACKET_UNKNOWN:
6422       error (_("No support for interrupting the remote target."));
6423     case PACKET_ERROR:
6424       error (_("Interrupting target failed: %s"), rs->buf);
6425     }
6426 }
6427
6428 /* Implement the to_stop function for the remote targets.  */
6429
6430 void
6431 remote_target::stop (ptid_t ptid)
6432 {
6433   if (remote_debug)
6434     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6435
6436   if (target_is_non_stop_p ())
6437     remote_stop_ns (ptid);
6438   else
6439     {
6440       /* We don't currently have a way to transparently pause the
6441          remote target in all-stop mode.  Interrupt it instead.  */
6442       remote_interrupt_as ();
6443     }
6444 }
6445
6446 /* Implement the to_interrupt function for the remote targets.  */
6447
6448 void
6449 remote_target::interrupt ()
6450 {
6451   if (remote_debug)
6452     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6453
6454   if (target_is_non_stop_p ())
6455     remote_interrupt_ns ();
6456   else
6457     remote_interrupt_as ();
6458 }
6459
6460 /* Implement the to_pass_ctrlc function for the remote targets.  */
6461
6462 void
6463 remote_target::pass_ctrlc ()
6464 {
6465   struct remote_state *rs = get_remote_state ();
6466
6467   if (remote_debug)
6468     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6469
6470   /* If we're starting up, we're not fully synced yet.  Quit
6471      immediately.  */
6472   if (rs->starting_up)
6473     quit ();
6474   /* If ^C has already been sent once, offer to disconnect.  */
6475   else if (rs->ctrlc_pending_p)
6476     interrupt_query ();
6477   else
6478     target_interrupt ();
6479 }
6480
6481 /* Ask the user what to do when an interrupt is received.  */
6482
6483 static void
6484 interrupt_query (void)
6485 {
6486   struct remote_state *rs = get_remote_state ();
6487
6488   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6489     {
6490       if (query (_("The target is not responding to interrupt requests.\n"
6491                    "Stop debugging it? ")))
6492         {
6493           remote_unpush_target ();
6494           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6495         }
6496     }
6497   else
6498     {
6499       if (query (_("Interrupted while waiting for the program.\n"
6500                    "Give up waiting? ")))
6501         quit ();
6502     }
6503 }
6504
6505 /* Enable/disable target terminal ownership.  Most targets can use
6506    terminal groups to control terminal ownership.  Remote targets are
6507    different in that explicit transfer of ownership to/from GDB/target
6508    is required.  */
6509
6510 void
6511 remote_target::terminal_inferior ()
6512 {
6513   /* NOTE: At this point we could also register our selves as the
6514      recipient of all input.  Any characters typed could then be
6515      passed on down to the target.  */
6516 }
6517
6518 void
6519 remote_target::terminal_ours ()
6520 {
6521 }
6522
6523 static void
6524 remote_console_output (char *msg)
6525 {
6526   char *p;
6527
6528   for (p = msg; p[0] && p[1]; p += 2)
6529     {
6530       char tb[2];
6531       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6532
6533       tb[0] = c;
6534       tb[1] = 0;
6535       fputs_unfiltered (tb, gdb_stdtarg);
6536     }
6537   gdb_flush (gdb_stdtarg);
6538 }
6539
6540 DEF_VEC_O(cached_reg_t);
6541
6542 typedef struct stop_reply
6543 {
6544   struct notif_event base;
6545
6546   /* The identifier of the thread about this event  */
6547   ptid_t ptid;
6548
6549   /* The remote state this event is associated with.  When the remote
6550      connection, represented by a remote_state object, is closed,
6551      all the associated stop_reply events should be released.  */
6552   struct remote_state *rs;
6553
6554   struct target_waitstatus ws;
6555
6556   /* The architecture associated with the expedited registers.  */
6557   gdbarch *arch;
6558
6559   /* Expedited registers.  This makes remote debugging a bit more
6560      efficient for those targets that provide critical registers as
6561      part of their normal status mechanism (as another roundtrip to
6562      fetch them is avoided).  */
6563   VEC(cached_reg_t) *regcache;
6564
6565   enum target_stop_reason stop_reason;
6566
6567   CORE_ADDR watch_data_address;
6568
6569   int core;
6570 } *stop_reply_p;
6571
6572 DECLARE_QUEUE_P (stop_reply_p);
6573 DEFINE_QUEUE_P (stop_reply_p);
6574 /* The list of already fetched and acknowledged stop events.  This
6575    queue is used for notification Stop, and other notifications
6576    don't need queue for their events, because the notification events
6577    of Stop can't be consumed immediately, so that events should be
6578    queued first, and be consumed by remote_wait_{ns,as} one per
6579    time.  Other notifications can consume their events immediately,
6580    so queue is not needed for them.  */
6581 static QUEUE (stop_reply_p) *stop_reply_queue;
6582
6583 static void
6584 stop_reply_xfree (struct stop_reply *r)
6585 {
6586   notif_event_xfree ((struct notif_event *) r);
6587 }
6588
6589 /* Return the length of the stop reply queue.  */
6590
6591 static int
6592 stop_reply_queue_length (void)
6593 {
6594   return QUEUE_length (stop_reply_p, stop_reply_queue);
6595 }
6596
6597 static void
6598 remote_notif_stop_parse (struct notif_client *self, char *buf,
6599                          struct notif_event *event)
6600 {
6601   remote_parse_stop_reply (buf, (struct stop_reply *) event);
6602 }
6603
6604 static void
6605 remote_notif_stop_ack (struct notif_client *self, char *buf,
6606                        struct notif_event *event)
6607 {
6608   struct stop_reply *stop_reply = (struct stop_reply *) event;
6609
6610   /* acknowledge */
6611   putpkt (self->ack_command);
6612
6613   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6614       /* We got an unknown stop reply.  */
6615       error (_("Unknown stop reply"));
6616
6617   push_stop_reply (stop_reply);
6618 }
6619
6620 static int
6621 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6622 {
6623   /* We can't get pending events in remote_notif_process for
6624      notification stop, and we have to do this in remote_wait_ns
6625      instead.  If we fetch all queued events from stub, remote stub
6626      may exit and we have no chance to process them back in
6627      remote_wait_ns.  */
6628   mark_async_event_handler (remote_async_inferior_event_token);
6629   return 0;
6630 }
6631
6632 static void
6633 stop_reply_dtr (struct notif_event *event)
6634 {
6635   struct stop_reply *r = (struct stop_reply *) event;
6636   cached_reg_t *reg;
6637   int ix;
6638
6639   for (ix = 0;
6640        VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6641        ix++)
6642     xfree (reg->data);
6643
6644   VEC_free (cached_reg_t, r->regcache);
6645 }
6646
6647 static struct notif_event *
6648 remote_notif_stop_alloc_reply (void)
6649 {
6650   /* We cast to a pointer to the "base class".  */
6651   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6652
6653   r->dtr = stop_reply_dtr;
6654
6655   return r;
6656 }
6657
6658 /* A client of notification Stop.  */
6659
6660 struct notif_client notif_client_stop =
6661 {
6662   "Stop",
6663   "vStopped",
6664   remote_notif_stop_parse,
6665   remote_notif_stop_ack,
6666   remote_notif_stop_can_get_pending_events,
6667   remote_notif_stop_alloc_reply,
6668   REMOTE_NOTIF_STOP,
6669 };
6670
6671 /* A parameter to pass data in and out.  */
6672
6673 struct queue_iter_param
6674 {
6675   void *input;
6676   struct stop_reply *output;
6677 };
6678
6679 /* Determine if THREAD_PTID is a pending fork parent thread.  ARG contains
6680    the pid of the process that owns the threads we want to check, or
6681    -1 if we want to check all threads.  */
6682
6683 static int
6684 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6685                         ptid_t thread_ptid)
6686 {
6687   if (ws->kind == TARGET_WAITKIND_FORKED
6688       || ws->kind == TARGET_WAITKIND_VFORKED)
6689     {
6690       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6691         return 1;
6692     }
6693
6694   return 0;
6695 }
6696
6697 /* Return the thread's pending status used to determine whether the
6698    thread is a fork parent stopped at a fork event.  */
6699
6700 static struct target_waitstatus *
6701 thread_pending_fork_status (struct thread_info *thread)
6702 {
6703   if (thread->suspend.waitstatus_pending_p)
6704     return &thread->suspend.waitstatus;
6705   else
6706     return &thread->pending_follow;
6707 }
6708
6709 /* Determine if THREAD is a pending fork parent thread.  */
6710
6711 static int
6712 is_pending_fork_parent_thread (struct thread_info *thread)
6713 {
6714   struct target_waitstatus *ws = thread_pending_fork_status (thread);
6715   int pid = -1;
6716
6717   return is_pending_fork_parent (ws, pid, thread->ptid);
6718 }
6719
6720 /* Check whether EVENT is a fork event, and if it is, remove the
6721    fork child from the context list passed in DATA.  */
6722
6723 static int
6724 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6725                               QUEUE_ITER (stop_reply_p) *iter,
6726                               stop_reply_p event,
6727                               void *data)
6728 {
6729   struct queue_iter_param *param = (struct queue_iter_param *) data;
6730   struct threads_listing_context *context
6731     = (struct threads_listing_context *) param->input;
6732
6733   if (event->ws.kind == TARGET_WAITKIND_FORKED
6734       || event->ws.kind == TARGET_WAITKIND_VFORKED
6735       || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6736     context->remove_thread (event->ws.value.related_pid);
6737
6738   return 1;
6739 }
6740
6741 /* If CONTEXT contains any fork child threads that have not been
6742    reported yet, remove them from the CONTEXT list.  If such a
6743    thread exists it is because we are stopped at a fork catchpoint
6744    and have not yet called follow_fork, which will set up the
6745    host-side data structures for the new process.  */
6746
6747 static void
6748 remove_new_fork_children (struct threads_listing_context *context)
6749 {
6750   struct thread_info * thread;
6751   int pid = -1;
6752   struct notif_client *notif = &notif_client_stop;
6753   struct queue_iter_param param;
6754
6755   /* For any threads stopped at a fork event, remove the corresponding
6756      fork child threads from the CONTEXT list.  */
6757   ALL_NON_EXITED_THREADS (thread)
6758     {
6759       struct target_waitstatus *ws = thread_pending_fork_status (thread);
6760
6761       if (is_pending_fork_parent (ws, pid, thread->ptid))
6762         context->remove_thread (ws->value.related_pid);
6763     }
6764
6765   /* Check for any pending fork events (not reported or processed yet)
6766      in process PID and remove those fork child threads from the
6767      CONTEXT list as well.  */
6768   remote_notif_get_pending_events (notif);
6769   param.input = context;
6770   param.output = NULL;
6771   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6772                  remove_child_of_pending_fork, &param);
6773 }
6774
6775 /* Check whether EVENT would prevent a global or process wildcard
6776    vCont action.  */
6777
6778 static int
6779 check_pending_event_prevents_wildcard_vcont_callback
6780   (QUEUE (stop_reply_p) *q,
6781    QUEUE_ITER (stop_reply_p) *iter,
6782    stop_reply_p event,
6783    void *data)
6784 {
6785   struct inferior *inf;
6786   int *may_global_wildcard_vcont = (int *) data;
6787
6788   if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6789       || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6790     return 1;
6791
6792   if (event->ws.kind == TARGET_WAITKIND_FORKED
6793       || event->ws.kind == TARGET_WAITKIND_VFORKED)
6794     *may_global_wildcard_vcont = 0;
6795
6796   inf = find_inferior_ptid (event->ptid);
6797
6798   /* This may be the first time we heard about this process.
6799      Regardless, we must not do a global wildcard resume, otherwise
6800      we'd resume this process too.  */
6801   *may_global_wildcard_vcont = 0;
6802   if (inf != NULL)
6803     get_remote_inferior (inf)->may_wildcard_vcont = false;
6804
6805   return 1;
6806 }
6807
6808 /* Check whether any event pending in the vStopped queue would prevent
6809    a global or process wildcard vCont action.  Clear
6810    *may_global_wildcard if we can't do a global wildcard (vCont;c),
6811    and clear the event inferior's may_wildcard_vcont flag if we can't
6812    do a process-wide wildcard resume (vCont;c:pPID.-1).  */
6813
6814 static void
6815 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6816 {
6817   struct notif_client *notif = &notif_client_stop;
6818
6819   remote_notif_get_pending_events (notif);
6820   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6821                  check_pending_event_prevents_wildcard_vcont_callback,
6822                  may_global_wildcard);
6823 }
6824
6825 /* Remove stop replies in the queue if its pid is equal to the given
6826    inferior's pid.  */
6827
6828 static int
6829 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6830                                 QUEUE_ITER (stop_reply_p) *iter,
6831                                 stop_reply_p event,
6832                                 void *data)
6833 {
6834   struct queue_iter_param *param = (struct queue_iter_param *) data;
6835   struct inferior *inf = (struct inferior *) param->input;
6836
6837   if (ptid_get_pid (event->ptid) == inf->pid)
6838     {
6839       stop_reply_xfree (event);
6840       QUEUE_remove_elem (stop_reply_p, q, iter);
6841     }
6842
6843   return 1;
6844 }
6845
6846 /* Discard all pending stop replies of inferior INF.  */
6847
6848 static void
6849 discard_pending_stop_replies (struct inferior *inf)
6850 {
6851   struct queue_iter_param param;
6852   struct stop_reply *reply;
6853   struct remote_state *rs = get_remote_state ();
6854   struct remote_notif_state *rns = rs->notif_state;
6855
6856   /* This function can be notified when an inferior exists.  When the
6857      target is not remote, the notification state is NULL.  */
6858   if (rs->remote_desc == NULL)
6859     return;
6860
6861   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6862
6863   /* Discard the in-flight notification.  */
6864   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6865     {
6866       stop_reply_xfree (reply);
6867       rns->pending_event[notif_client_stop.id] = NULL;
6868     }
6869
6870   param.input = inf;
6871   param.output = NULL;
6872   /* Discard the stop replies we have already pulled with
6873      vStopped.  */
6874   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6875                  remove_stop_reply_for_inferior, &param);
6876 }
6877
6878 /* If its remote state is equal to the given remote state,
6879    remove EVENT from the stop reply queue.  */
6880
6881 static int
6882 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6883                                    QUEUE_ITER (stop_reply_p) *iter,
6884                                    stop_reply_p event,
6885                                    void *data)
6886 {
6887   struct queue_iter_param *param = (struct queue_iter_param *) data;
6888   struct remote_state *rs = (struct remote_state *) param->input;
6889
6890   if (event->rs == rs)
6891     {
6892       stop_reply_xfree (event);
6893       QUEUE_remove_elem (stop_reply_p, q, iter);
6894     }
6895
6896   return 1;
6897 }
6898
6899 /* Discard the stop replies for RS in stop_reply_queue.  */
6900
6901 static void
6902 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6903 {
6904   struct queue_iter_param param;
6905
6906   param.input = rs;
6907   param.output = NULL;
6908   /* Discard the stop replies we have already pulled with
6909      vStopped.  */
6910   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6911                  remove_stop_reply_of_remote_state, &param);
6912 }
6913
6914 /* A parameter to pass data in and out.  */
6915
6916 static int
6917 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6918                                    QUEUE_ITER (stop_reply_p) *iter,
6919                                    stop_reply_p event,
6920                                    void *data)
6921 {
6922   struct queue_iter_param *param = (struct queue_iter_param *) data;
6923   ptid_t *ptid = (ptid_t *) param->input;
6924
6925   if (ptid_match (event->ptid, *ptid))
6926     {
6927       param->output = event;
6928       QUEUE_remove_elem (stop_reply_p, q, iter);
6929       return 0;
6930     }
6931
6932   return 1;
6933 }
6934
6935 /* Remove the first reply in 'stop_reply_queue' which matches
6936    PTID.  */
6937
6938 static struct stop_reply *
6939 remote_notif_remove_queued_reply (ptid_t ptid)
6940 {
6941   struct queue_iter_param param;
6942
6943   param.input = &ptid;
6944   param.output = NULL;
6945
6946   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6947                  remote_notif_remove_once_on_match, &param);
6948   if (notif_debug)
6949     fprintf_unfiltered (gdb_stdlog,
6950                         "notif: discard queued event: 'Stop' in %s\n",
6951                         target_pid_to_str (ptid));
6952
6953   return param.output;
6954 }
6955
6956 /* Look for a queued stop reply belonging to PTID.  If one is found,
6957    remove it from the queue, and return it.  Returns NULL if none is
6958    found.  If there are still queued events left to process, tell the
6959    event loop to get back to target_wait soon.  */
6960
6961 static struct stop_reply *
6962 queued_stop_reply (ptid_t ptid)
6963 {
6964   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6965
6966   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6967     /* There's still at least an event left.  */
6968     mark_async_event_handler (remote_async_inferior_event_token);
6969
6970   return r;
6971 }
6972
6973 /* Push a fully parsed stop reply in the stop reply queue.  Since we
6974    know that we now have at least one queued event left to pass to the
6975    core side, tell the event loop to get back to target_wait soon.  */
6976
6977 static void
6978 push_stop_reply (struct stop_reply *new_event)
6979 {
6980   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6981
6982   if (notif_debug)
6983     fprintf_unfiltered (gdb_stdlog,
6984                         "notif: push 'Stop' %s to queue %d\n",
6985                         target_pid_to_str (new_event->ptid),
6986                         QUEUE_length (stop_reply_p,
6987                                       stop_reply_queue));
6988
6989   mark_async_event_handler (remote_async_inferior_event_token);
6990 }
6991
6992 static int
6993 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6994                               QUEUE_ITER (stop_reply_p) *iter,
6995                               struct stop_reply *event,
6996                               void *data)
6997 {
6998   ptid_t *ptid = (ptid_t *) data;
6999
7000   return !(ptid_equal (*ptid, event->ptid)
7001            && event->ws.kind == TARGET_WAITKIND_STOPPED);
7002 }
7003
7004 /* Returns true if we have a stop reply for PTID.  */
7005
7006 static int
7007 peek_stop_reply (ptid_t ptid)
7008 {
7009   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
7010                          stop_reply_match_ptid_and_ws, &ptid);
7011 }
7012
7013 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
7014    starting with P and ending with PEND matches PREFIX.  */
7015
7016 static int
7017 strprefix (const char *p, const char *pend, const char *prefix)
7018 {
7019   for ( ; p < pend; p++, prefix++)
7020     if (*p != *prefix)
7021       return 0;
7022   return *prefix == '\0';
7023 }
7024
7025 /* Parse the stop reply in BUF.  Either the function succeeds, and the
7026    result is stored in EVENT, or throws an error.  */
7027
7028 static void
7029 remote_parse_stop_reply (char *buf, struct stop_reply *event)
7030 {
7031   remote_arch_state *rsa = NULL;
7032   ULONGEST addr;
7033   const char *p;
7034   int skipregs = 0;
7035
7036   event->ptid = null_ptid;
7037   event->rs = get_remote_state ();
7038   event->ws.kind = TARGET_WAITKIND_IGNORE;
7039   event->ws.value.integer = 0;
7040   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7041   event->regcache = NULL;
7042   event->core = -1;
7043
7044   switch (buf[0])
7045     {
7046     case 'T':           /* Status with PC, SP, FP, ...  */
7047       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
7048       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
7049             ss = signal number
7050             n... = register number
7051             r... = register contents
7052       */
7053
7054       p = &buf[3];      /* after Txx */
7055       while (*p)
7056         {
7057           const char *p1;
7058           int fieldsize;
7059
7060           p1 = strchr (p, ':');
7061           if (p1 == NULL)
7062             error (_("Malformed packet(a) (missing colon): %s\n\
7063 Packet: '%s'\n"),
7064                    p, buf);
7065           if (p == p1)
7066             error (_("Malformed packet(a) (missing register number): %s\n\
7067 Packet: '%s'\n"),
7068                    p, buf);
7069
7070           /* Some "registers" are actually extended stop information.
7071              Note if you're adding a new entry here: GDB 7.9 and
7072              earlier assume that all register "numbers" that start
7073              with an hex digit are real register numbers.  Make sure
7074              the server only sends such a packet if it knows the
7075              client understands it.  */
7076
7077           if (strprefix (p, p1, "thread"))
7078             event->ptid = read_ptid (++p1, &p);
7079           else if (strprefix (p, p1, "syscall_entry"))
7080             {
7081               ULONGEST sysno;
7082
7083               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7084               p = unpack_varlen_hex (++p1, &sysno);
7085               event->ws.value.syscall_number = (int) sysno;
7086             }
7087           else if (strprefix (p, p1, "syscall_return"))
7088             {
7089               ULONGEST sysno;
7090
7091               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7092               p = unpack_varlen_hex (++p1, &sysno);
7093               event->ws.value.syscall_number = (int) sysno;
7094             }
7095           else if (strprefix (p, p1, "watch")
7096                    || strprefix (p, p1, "rwatch")
7097                    || strprefix (p, p1, "awatch"))
7098             {
7099               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7100               p = unpack_varlen_hex (++p1, &addr);
7101               event->watch_data_address = (CORE_ADDR) addr;
7102             }
7103           else if (strprefix (p, p1, "swbreak"))
7104             {
7105               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7106
7107               /* Make sure the stub doesn't forget to indicate support
7108                  with qSupported.  */
7109               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7110                 error (_("Unexpected swbreak stop reason"));
7111
7112               /* The value part is documented as "must be empty",
7113                  though we ignore it, in case we ever decide to make
7114                  use of it in a backward compatible way.  */
7115               p = strchrnul (p1 + 1, ';');
7116             }
7117           else if (strprefix (p, p1, "hwbreak"))
7118             {
7119               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7120
7121               /* Make sure the stub doesn't forget to indicate support
7122                  with qSupported.  */
7123               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7124                 error (_("Unexpected hwbreak stop reason"));
7125
7126               /* See above.  */
7127               p = strchrnul (p1 + 1, ';');
7128             }
7129           else if (strprefix (p, p1, "library"))
7130             {
7131               event->ws.kind = TARGET_WAITKIND_LOADED;
7132               p = strchrnul (p1 + 1, ';');
7133             }
7134           else if (strprefix (p, p1, "replaylog"))
7135             {
7136               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7137               /* p1 will indicate "begin" or "end", but it makes
7138                  no difference for now, so ignore it.  */
7139               p = strchrnul (p1 + 1, ';');
7140             }
7141           else if (strprefix (p, p1, "core"))
7142             {
7143               ULONGEST c;
7144
7145               p = unpack_varlen_hex (++p1, &c);
7146               event->core = c;
7147             }
7148           else if (strprefix (p, p1, "fork"))
7149             {
7150               event->ws.value.related_pid = read_ptid (++p1, &p);
7151               event->ws.kind = TARGET_WAITKIND_FORKED;
7152             }
7153           else if (strprefix (p, p1, "vfork"))
7154             {
7155               event->ws.value.related_pid = read_ptid (++p1, &p);
7156               event->ws.kind = TARGET_WAITKIND_VFORKED;
7157             }
7158           else if (strprefix (p, p1, "vforkdone"))
7159             {
7160               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7161               p = strchrnul (p1 + 1, ';');
7162             }
7163           else if (strprefix (p, p1, "exec"))
7164             {
7165               ULONGEST ignored;
7166               char pathname[PATH_MAX];
7167               int pathlen;
7168
7169               /* Determine the length of the execd pathname.  */
7170               p = unpack_varlen_hex (++p1, &ignored);
7171               pathlen = (p - p1) / 2;
7172
7173               /* Save the pathname for event reporting and for
7174                  the next run command.  */
7175               hex2bin (p1, (gdb_byte *) pathname, pathlen);
7176               pathname[pathlen] = '\0';
7177
7178               /* This is freed during event handling.  */
7179               event->ws.value.execd_pathname = xstrdup (pathname);
7180               event->ws.kind = TARGET_WAITKIND_EXECD;
7181
7182               /* Skip the registers included in this packet, since
7183                  they may be for an architecture different from the
7184                  one used by the original program.  */
7185               skipregs = 1;
7186             }
7187           else if (strprefix (p, p1, "create"))
7188             {
7189               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7190               p = strchrnul (p1 + 1, ';');
7191             }
7192           else
7193             {
7194               ULONGEST pnum;
7195               const char *p_temp;
7196
7197               if (skipregs)
7198                 {
7199                   p = strchrnul (p1 + 1, ';');
7200                   p++;
7201                   continue;
7202                 }
7203
7204               /* Maybe a real ``P'' register number.  */
7205               p_temp = unpack_varlen_hex (p, &pnum);
7206               /* If the first invalid character is the colon, we got a
7207                  register number.  Otherwise, it's an unknown stop
7208                  reason.  */
7209               if (p_temp == p1)
7210                 {
7211                   /* If we haven't parsed the event's thread yet, find
7212                      it now, in order to find the architecture of the
7213                      reported expedited registers.  */
7214                   if (event->ptid == null_ptid)
7215                     {
7216                       const char *thr = strstr (p1 + 1, ";thread:");
7217                       if (thr != NULL)
7218                         event->ptid = read_ptid (thr + strlen (";thread:"),
7219                                                  NULL);
7220                       else
7221                         {
7222                           /* Either the current thread hasn't changed,
7223                              or the inferior is not multi-threaded.
7224                              The event must be for the thread we last
7225                              set as (or learned as being) current.  */
7226                           event->ptid = event->rs->general_thread;
7227                         }
7228                     }
7229
7230                   if (rsa == NULL)
7231                     {
7232                       inferior *inf = (event->ptid == null_ptid
7233                                        ? NULL
7234                                        : find_inferior_ptid (event->ptid));
7235                       /* If this is the first time we learn anything
7236                          about this process, skip the registers
7237                          included in this packet, since we don't yet
7238                          know which architecture to use to parse them.
7239                          We'll determine the architecture later when
7240                          we process the stop reply and retrieve the
7241                          target description, via
7242                          remote_notice_new_inferior ->
7243                          post_create_inferior.  */
7244                       if (inf == NULL)
7245                         {
7246                           p = strchrnul (p1 + 1, ';');
7247                           p++;
7248                           continue;
7249                         }
7250
7251                       event->arch = inf->gdbarch;
7252                       rsa = get_remote_arch_state (event->arch);
7253                     }
7254
7255                   packet_reg *reg
7256                     = packet_reg_from_pnum (event->arch, rsa, pnum);
7257                   cached_reg_t cached_reg;
7258
7259                   if (reg == NULL)
7260                     error (_("Remote sent bad register number %s: %s\n\
7261 Packet: '%s'\n"),
7262                            hex_string (pnum), p, buf);
7263
7264                   cached_reg.num = reg->regnum;
7265                   cached_reg.data = (gdb_byte *)
7266                     xmalloc (register_size (event->arch, reg->regnum));
7267
7268                   p = p1 + 1;
7269                   fieldsize = hex2bin (p, cached_reg.data,
7270                                        register_size (event->arch, reg->regnum));
7271                   p += 2 * fieldsize;
7272                   if (fieldsize < register_size (event->arch, reg->regnum))
7273                     warning (_("Remote reply is too short: %s"), buf);
7274
7275                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7276                 }
7277               else
7278                 {
7279                   /* Not a number.  Silently skip unknown optional
7280                      info.  */
7281                   p = strchrnul (p1 + 1, ';');
7282                 }
7283             }
7284
7285           if (*p != ';')
7286             error (_("Remote register badly formatted: %s\nhere: %s"),
7287                    buf, p);
7288           ++p;
7289         }
7290
7291       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7292         break;
7293
7294       /* fall through */
7295     case 'S':           /* Old style status, just signal only.  */
7296       {
7297         int sig;
7298
7299         event->ws.kind = TARGET_WAITKIND_STOPPED;
7300         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7301         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7302           event->ws.value.sig = (enum gdb_signal) sig;
7303         else
7304           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7305       }
7306       break;
7307     case 'w':           /* Thread exited.  */
7308       {
7309         const char *p;
7310         ULONGEST value;
7311
7312         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7313         p = unpack_varlen_hex (&buf[1], &value);
7314         event->ws.value.integer = value;
7315         if (*p != ';')
7316           error (_("stop reply packet badly formatted: %s"), buf);
7317         event->ptid = read_ptid (++p, NULL);
7318         break;
7319       }
7320     case 'W':           /* Target exited.  */
7321     case 'X':
7322       {
7323         const char *p;
7324         int pid;
7325         ULONGEST value;
7326
7327         /* GDB used to accept only 2 hex chars here.  Stubs should
7328            only send more if they detect GDB supports multi-process
7329            support.  */
7330         p = unpack_varlen_hex (&buf[1], &value);
7331
7332         if (buf[0] == 'W')
7333           {
7334             /* The remote process exited.  */
7335             event->ws.kind = TARGET_WAITKIND_EXITED;
7336             event->ws.value.integer = value;
7337           }
7338         else
7339           {
7340             /* The remote process exited with a signal.  */
7341             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7342             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7343               event->ws.value.sig = (enum gdb_signal) value;
7344             else
7345               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7346           }
7347
7348         /* If no process is specified, assume inferior_ptid.  */
7349         pid = ptid_get_pid (inferior_ptid);
7350         if (*p == '\0')
7351           ;
7352         else if (*p == ';')
7353           {
7354             p++;
7355
7356             if (*p == '\0')
7357               ;
7358             else if (startswith (p, "process:"))
7359               {
7360                 ULONGEST upid;
7361
7362                 p += sizeof ("process:") - 1;
7363                 unpack_varlen_hex (p, &upid);
7364                 pid = upid;
7365               }
7366             else
7367               error (_("unknown stop reply packet: %s"), buf);
7368           }
7369         else
7370           error (_("unknown stop reply packet: %s"), buf);
7371         event->ptid = pid_to_ptid (pid);
7372       }
7373       break;
7374     case 'N':
7375       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7376       event->ptid = minus_one_ptid;
7377       break;
7378     }
7379
7380   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7381     error (_("No process or thread specified in stop reply: %s"), buf);
7382 }
7383
7384 /* When the stub wants to tell GDB about a new notification reply, it
7385    sends a notification (%Stop, for example).  Those can come it at
7386    any time, hence, we have to make sure that any pending
7387    putpkt/getpkt sequence we're making is finished, before querying
7388    the stub for more events with the corresponding ack command
7389    (vStopped, for example).  E.g., if we started a vStopped sequence
7390    immediately upon receiving the notification, something like this
7391    could happen:
7392
7393     1.1) --> Hg 1
7394     1.2) <-- OK
7395     1.3) --> g
7396     1.4) <-- %Stop
7397     1.5) --> vStopped
7398     1.6) <-- (registers reply to step #1.3)
7399
7400    Obviously, the reply in step #1.6 would be unexpected to a vStopped
7401    query.
7402
7403    To solve this, whenever we parse a %Stop notification successfully,
7404    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7405    doing whatever we were doing:
7406
7407     2.1) --> Hg 1
7408     2.2) <-- OK
7409     2.3) --> g
7410     2.4) <-- %Stop
7411       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7412     2.5) <-- (registers reply to step #2.3)
7413
7414    Eventualy after step #2.5, we return to the event loop, which
7415    notices there's an event on the
7416    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7417    associated callback --- the function below.  At this point, we're
7418    always safe to start a vStopped sequence. :
7419
7420     2.6) --> vStopped
7421     2.7) <-- T05 thread:2
7422     2.8) --> vStopped
7423     2.9) --> OK
7424 */
7425
7426 void
7427 remote_notif_get_pending_events (struct notif_client *nc)
7428 {
7429   struct remote_state *rs = get_remote_state ();
7430
7431   if (rs->notif_state->pending_event[nc->id] != NULL)
7432     {
7433       if (notif_debug)
7434         fprintf_unfiltered (gdb_stdlog,
7435                             "notif: process: '%s' ack pending event\n",
7436                             nc->name);
7437
7438       /* acknowledge */
7439       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7440       rs->notif_state->pending_event[nc->id] = NULL;
7441
7442       while (1)
7443         {
7444           getpkt (&rs->buf, &rs->buf_size, 0);
7445           if (strcmp (rs->buf, "OK") == 0)
7446             break;
7447           else
7448             remote_notif_ack (nc, rs->buf);
7449         }
7450     }
7451   else
7452     {
7453       if (notif_debug)
7454         fprintf_unfiltered (gdb_stdlog,
7455                             "notif: process: '%s' no pending reply\n",
7456                             nc->name);
7457     }
7458 }
7459
7460 /* Called when it is decided that STOP_REPLY holds the info of the
7461    event that is to be returned to the core.  This function always
7462    destroys STOP_REPLY.  */
7463
7464 static ptid_t
7465 process_stop_reply (struct stop_reply *stop_reply,
7466                     struct target_waitstatus *status)
7467 {
7468   ptid_t ptid;
7469
7470   *status = stop_reply->ws;
7471   ptid = stop_reply->ptid;
7472
7473   /* If no thread/process was reported by the stub, assume the current
7474      inferior.  */
7475   if (ptid_equal (ptid, null_ptid))
7476     ptid = inferior_ptid;
7477
7478   if (status->kind != TARGET_WAITKIND_EXITED
7479       && status->kind != TARGET_WAITKIND_SIGNALLED
7480       && status->kind != TARGET_WAITKIND_NO_RESUMED)
7481     {
7482       /* Expedited registers.  */
7483       if (stop_reply->regcache)
7484         {
7485           struct regcache *regcache
7486             = get_thread_arch_regcache (ptid, stop_reply->arch);
7487           cached_reg_t *reg;
7488           int ix;
7489
7490           for (ix = 0;
7491                VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7492                ix++)
7493           {
7494             regcache_raw_supply (regcache, reg->num, reg->data);
7495             xfree (reg->data);
7496           }
7497
7498           VEC_free (cached_reg_t, stop_reply->regcache);
7499         }
7500
7501       remote_notice_new_inferior (ptid, 0);
7502       remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7503       remote_thr->core = stop_reply->core;
7504       remote_thr->stop_reason = stop_reply->stop_reason;
7505       remote_thr->watch_data_address = stop_reply->watch_data_address;
7506       remote_thr->vcont_resumed = 0;
7507     }
7508
7509   stop_reply_xfree (stop_reply);
7510   return ptid;
7511 }
7512
7513 /* The non-stop mode version of target_wait.  */
7514
7515 static ptid_t
7516 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7517 {
7518   struct remote_state *rs = get_remote_state ();
7519   struct stop_reply *stop_reply;
7520   int ret;
7521   int is_notif = 0;
7522
7523   /* If in non-stop mode, get out of getpkt even if a
7524      notification is received.  */
7525
7526   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7527                               0 /* forever */, &is_notif);
7528   while (1)
7529     {
7530       if (ret != -1 && !is_notif)
7531         switch (rs->buf[0])
7532           {
7533           case 'E':             /* Error of some sort.  */
7534             /* We're out of sync with the target now.  Did it continue
7535                or not?  We can't tell which thread it was in non-stop,
7536                so just ignore this.  */
7537             warning (_("Remote failure reply: %s"), rs->buf);
7538             break;
7539           case 'O':             /* Console output.  */
7540             remote_console_output (rs->buf + 1);
7541             break;
7542           default:
7543             warning (_("Invalid remote reply: %s"), rs->buf);
7544             break;
7545           }
7546
7547       /* Acknowledge a pending stop reply that may have arrived in the
7548          mean time.  */
7549       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7550         remote_notif_get_pending_events (&notif_client_stop);
7551
7552       /* If indeed we noticed a stop reply, we're done.  */
7553       stop_reply = queued_stop_reply (ptid);
7554       if (stop_reply != NULL)
7555         return process_stop_reply (stop_reply, status);
7556
7557       /* Still no event.  If we're just polling for an event, then
7558          return to the event loop.  */
7559       if (options & TARGET_WNOHANG)
7560         {
7561           status->kind = TARGET_WAITKIND_IGNORE;
7562           return minus_one_ptid;
7563         }
7564
7565       /* Otherwise do a blocking wait.  */
7566       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7567                                   1 /* forever */, &is_notif);
7568     }
7569 }
7570
7571 /* Wait until the remote machine stops, then return, storing status in
7572    STATUS just as `wait' would.  */
7573
7574 static ptid_t
7575 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7576 {
7577   struct remote_state *rs = get_remote_state ();
7578   ptid_t event_ptid = null_ptid;
7579   char *buf;
7580   struct stop_reply *stop_reply;
7581
7582  again:
7583
7584   status->kind = TARGET_WAITKIND_IGNORE;
7585   status->value.integer = 0;
7586
7587   stop_reply = queued_stop_reply (ptid);
7588   if (stop_reply != NULL)
7589     return process_stop_reply (stop_reply, status);
7590
7591   if (rs->cached_wait_status)
7592     /* Use the cached wait status, but only once.  */
7593     rs->cached_wait_status = 0;
7594   else
7595     {
7596       int ret;
7597       int is_notif;
7598       int forever = ((options & TARGET_WNOHANG) == 0
7599                      && wait_forever_enabled_p);
7600
7601       if (!rs->waiting_for_stop_reply)
7602         {
7603           status->kind = TARGET_WAITKIND_NO_RESUMED;
7604           return minus_one_ptid;
7605         }
7606
7607       /* FIXME: cagney/1999-09-27: If we're in async mode we should
7608          _never_ wait for ever -> test on target_is_async_p().
7609          However, before we do that we need to ensure that the caller
7610          knows how to take the target into/out of async mode.  */
7611       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7612                                   forever, &is_notif);
7613
7614       /* GDB gets a notification.  Return to core as this event is
7615          not interesting.  */
7616       if (ret != -1 && is_notif)
7617         return minus_one_ptid;
7618
7619       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7620         return minus_one_ptid;
7621     }
7622
7623   buf = rs->buf;
7624
7625   /* Assume that the target has acknowledged Ctrl-C unless we receive
7626      an 'F' or 'O' packet.  */
7627   if (buf[0] != 'F' && buf[0] != 'O')
7628     rs->ctrlc_pending_p = 0;
7629
7630   switch (buf[0])
7631     {
7632     case 'E':           /* Error of some sort.  */
7633       /* We're out of sync with the target now.  Did it continue or
7634          not?  Not is more likely, so report a stop.  */
7635       rs->waiting_for_stop_reply = 0;
7636
7637       warning (_("Remote failure reply: %s"), buf);
7638       status->kind = TARGET_WAITKIND_STOPPED;
7639       status->value.sig = GDB_SIGNAL_0;
7640       break;
7641     case 'F':           /* File-I/O request.  */
7642       /* GDB may access the inferior memory while handling the File-I/O
7643          request, but we don't want GDB accessing memory while waiting
7644          for a stop reply.  See the comments in putpkt_binary.  Set
7645          waiting_for_stop_reply to 0 temporarily.  */
7646       rs->waiting_for_stop_reply = 0;
7647       remote_fileio_request (buf, rs->ctrlc_pending_p);
7648       rs->ctrlc_pending_p = 0;
7649       /* GDB handled the File-I/O request, and the target is running
7650          again.  Keep waiting for events.  */
7651       rs->waiting_for_stop_reply = 1;
7652       break;
7653     case 'N': case 'T': case 'S': case 'X': case 'W':
7654       {
7655         struct stop_reply *stop_reply;
7656
7657         /* There is a stop reply to handle.  */
7658         rs->waiting_for_stop_reply = 0;
7659
7660         stop_reply
7661           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7662                                                       rs->buf);
7663
7664         event_ptid = process_stop_reply (stop_reply, status);
7665         break;
7666       }
7667     case 'O':           /* Console output.  */
7668       remote_console_output (buf + 1);
7669       break;
7670     case '\0':
7671       if (rs->last_sent_signal != GDB_SIGNAL_0)
7672         {
7673           /* Zero length reply means that we tried 'S' or 'C' and the
7674              remote system doesn't support it.  */
7675           target_terminal::ours_for_output ();
7676           printf_filtered
7677             ("Can't send signals to this remote system.  %s not sent.\n",
7678              gdb_signal_to_name (rs->last_sent_signal));
7679           rs->last_sent_signal = GDB_SIGNAL_0;
7680           target_terminal::inferior ();
7681
7682           strcpy (buf, rs->last_sent_step ? "s" : "c");
7683           putpkt (buf);
7684           break;
7685         }
7686       /* fallthrough */
7687     default:
7688       warning (_("Invalid remote reply: %s"), buf);
7689       break;
7690     }
7691
7692   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7693     return minus_one_ptid;
7694   else if (status->kind == TARGET_WAITKIND_IGNORE)
7695     {
7696       /* Nothing interesting happened.  If we're doing a non-blocking
7697          poll, we're done.  Otherwise, go back to waiting.  */
7698       if (options & TARGET_WNOHANG)
7699         return minus_one_ptid;
7700       else
7701         goto again;
7702     }
7703   else if (status->kind != TARGET_WAITKIND_EXITED
7704            && status->kind != TARGET_WAITKIND_SIGNALLED)
7705     {
7706       if (!ptid_equal (event_ptid, null_ptid))
7707         record_currthread (rs, event_ptid);
7708       else
7709         event_ptid = inferior_ptid;
7710     }
7711   else
7712     /* A process exit.  Invalidate our notion of current thread.  */
7713     record_currthread (rs, minus_one_ptid);
7714
7715   return event_ptid;
7716 }
7717
7718 /* Wait until the remote machine stops, then return, storing status in
7719    STATUS just as `wait' would.  */
7720
7721 ptid_t
7722 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7723 {
7724   ptid_t event_ptid;
7725
7726   if (target_is_non_stop_p ())
7727     event_ptid = remote_wait_ns (ptid, status, options);
7728   else
7729     event_ptid = remote_wait_as (ptid, status, options);
7730
7731   if (target_is_async_p ())
7732     {
7733       /* If there are are events left in the queue tell the event loop
7734          to return here.  */
7735       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7736         mark_async_event_handler (remote_async_inferior_event_token);
7737     }
7738
7739   return event_ptid;
7740 }
7741
7742 /* Fetch a single register using a 'p' packet.  */
7743
7744 static int
7745 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7746 {
7747   struct gdbarch *gdbarch = regcache->arch ();
7748   struct remote_state *rs = get_remote_state ();
7749   char *buf, *p;
7750   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7751   int i;
7752
7753   if (packet_support (PACKET_p) == PACKET_DISABLE)
7754     return 0;
7755
7756   if (reg->pnum == -1)
7757     return 0;
7758
7759   p = rs->buf;
7760   *p++ = 'p';
7761   p += hexnumstr (p, reg->pnum);
7762   *p++ = '\0';
7763   putpkt (rs->buf);
7764   getpkt (&rs->buf, &rs->buf_size, 0);
7765
7766   buf = rs->buf;
7767
7768   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7769     {
7770     case PACKET_OK:
7771       break;
7772     case PACKET_UNKNOWN:
7773       return 0;
7774     case PACKET_ERROR:
7775       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7776              gdbarch_register_name (regcache->arch (), 
7777                                     reg->regnum), 
7778              buf);
7779     }
7780
7781   /* If this register is unfetchable, tell the regcache.  */
7782   if (buf[0] == 'x')
7783     {
7784       regcache_raw_supply (regcache, reg->regnum, NULL);
7785       return 1;
7786     }
7787
7788   /* Otherwise, parse and supply the value.  */
7789   p = buf;
7790   i = 0;
7791   while (p[0] != 0)
7792     {
7793       if (p[1] == 0)
7794         error (_("fetch_register_using_p: early buf termination"));
7795
7796       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7797       p += 2;
7798     }
7799   regcache_raw_supply (regcache, reg->regnum, regp);
7800   return 1;
7801 }
7802
7803 /* Fetch the registers included in the target's 'g' packet.  */
7804
7805 static int
7806 send_g_packet (void)
7807 {
7808   struct remote_state *rs = get_remote_state ();
7809   int buf_len;
7810
7811   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7812   putpkt (rs->buf);
7813   getpkt (&rs->buf, &rs->buf_size, 0);
7814   if (packet_check_result (rs->buf) == PACKET_ERROR)
7815     error (_("Could not read registers; remote failure reply '%s'"),
7816            rs->buf);
7817
7818   /* We can get out of synch in various cases.  If the first character
7819      in the buffer is not a hex character, assume that has happened
7820      and try to fetch another packet to read.  */
7821   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7822          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7823          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7824          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
7825     {
7826       if (remote_debug)
7827         fprintf_unfiltered (gdb_stdlog,
7828                             "Bad register packet; fetching a new packet\n");
7829       getpkt (&rs->buf, &rs->buf_size, 0);
7830     }
7831
7832   buf_len = strlen (rs->buf);
7833
7834   /* Sanity check the received packet.  */
7835   if (buf_len % 2 != 0)
7836     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7837
7838   return buf_len / 2;
7839 }
7840
7841 static void
7842 process_g_packet (struct regcache *regcache)
7843 {
7844   struct gdbarch *gdbarch = regcache->arch ();
7845   struct remote_state *rs = get_remote_state ();
7846   remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7847   int i, buf_len;
7848   char *p;
7849   char *regs;
7850
7851   buf_len = strlen (rs->buf);
7852
7853   /* Further sanity checks, with knowledge of the architecture.  */
7854   if (buf_len > 2 * rsa->sizeof_g_packet)
7855     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7856              "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7857
7858   /* Save the size of the packet sent to us by the target.  It is used
7859      as a heuristic when determining the max size of packets that the
7860      target can safely receive.  */
7861   if (rsa->actual_register_packet_size == 0)
7862     rsa->actual_register_packet_size = buf_len;
7863
7864   /* If this is smaller than we guessed the 'g' packet would be,
7865      update our records.  A 'g' reply that doesn't include a register's
7866      value implies either that the register is not available, or that
7867      the 'p' packet must be used.  */
7868   if (buf_len < 2 * rsa->sizeof_g_packet)
7869     {
7870       long sizeof_g_packet = buf_len / 2;
7871
7872       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7873         {
7874           long offset = rsa->regs[i].offset;
7875           long reg_size = register_size (gdbarch, i);
7876
7877           if (rsa->regs[i].pnum == -1)
7878             continue;
7879
7880           if (offset >= sizeof_g_packet)
7881             rsa->regs[i].in_g_packet = 0;
7882           else if (offset + reg_size > sizeof_g_packet)
7883             error (_("Truncated register %d in remote 'g' packet"), i);
7884           else
7885             rsa->regs[i].in_g_packet = 1;
7886         }
7887
7888       /* Looks valid enough, we can assume this is the correct length
7889          for a 'g' packet.  It's important not to adjust
7890          rsa->sizeof_g_packet if we have truncated registers otherwise
7891          this "if" won't be run the next time the method is called
7892          with a packet of the same size and one of the internal errors
7893          below will trigger instead.  */
7894       rsa->sizeof_g_packet = sizeof_g_packet;
7895     }
7896
7897   regs = (char *) alloca (rsa->sizeof_g_packet);
7898
7899   /* Unimplemented registers read as all bits zero.  */
7900   memset (regs, 0, rsa->sizeof_g_packet);
7901
7902   /* Reply describes registers byte by byte, each byte encoded as two
7903      hex characters.  Suck them all up, then supply them to the
7904      register cacheing/storage mechanism.  */
7905
7906   p = rs->buf;
7907   for (i = 0; i < rsa->sizeof_g_packet; i++)
7908     {
7909       if (p[0] == 0 || p[1] == 0)
7910         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
7911         internal_error (__FILE__, __LINE__,
7912                         _("unexpected end of 'g' packet reply"));
7913
7914       if (p[0] == 'x' && p[1] == 'x')
7915         regs[i] = 0;            /* 'x' */
7916       else
7917         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7918       p += 2;
7919     }
7920
7921   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7922     {
7923       struct packet_reg *r = &rsa->regs[i];
7924       long reg_size = register_size (gdbarch, i);
7925
7926       if (r->in_g_packet)
7927         {
7928           if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7929             /* This shouldn't happen - we adjusted in_g_packet above.  */
7930             internal_error (__FILE__, __LINE__,
7931                             _("unexpected end of 'g' packet reply"));
7932           else if (rs->buf[r->offset * 2] == 'x')
7933             {
7934               gdb_assert (r->offset * 2 < strlen (rs->buf));
7935               /* The register isn't available, mark it as such (at
7936                  the same time setting the value to zero).  */
7937               regcache_raw_supply (regcache, r->regnum, NULL);
7938             }
7939           else
7940             regcache_raw_supply (regcache, r->regnum,
7941                                  regs + r->offset);
7942         }
7943     }
7944 }
7945
7946 static void
7947 fetch_registers_using_g (struct regcache *regcache)
7948 {
7949   send_g_packet ();
7950   process_g_packet (regcache);
7951 }
7952
7953 /* Make the remote selected traceframe match GDB's selected
7954    traceframe.  */
7955
7956 static void
7957 set_remote_traceframe (void)
7958 {
7959   int newnum;
7960   struct remote_state *rs = get_remote_state ();
7961
7962   if (rs->remote_traceframe_number == get_traceframe_number ())
7963     return;
7964
7965   /* Avoid recursion, remote_trace_find calls us again.  */
7966   rs->remote_traceframe_number = get_traceframe_number ();
7967
7968   newnum = target_trace_find (tfind_number,
7969                               get_traceframe_number (), 0, 0, NULL);
7970
7971   /* Should not happen.  If it does, all bets are off.  */
7972   if (newnum != get_traceframe_number ())
7973     warning (_("could not set remote traceframe"));
7974 }
7975
7976 void
7977 remote_target::fetch_registers (struct regcache *regcache, int regnum)
7978 {
7979   struct gdbarch *gdbarch = regcache->arch ();
7980   remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7981   int i;
7982
7983   set_remote_traceframe ();
7984   set_general_thread (regcache_get_ptid (regcache));
7985
7986   if (regnum >= 0)
7987     {
7988       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
7989
7990       gdb_assert (reg != NULL);
7991
7992       /* If this register might be in the 'g' packet, try that first -
7993          we are likely to read more than one register.  If this is the
7994          first 'g' packet, we might be overly optimistic about its
7995          contents, so fall back to 'p'.  */
7996       if (reg->in_g_packet)
7997         {
7998           fetch_registers_using_g (regcache);
7999           if (reg->in_g_packet)
8000             return;
8001         }
8002
8003       if (fetch_register_using_p (regcache, reg))
8004         return;
8005
8006       /* This register is not available.  */
8007       regcache_raw_supply (regcache, reg->regnum, NULL);
8008
8009       return;
8010     }
8011
8012   fetch_registers_using_g (regcache);
8013
8014   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8015     if (!rsa->regs[i].in_g_packet)
8016       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8017         {
8018           /* This register is not available.  */
8019           regcache_raw_supply (regcache, i, NULL);
8020         }
8021 }
8022
8023 /* Prepare to store registers.  Since we may send them all (using a
8024    'G' request), we have to read out the ones we don't want to change
8025    first.  */
8026
8027 void
8028 remote_target::prepare_to_store (struct regcache *regcache)
8029 {
8030   remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8031   int i;
8032
8033   /* Make sure the entire registers array is valid.  */
8034   switch (packet_support (PACKET_P))
8035     {
8036     case PACKET_DISABLE:
8037     case PACKET_SUPPORT_UNKNOWN:
8038       /* Make sure all the necessary registers are cached.  */
8039       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8040         if (rsa->regs[i].in_g_packet)
8041           regcache_raw_update (regcache, rsa->regs[i].regnum);
8042       break;
8043     case PACKET_ENABLE:
8044       break;
8045     }
8046 }
8047
8048 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
8049    packet was not recognized.  */
8050
8051 static int
8052 store_register_using_P (const struct regcache *regcache, 
8053                         struct packet_reg *reg)
8054 {
8055   struct gdbarch *gdbarch = regcache->arch ();
8056   struct remote_state *rs = get_remote_state ();
8057   /* Try storing a single register.  */
8058   char *buf = rs->buf;
8059   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8060   char *p;
8061
8062   if (packet_support (PACKET_P) == PACKET_DISABLE)
8063     return 0;
8064
8065   if (reg->pnum == -1)
8066     return 0;
8067
8068   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8069   p = buf + strlen (buf);
8070   regcache_raw_collect (regcache, reg->regnum, regp);
8071   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8072   putpkt (rs->buf);
8073   getpkt (&rs->buf, &rs->buf_size, 0);
8074
8075   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8076     {
8077     case PACKET_OK:
8078       return 1;
8079     case PACKET_ERROR:
8080       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8081              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8082     case PACKET_UNKNOWN:
8083       return 0;
8084     default:
8085       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8086     }
8087 }
8088
8089 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8090    contents of the register cache buffer.  FIXME: ignores errors.  */
8091
8092 static void
8093 store_registers_using_G (const struct regcache *regcache)
8094 {
8095   struct remote_state *rs = get_remote_state ();
8096   remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8097   gdb_byte *regs;
8098   char *p;
8099
8100   /* Extract all the registers in the regcache copying them into a
8101      local buffer.  */
8102   {
8103     int i;
8104
8105     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8106     memset (regs, 0, rsa->sizeof_g_packet);
8107     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8108       {
8109         struct packet_reg *r = &rsa->regs[i];
8110
8111         if (r->in_g_packet)
8112           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
8113       }
8114   }
8115
8116   /* Command describes registers byte by byte,
8117      each byte encoded as two hex characters.  */
8118   p = rs->buf;
8119   *p++ = 'G';
8120   bin2hex (regs, p, rsa->sizeof_g_packet);
8121   putpkt (rs->buf);
8122   getpkt (&rs->buf, &rs->buf_size, 0);
8123   if (packet_check_result (rs->buf) == PACKET_ERROR)
8124     error (_("Could not write registers; remote failure reply '%s'"), 
8125            rs->buf);
8126 }
8127
8128 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8129    of the register cache buffer.  FIXME: ignores errors.  */
8130
8131 void
8132 remote_target::store_registers (struct regcache *regcache, int regnum)
8133 {
8134   struct gdbarch *gdbarch = regcache->arch ();
8135   remote_arch_state *rsa = get_remote_arch_state (gdbarch);
8136   int i;
8137
8138   set_remote_traceframe ();
8139   set_general_thread (regcache_get_ptid (regcache));
8140
8141   if (regnum >= 0)
8142     {
8143       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8144
8145       gdb_assert (reg != NULL);
8146
8147       /* Always prefer to store registers using the 'P' packet if
8148          possible; we often change only a small number of registers.
8149          Sometimes we change a larger number; we'd need help from a
8150          higher layer to know to use 'G'.  */
8151       if (store_register_using_P (regcache, reg))
8152         return;
8153
8154       /* For now, don't complain if we have no way to write the
8155          register.  GDB loses track of unavailable registers too
8156          easily.  Some day, this may be an error.  We don't have
8157          any way to read the register, either...  */
8158       if (!reg->in_g_packet)
8159         return;
8160
8161       store_registers_using_G (regcache);
8162       return;
8163     }
8164
8165   store_registers_using_G (regcache);
8166
8167   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8168     if (!rsa->regs[i].in_g_packet)
8169       if (!store_register_using_P (regcache, &rsa->regs[i]))
8170         /* See above for why we do not issue an error here.  */
8171         continue;
8172 }
8173 \f
8174
8175 /* Return the number of hex digits in num.  */
8176
8177 static int
8178 hexnumlen (ULONGEST num)
8179 {
8180   int i;
8181
8182   for (i = 0; num != 0; i++)
8183     num >>= 4;
8184
8185   return std::max (i, 1);
8186 }
8187
8188 /* Set BUF to the minimum number of hex digits representing NUM.  */
8189
8190 static int
8191 hexnumstr (char *buf, ULONGEST num)
8192 {
8193   int len = hexnumlen (num);
8194
8195   return hexnumnstr (buf, num, len);
8196 }
8197
8198
8199 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
8200
8201 static int
8202 hexnumnstr (char *buf, ULONGEST num, int width)
8203 {
8204   int i;
8205
8206   buf[width] = '\0';
8207
8208   for (i = width - 1; i >= 0; i--)
8209     {
8210       buf[i] = "0123456789abcdef"[(num & 0xf)];
8211       num >>= 4;
8212     }
8213
8214   return width;
8215 }
8216
8217 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
8218
8219 static CORE_ADDR
8220 remote_address_masked (CORE_ADDR addr)
8221 {
8222   unsigned int address_size = remote_address_size;
8223
8224   /* If "remoteaddresssize" was not set, default to target address size.  */
8225   if (!address_size)
8226     address_size = gdbarch_addr_bit (target_gdbarch ());
8227
8228   if (address_size > 0
8229       && address_size < (sizeof (ULONGEST) * 8))
8230     {
8231       /* Only create a mask when that mask can safely be constructed
8232          in a ULONGEST variable.  */
8233       ULONGEST mask = 1;
8234
8235       mask = (mask << address_size) - 1;
8236       addr &= mask;
8237     }
8238   return addr;
8239 }
8240
8241 /* Determine whether the remote target supports binary downloading.
8242    This is accomplished by sending a no-op memory write of zero length
8243    to the target at the specified address. It does not suffice to send
8244    the whole packet, since many stubs strip the eighth bit and
8245    subsequently compute a wrong checksum, which causes real havoc with
8246    remote_write_bytes.
8247
8248    NOTE: This can still lose if the serial line is not eight-bit
8249    clean.  In cases like this, the user should clear "remote
8250    X-packet".  */
8251
8252 static void
8253 check_binary_download (CORE_ADDR addr)
8254 {
8255   struct remote_state *rs = get_remote_state ();
8256
8257   switch (packet_support (PACKET_X))
8258     {
8259     case PACKET_DISABLE:
8260       break;
8261     case PACKET_ENABLE:
8262       break;
8263     case PACKET_SUPPORT_UNKNOWN:
8264       {
8265         char *p;
8266
8267         p = rs->buf;
8268         *p++ = 'X';
8269         p += hexnumstr (p, (ULONGEST) addr);
8270         *p++ = ',';
8271         p += hexnumstr (p, (ULONGEST) 0);
8272         *p++ = ':';
8273         *p = '\0';
8274
8275         putpkt_binary (rs->buf, (int) (p - rs->buf));
8276         getpkt (&rs->buf, &rs->buf_size, 0);
8277
8278         if (rs->buf[0] == '\0')
8279           {
8280             if (remote_debug)
8281               fprintf_unfiltered (gdb_stdlog,
8282                                   "binary downloading NOT "
8283                                   "supported by target\n");
8284             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8285           }
8286         else
8287           {
8288             if (remote_debug)
8289               fprintf_unfiltered (gdb_stdlog,
8290                                   "binary downloading supported by target\n");
8291             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8292           }
8293         break;
8294       }
8295     }
8296 }
8297
8298 /* Helper function to resize the payload in order to try to get a good
8299    alignment.  We try to write an amount of data such that the next write will
8300    start on an address aligned on REMOTE_ALIGN_WRITES.  */
8301
8302 static int
8303 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8304 {
8305   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8306 }
8307
8308 /* Write memory data directly to the remote machine.
8309    This does not inform the data cache; the data cache uses this.
8310    HEADER is the starting part of the packet.
8311    MEMADDR is the address in the remote memory space.
8312    MYADDR is the address of the buffer in our space.
8313    LEN_UNITS is the number of addressable units to write.
8314    UNIT_SIZE is the length in bytes of an addressable unit.
8315    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8316    should send data as binary ('X'), or hex-encoded ('M').
8317
8318    The function creates packet of the form
8319        <HEADER><ADDRESS>,<LENGTH>:<DATA>
8320
8321    where encoding of <DATA> is terminated by PACKET_FORMAT.
8322
8323    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8324    are omitted.
8325
8326    Return the transferred status, error or OK (an
8327    'enum target_xfer_status' value).  Save the number of addressable units
8328    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
8329
8330    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8331    exchange between gdb and the stub could look like (?? in place of the
8332    checksum):
8333
8334    -> $m1000,4#??
8335    <- aaaabbbbccccdddd
8336
8337    -> $M1000,3:eeeeffffeeee#??
8338    <- OK
8339
8340    -> $m1000,4#??
8341    <- eeeeffffeeeedddd  */
8342
8343 static enum target_xfer_status
8344 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8345                         const gdb_byte *myaddr, ULONGEST len_units,
8346                         int unit_size, ULONGEST *xfered_len_units,
8347                         char packet_format, int use_length)
8348 {
8349   struct remote_state *rs = get_remote_state ();
8350   char *p;
8351   char *plen = NULL;
8352   int plenlen = 0;
8353   int todo_units;
8354   int units_written;
8355   int payload_capacity_bytes;
8356   int payload_length_bytes;
8357
8358   if (packet_format != 'X' && packet_format != 'M')
8359     internal_error (__FILE__, __LINE__,
8360                     _("remote_write_bytes_aux: bad packet format"));
8361
8362   if (len_units == 0)
8363     return TARGET_XFER_EOF;
8364
8365   payload_capacity_bytes = get_memory_write_packet_size ();
8366
8367   /* The packet buffer will be large enough for the payload;
8368      get_memory_packet_size ensures this.  */
8369   rs->buf[0] = '\0';
8370
8371   /* Compute the size of the actual payload by subtracting out the
8372      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
8373
8374   payload_capacity_bytes -= strlen ("$,:#NN");
8375   if (!use_length)
8376     /* The comma won't be used.  */
8377     payload_capacity_bytes += 1;
8378   payload_capacity_bytes -= strlen (header);
8379   payload_capacity_bytes -= hexnumlen (memaddr);
8380
8381   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
8382
8383   strcat (rs->buf, header);
8384   p = rs->buf + strlen (header);
8385
8386   /* Compute a best guess of the number of bytes actually transfered.  */
8387   if (packet_format == 'X')
8388     {
8389       /* Best guess at number of bytes that will fit.  */
8390       todo_units = std::min (len_units,
8391                              (ULONGEST) payload_capacity_bytes / unit_size);
8392       if (use_length)
8393         payload_capacity_bytes -= hexnumlen (todo_units);
8394       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8395     }
8396   else
8397     {
8398       /* Number of bytes that will fit.  */
8399       todo_units
8400         = std::min (len_units,
8401                     (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8402       if (use_length)
8403         payload_capacity_bytes -= hexnumlen (todo_units);
8404       todo_units = std::min (todo_units,
8405                              (payload_capacity_bytes / unit_size) / 2);
8406     }
8407
8408   if (todo_units <= 0)
8409     internal_error (__FILE__, __LINE__,
8410                     _("minimum packet size too small to write data"));
8411
8412   /* If we already need another packet, then try to align the end
8413      of this packet to a useful boundary.  */
8414   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8415     todo_units = align_for_efficient_write (todo_units, memaddr);
8416
8417   /* Append "<memaddr>".  */
8418   memaddr = remote_address_masked (memaddr);
8419   p += hexnumstr (p, (ULONGEST) memaddr);
8420
8421   if (use_length)
8422     {
8423       /* Append ",".  */
8424       *p++ = ',';
8425
8426       /* Append the length and retain its location and size.  It may need to be
8427          adjusted once the packet body has been created.  */
8428       plen = p;
8429       plenlen = hexnumstr (p, (ULONGEST) todo_units);
8430       p += plenlen;
8431     }
8432
8433   /* Append ":".  */
8434   *p++ = ':';
8435   *p = '\0';
8436
8437   /* Append the packet body.  */
8438   if (packet_format == 'X')
8439     {
8440       /* Binary mode.  Send target system values byte by byte, in
8441          increasing byte addresses.  Only escape certain critical
8442          characters.  */
8443       payload_length_bytes =
8444           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8445                                 &units_written, payload_capacity_bytes);
8446
8447       /* If not all TODO units fit, then we'll need another packet.  Make
8448          a second try to keep the end of the packet aligned.  Don't do
8449          this if the packet is tiny.  */
8450       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8451         {
8452           int new_todo_units;
8453
8454           new_todo_units = align_for_efficient_write (units_written, memaddr);
8455
8456           if (new_todo_units != units_written)
8457             payload_length_bytes =
8458                 remote_escape_output (myaddr, new_todo_units, unit_size,
8459                                       (gdb_byte *) p, &units_written,
8460                                       payload_capacity_bytes);
8461         }
8462
8463       p += payload_length_bytes;
8464       if (use_length && units_written < todo_units)
8465         {
8466           /* Escape chars have filled up the buffer prematurely,
8467              and we have actually sent fewer units than planned.
8468              Fix-up the length field of the packet.  Use the same
8469              number of characters as before.  */
8470           plen += hexnumnstr (plen, (ULONGEST) units_written,
8471                               plenlen);
8472           *plen = ':';  /* overwrite \0 from hexnumnstr() */
8473         }
8474     }
8475   else
8476     {
8477       /* Normal mode: Send target system values byte by byte, in
8478          increasing byte addresses.  Each byte is encoded as a two hex
8479          value.  */
8480       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8481       units_written = todo_units;
8482     }
8483
8484   putpkt_binary (rs->buf, (int) (p - rs->buf));
8485   getpkt (&rs->buf, &rs->buf_size, 0);
8486
8487   if (rs->buf[0] == 'E')
8488     return TARGET_XFER_E_IO;
8489
8490   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8491      send fewer units than we'd planned.  */
8492   *xfered_len_units = (ULONGEST) units_written;
8493   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8494 }
8495
8496 /* Write memory data directly to the remote machine.
8497    This does not inform the data cache; the data cache uses this.
8498    MEMADDR is the address in the remote memory space.
8499    MYADDR is the address of the buffer in our space.
8500    LEN is the number of bytes.
8501
8502    Return the transferred status, error or OK (an
8503    'enum target_xfer_status' value).  Save the number of bytes
8504    transferred in *XFERED_LEN.  Only transfer a single packet.  */
8505
8506 static enum target_xfer_status
8507 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8508                     int unit_size, ULONGEST *xfered_len)
8509 {
8510   const char *packet_format = NULL;
8511
8512   /* Check whether the target supports binary download.  */
8513   check_binary_download (memaddr);
8514
8515   switch (packet_support (PACKET_X))
8516     {
8517     case PACKET_ENABLE:
8518       packet_format = "X";
8519       break;
8520     case PACKET_DISABLE:
8521       packet_format = "M";
8522       break;
8523     case PACKET_SUPPORT_UNKNOWN:
8524       internal_error (__FILE__, __LINE__,
8525                       _("remote_write_bytes: bad internal state"));
8526     default:
8527       internal_error (__FILE__, __LINE__, _("bad switch"));
8528     }
8529
8530   return remote_write_bytes_aux (packet_format,
8531                                  memaddr, myaddr, len, unit_size, xfered_len,
8532                                  packet_format[0], 1);
8533 }
8534
8535 /* Read memory data directly from the remote machine.
8536    This does not use the data cache; the data cache uses this.
8537    MEMADDR is the address in the remote memory space.
8538    MYADDR is the address of the buffer in our space.
8539    LEN_UNITS is the number of addressable memory units to read..
8540    UNIT_SIZE is the length in bytes of an addressable unit.
8541
8542    Return the transferred status, error or OK (an
8543    'enum target_xfer_status' value).  Save the number of bytes
8544    transferred in *XFERED_LEN_UNITS.
8545
8546    See the comment of remote_write_bytes_aux for an example of
8547    memory read/write exchange between gdb and the stub.  */
8548
8549 static enum target_xfer_status
8550 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8551                      int unit_size, ULONGEST *xfered_len_units)
8552 {
8553   struct remote_state *rs = get_remote_state ();
8554   int buf_size_bytes;           /* Max size of packet output buffer.  */
8555   char *p;
8556   int todo_units;
8557   int decoded_bytes;
8558
8559   buf_size_bytes = get_memory_read_packet_size ();
8560   /* The packet buffer will be large enough for the payload;
8561      get_memory_packet_size ensures this.  */
8562
8563   /* Number of units that will fit.  */
8564   todo_units = std::min (len_units,
8565                          (ULONGEST) (buf_size_bytes / unit_size) / 2);
8566
8567   /* Construct "m"<memaddr>","<len>".  */
8568   memaddr = remote_address_masked (memaddr);
8569   p = rs->buf;
8570   *p++ = 'm';
8571   p += hexnumstr (p, (ULONGEST) memaddr);
8572   *p++ = ',';
8573   p += hexnumstr (p, (ULONGEST) todo_units);
8574   *p = '\0';
8575   putpkt (rs->buf);
8576   getpkt (&rs->buf, &rs->buf_size, 0);
8577   if (rs->buf[0] == 'E'
8578       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8579       && rs->buf[3] == '\0')
8580     return TARGET_XFER_E_IO;
8581   /* Reply describes memory byte by byte, each byte encoded as two hex
8582      characters.  */
8583   p = rs->buf;
8584   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8585   /* Return what we have.  Let higher layers handle partial reads.  */
8586   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8587   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8588 }
8589
8590 /* Using the set of read-only target sections of remote, read live
8591    read-only memory.
8592
8593    For interface/parameters/return description see target.h,
8594    to_xfer_partial.  */
8595
8596 static enum target_xfer_status
8597 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8598                                    ULONGEST memaddr, ULONGEST len,
8599                                    int unit_size, ULONGEST *xfered_len)
8600 {
8601   struct target_section *secp;
8602   struct target_section_table *table;
8603
8604   secp = target_section_by_addr (ops, memaddr);
8605   if (secp != NULL
8606       && (bfd_get_section_flags (secp->the_bfd_section->owner,
8607                                  secp->the_bfd_section)
8608           & SEC_READONLY))
8609     {
8610       struct target_section *p;
8611       ULONGEST memend = memaddr + len;
8612
8613       table = target_get_section_table (ops);
8614
8615       for (p = table->sections; p < table->sections_end; p++)
8616         {
8617           if (memaddr >= p->addr)
8618             {
8619               if (memend <= p->endaddr)
8620                 {
8621                   /* Entire transfer is within this section.  */
8622                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8623                                               xfered_len);
8624                 }
8625               else if (memaddr >= p->endaddr)
8626                 {
8627                   /* This section ends before the transfer starts.  */
8628                   continue;
8629                 }
8630               else
8631                 {
8632                   /* This section overlaps the transfer.  Just do half.  */
8633                   len = p->endaddr - memaddr;
8634                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8635                                               xfered_len);
8636                 }
8637             }
8638         }
8639     }
8640
8641   return TARGET_XFER_EOF;
8642 }
8643
8644 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8645    first if the requested memory is unavailable in traceframe.
8646    Otherwise, fall back to remote_read_bytes_1.  */
8647
8648 static enum target_xfer_status
8649 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8650                    gdb_byte *myaddr, ULONGEST len, int unit_size,
8651                    ULONGEST *xfered_len)
8652 {
8653   if (len == 0)
8654     return TARGET_XFER_EOF;
8655
8656   if (get_traceframe_number () != -1)
8657     {
8658       std::vector<mem_range> available;
8659
8660       /* If we fail to get the set of available memory, then the
8661          target does not support querying traceframe info, and so we
8662          attempt reading from the traceframe anyway (assuming the
8663          target implements the old QTro packet then).  */
8664       if (traceframe_available_memory (&available, memaddr, len))
8665         {
8666           if (available.empty () || available[0].start != memaddr)
8667             {
8668               enum target_xfer_status res;
8669
8670               /* Don't read into the traceframe's available
8671                  memory.  */
8672               if (!available.empty ())
8673                 {
8674                   LONGEST oldlen = len;
8675
8676                   len = available[0].start - memaddr;
8677                   gdb_assert (len <= oldlen);
8678                 }
8679
8680               /* This goes through the topmost target again.  */
8681               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8682                                                        len, unit_size, xfered_len);
8683               if (res == TARGET_XFER_OK)
8684                 return TARGET_XFER_OK;
8685               else
8686                 {
8687                   /* No use trying further, we know some memory starting
8688                      at MEMADDR isn't available.  */
8689                   *xfered_len = len;
8690                   return (*xfered_len != 0) ?
8691                     TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8692                 }
8693             }
8694
8695           /* Don't try to read more than how much is available, in
8696              case the target implements the deprecated QTro packet to
8697              cater for older GDBs (the target's knowledge of read-only
8698              sections may be outdated by now).  */
8699           len = available[0].length;
8700         }
8701     }
8702
8703   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8704 }
8705
8706 \f
8707
8708 /* Sends a packet with content determined by the printf format string
8709    FORMAT and the remaining arguments, then gets the reply.  Returns
8710    whether the packet was a success, a failure, or unknown.  */
8711
8712 static enum packet_result remote_send_printf (const char *format, ...)
8713   ATTRIBUTE_PRINTF (1, 2);
8714
8715 static enum packet_result
8716 remote_send_printf (const char *format, ...)
8717 {
8718   struct remote_state *rs = get_remote_state ();
8719   int max_size = get_remote_packet_size ();
8720   va_list ap;
8721
8722   va_start (ap, format);
8723
8724   rs->buf[0] = '\0';
8725   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8726     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8727
8728   if (putpkt (rs->buf) < 0)
8729     error (_("Communication problem with target."));
8730
8731   rs->buf[0] = '\0';
8732   getpkt (&rs->buf, &rs->buf_size, 0);
8733
8734   return packet_check_result (rs->buf);
8735 }
8736
8737 /* Flash writing can take quite some time.  We'll set
8738    effectively infinite timeout for flash operations.
8739    In future, we'll need to decide on a better approach.  */
8740 static const int remote_flash_timeout = 1000;
8741
8742 void
8743 remote_target::flash_erase (ULONGEST address, LONGEST length)
8744 {
8745   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8746   enum packet_result ret;
8747   scoped_restore restore_timeout
8748     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8749
8750   ret = remote_send_printf ("vFlashErase:%s,%s",
8751                             phex (address, addr_size),
8752                             phex (length, 4));
8753   switch (ret)
8754     {
8755     case PACKET_UNKNOWN:
8756       error (_("Remote target does not support flash erase"));
8757     case PACKET_ERROR:
8758       error (_("Error erasing flash with vFlashErase packet"));
8759     default:
8760       break;
8761     }
8762 }
8763
8764 static enum target_xfer_status
8765 remote_flash_write (struct target_ops *ops, ULONGEST address,
8766                     ULONGEST length, ULONGEST *xfered_len,
8767                     const gdb_byte *data)
8768 {
8769   scoped_restore restore_timeout
8770     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8771   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8772                                  xfered_len,'X', 0);
8773 }
8774
8775 void
8776 remote_target::flash_done ()
8777 {
8778   int ret;
8779
8780   scoped_restore restore_timeout
8781     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8782
8783   ret = remote_send_printf ("vFlashDone");
8784
8785   switch (ret)
8786     {
8787     case PACKET_UNKNOWN:
8788       error (_("Remote target does not support vFlashDone"));
8789     case PACKET_ERROR:
8790       error (_("Error finishing flash operation"));
8791     default:
8792       break;
8793     }
8794 }
8795
8796 void
8797 remote_target::files_info ()
8798 {
8799   puts_filtered ("Debugging a target over a serial line.\n");
8800 }
8801 \f
8802 /* Stuff for dealing with the packets which are part of this protocol.
8803    See comment at top of file for details.  */
8804
8805 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8806    error to higher layers.  Called when a serial error is detected.
8807    The exception message is STRING, followed by a colon and a blank,
8808    the system error message for errno at function entry and final dot
8809    for output compatibility with throw_perror_with_name.  */
8810
8811 static void
8812 unpush_and_perror (const char *string)
8813 {
8814   int saved_errno = errno;
8815
8816   remote_unpush_target ();
8817   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8818                safe_strerror (saved_errno));
8819 }
8820
8821 /* Read a single character from the remote end.  The current quit
8822    handler is overridden to avoid quitting in the middle of packet
8823    sequence, as that would break communication with the remote server.
8824    See remote_serial_quit_handler for more detail.  */
8825
8826 static int
8827 readchar (int timeout)
8828 {
8829   int ch;
8830   struct remote_state *rs = get_remote_state ();
8831
8832   {
8833     scoped_restore restore_quit
8834       = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8835
8836     rs->got_ctrlc_during_io = 0;
8837
8838     ch = serial_readchar (rs->remote_desc, timeout);
8839
8840     if (rs->got_ctrlc_during_io)
8841       set_quit_flag ();
8842   }
8843
8844   if (ch >= 0)
8845     return ch;
8846
8847   switch ((enum serial_rc) ch)
8848     {
8849     case SERIAL_EOF:
8850       remote_unpush_target ();
8851       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8852       /* no return */
8853     case SERIAL_ERROR:
8854       unpush_and_perror (_("Remote communication error.  "
8855                            "Target disconnected."));
8856       /* no return */
8857     case SERIAL_TIMEOUT:
8858       break;
8859     }
8860   return ch;
8861 }
8862
8863 /* Wrapper for serial_write that closes the target and throws if
8864    writing fails.  The current quit handler is overridden to avoid
8865    quitting in the middle of packet sequence, as that would break
8866    communication with the remote server.  See
8867    remote_serial_quit_handler for more detail.  */
8868
8869 static void
8870 remote_serial_write (const char *str, int len)
8871 {
8872   struct remote_state *rs = get_remote_state ();
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   if (serial_write (rs->remote_desc, str, len))
8880     {
8881       unpush_and_perror (_("Remote communication error.  "
8882                            "Target disconnected."));
8883     }
8884
8885   if (rs->got_ctrlc_during_io)
8886     set_quit_flag ();
8887 }
8888
8889 /* Return a string representing an escaped version of BUF, of len N.
8890    E.g. \n is converted to \\n, \t to \\t, etc.  */
8891
8892 static std::string
8893 escape_buffer (const char *buf, int n)
8894 {
8895   string_file stb;
8896
8897   stb.putstrn (buf, n, '\\');
8898   return std::move (stb.string ());
8899 }
8900
8901 /* Display a null-terminated packet on stdout, for debugging, using C
8902    string notation.  */
8903
8904 static void
8905 print_packet (const char *buf)
8906 {
8907   puts_filtered ("\"");
8908   fputstr_filtered (buf, '"', gdb_stdout);
8909   puts_filtered ("\"");
8910 }
8911
8912 int
8913 putpkt (const char *buf)
8914 {
8915   return putpkt_binary (buf, strlen (buf));
8916 }
8917
8918 /* Send a packet to the remote machine, with error checking.  The data
8919    of the packet is in BUF.  The string in BUF can be at most
8920    get_remote_packet_size () - 5 to account for the $, # and checksum,
8921    and for a possible /0 if we are debugging (remote_debug) and want
8922    to print the sent packet as a string.  */
8923
8924 static int
8925 putpkt_binary (const char *buf, int cnt)
8926 {
8927   struct remote_state *rs = get_remote_state ();
8928   int i;
8929   unsigned char csum = 0;
8930   gdb::def_vector<char> data (cnt + 6);
8931   char *buf2 = data.data ();
8932
8933   int ch;
8934   int tcount = 0;
8935   char *p;
8936
8937   /* Catch cases like trying to read memory or listing threads while
8938      we're waiting for a stop reply.  The remote server wouldn't be
8939      ready to handle this request, so we'd hang and timeout.  We don't
8940      have to worry about this in synchronous mode, because in that
8941      case it's not possible to issue a command while the target is
8942      running.  This is not a problem in non-stop mode, because in that
8943      case, the stub is always ready to process serial input.  */
8944   if (!target_is_non_stop_p ()
8945       && target_is_async_p ()
8946       && rs->waiting_for_stop_reply)
8947     {
8948       error (_("Cannot execute this command while the target is running.\n"
8949                "Use the \"interrupt\" command to stop the target\n"
8950                "and then try again."));
8951     }
8952
8953   /* We're sending out a new packet.  Make sure we don't look at a
8954      stale cached response.  */
8955   rs->cached_wait_status = 0;
8956
8957   /* Copy the packet into buffer BUF2, encapsulating it
8958      and giving it a checksum.  */
8959
8960   p = buf2;
8961   *p++ = '$';
8962
8963   for (i = 0; i < cnt; i++)
8964     {
8965       csum += buf[i];
8966       *p++ = buf[i];
8967     }
8968   *p++ = '#';
8969   *p++ = tohex ((csum >> 4) & 0xf);
8970   *p++ = tohex (csum & 0xf);
8971
8972   /* Send it over and over until we get a positive ack.  */
8973
8974   while (1)
8975     {
8976       int started_error_output = 0;
8977
8978       if (remote_debug)
8979         {
8980           *p = '\0';
8981
8982           int len = (int) (p - buf2);
8983
8984           std::string str
8985             = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8986
8987           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8988
8989           if (len > REMOTE_DEBUG_MAX_CHAR)
8990             fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
8991                                 len - REMOTE_DEBUG_MAX_CHAR);
8992
8993           fprintf_unfiltered (gdb_stdlog, "...");
8994
8995           gdb_flush (gdb_stdlog);
8996         }
8997       remote_serial_write (buf2, p - buf2);
8998
8999       /* If this is a no acks version of the remote protocol, send the
9000          packet and move on.  */
9001       if (rs->noack_mode)
9002         break;
9003
9004       /* Read until either a timeout occurs (-2) or '+' is read.
9005          Handle any notification that arrives in the mean time.  */
9006       while (1)
9007         {
9008           ch = readchar (remote_timeout);
9009
9010           if (remote_debug)
9011             {
9012               switch (ch)
9013                 {
9014                 case '+':
9015                 case '-':
9016                 case SERIAL_TIMEOUT:
9017                 case '$':
9018                 case '%':
9019                   if (started_error_output)
9020                     {
9021                       putchar_unfiltered ('\n');
9022                       started_error_output = 0;
9023                     }
9024                 }
9025             }
9026
9027           switch (ch)
9028             {
9029             case '+':
9030               if (remote_debug)
9031                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9032               return 1;
9033             case '-':
9034               if (remote_debug)
9035                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9036               /* FALLTHROUGH */
9037             case SERIAL_TIMEOUT:
9038               tcount++;
9039               if (tcount > 3)
9040                 return 0;
9041               break;            /* Retransmit buffer.  */
9042             case '$':
9043               {
9044                 if (remote_debug)
9045                   fprintf_unfiltered (gdb_stdlog,
9046                                       "Packet instead of Ack, ignoring it\n");
9047                 /* It's probably an old response sent because an ACK
9048                    was lost.  Gobble up the packet and ack it so it
9049                    doesn't get retransmitted when we resend this
9050                    packet.  */
9051                 skip_frame ();
9052                 remote_serial_write ("+", 1);
9053                 continue;       /* Now, go look for +.  */
9054               }
9055
9056             case '%':
9057               {
9058                 int val;
9059
9060                 /* If we got a notification, handle it, and go back to looking
9061                    for an ack.  */
9062                 /* We've found the start of a notification.  Now
9063                    collect the data.  */
9064                 val = read_frame (&rs->buf, &rs->buf_size);
9065                 if (val >= 0)
9066                   {
9067                     if (remote_debug)
9068                       {
9069                         std::string str = escape_buffer (rs->buf, val);
9070
9071                         fprintf_unfiltered (gdb_stdlog,
9072                                             "  Notification received: %s\n",
9073                                             str.c_str ());
9074                       }
9075                     handle_notification (rs->notif_state, rs->buf);
9076                     /* We're in sync now, rewait for the ack.  */
9077                     tcount = 0;
9078                   }
9079                 else
9080                   {
9081                     if (remote_debug)
9082                       {
9083                         if (!started_error_output)
9084                           {
9085                             started_error_output = 1;
9086                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9087                           }
9088                         fputc_unfiltered (ch & 0177, gdb_stdlog);
9089                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9090                       }
9091                   }
9092                 continue;
9093               }
9094               /* fall-through */
9095             default:
9096               if (remote_debug)
9097                 {
9098                   if (!started_error_output)
9099                     {
9100                       started_error_output = 1;
9101                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9102                     }
9103                   fputc_unfiltered (ch & 0177, gdb_stdlog);
9104                 }
9105               continue;
9106             }
9107           break;                /* Here to retransmit.  */
9108         }
9109
9110 #if 0
9111       /* This is wrong.  If doing a long backtrace, the user should be
9112          able to get out next time we call QUIT, without anything as
9113          violent as interrupt_query.  If we want to provide a way out of
9114          here without getting to the next QUIT, it should be based on
9115          hitting ^C twice as in remote_wait.  */
9116       if (quit_flag)
9117         {
9118           quit_flag = 0;
9119           interrupt_query ();
9120         }
9121 #endif
9122     }
9123
9124   return 0;
9125 }
9126
9127 /* Come here after finding the start of a frame when we expected an
9128    ack.  Do our best to discard the rest of this packet.  */
9129
9130 static void
9131 skip_frame (void)
9132 {
9133   int c;
9134
9135   while (1)
9136     {
9137       c = readchar (remote_timeout);
9138       switch (c)
9139         {
9140         case SERIAL_TIMEOUT:
9141           /* Nothing we can do.  */
9142           return;
9143         case '#':
9144           /* Discard the two bytes of checksum and stop.  */
9145           c = readchar (remote_timeout);
9146           if (c >= 0)
9147             c = readchar (remote_timeout);
9148
9149           return;
9150         case '*':               /* Run length encoding.  */
9151           /* Discard the repeat count.  */
9152           c = readchar (remote_timeout);
9153           if (c < 0)
9154             return;
9155           break;
9156         default:
9157           /* A regular character.  */
9158           break;
9159         }
9160     }
9161 }
9162
9163 /* Come here after finding the start of the frame.  Collect the rest
9164    into *BUF, verifying the checksum, length, and handling run-length
9165    compression.  NUL terminate the buffer.  If there is not enough room,
9166    expand *BUF using xrealloc.
9167
9168    Returns -1 on error, number of characters in buffer (ignoring the
9169    trailing NULL) on success. (could be extended to return one of the
9170    SERIAL status indications).  */
9171
9172 static long
9173 read_frame (char **buf_p,
9174             long *sizeof_buf)
9175 {
9176   unsigned char csum;
9177   long bc;
9178   int c;
9179   char *buf = *buf_p;
9180   struct remote_state *rs = get_remote_state ();
9181
9182   csum = 0;
9183   bc = 0;
9184
9185   while (1)
9186     {
9187       c = readchar (remote_timeout);
9188       switch (c)
9189         {
9190         case SERIAL_TIMEOUT:
9191           if (remote_debug)
9192             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9193           return -1;
9194         case '$':
9195           if (remote_debug)
9196             fputs_filtered ("Saw new packet start in middle of old one\n",
9197                             gdb_stdlog);
9198           return -1;            /* Start a new packet, count retries.  */
9199         case '#':
9200           {
9201             unsigned char pktcsum;
9202             int check_0 = 0;
9203             int check_1 = 0;
9204
9205             buf[bc] = '\0';
9206
9207             check_0 = readchar (remote_timeout);
9208             if (check_0 >= 0)
9209               check_1 = readchar (remote_timeout);
9210
9211             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9212               {
9213                 if (remote_debug)
9214                   fputs_filtered ("Timeout in checksum, retrying\n",
9215                                   gdb_stdlog);
9216                 return -1;
9217               }
9218             else if (check_0 < 0 || check_1 < 0)
9219               {
9220                 if (remote_debug)
9221                   fputs_filtered ("Communication error in checksum\n",
9222                                   gdb_stdlog);
9223                 return -1;
9224               }
9225
9226             /* Don't recompute the checksum; with no ack packets we
9227                don't have any way to indicate a packet retransmission
9228                is necessary.  */
9229             if (rs->noack_mode)
9230               return bc;
9231
9232             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9233             if (csum == pktcsum)
9234               return bc;
9235
9236             if (remote_debug)
9237               {
9238                 std::string str = escape_buffer (buf, bc);
9239
9240                 fprintf_unfiltered (gdb_stdlog,
9241                                     "Bad checksum, sentsum=0x%x, "
9242                                     "csum=0x%x, buf=%s\n",
9243                                     pktcsum, csum, str.c_str ());
9244               }
9245             /* Number of characters in buffer ignoring trailing
9246                NULL.  */
9247             return -1;
9248           }
9249         case '*':               /* Run length encoding.  */
9250           {
9251             int repeat;
9252
9253             csum += c;
9254             c = readchar (remote_timeout);
9255             csum += c;
9256             repeat = c - ' ' + 3;       /* Compute repeat count.  */
9257
9258             /* The character before ``*'' is repeated.  */
9259
9260             if (repeat > 0 && repeat <= 255 && bc > 0)
9261               {
9262                 if (bc + repeat - 1 >= *sizeof_buf - 1)
9263                   {
9264                     /* Make some more room in the buffer.  */
9265                     *sizeof_buf += repeat;
9266                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9267                     buf = *buf_p;
9268                   }
9269
9270                 memset (&buf[bc], buf[bc - 1], repeat);
9271                 bc += repeat;
9272                 continue;
9273               }
9274
9275             buf[bc] = '\0';
9276             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9277             return -1;
9278           }
9279         default:
9280           if (bc >= *sizeof_buf - 1)
9281             {
9282               /* Make some more room in the buffer.  */
9283               *sizeof_buf *= 2;
9284               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9285               buf = *buf_p;
9286             }
9287
9288           buf[bc++] = c;
9289           csum += c;
9290           continue;
9291         }
9292     }
9293 }
9294
9295 /* Read a packet from the remote machine, with error checking, and
9296    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9297    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9298    rather than timing out; this is used (in synchronous mode) to wait
9299    for a target that is is executing user code to stop.  */
9300 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9301    don't have to change all the calls to getpkt to deal with the
9302    return value, because at the moment I don't know what the right
9303    thing to do it for those.  */
9304 void
9305 getpkt (char **buf,
9306         long *sizeof_buf,
9307         int forever)
9308 {
9309   getpkt_sane (buf, sizeof_buf, forever);
9310 }
9311
9312
9313 /* Read a packet from the remote machine, with error checking, and
9314    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9315    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9316    rather than timing out; this is used (in synchronous mode) to wait
9317    for a target that is is executing user code to stop.  If FOREVER ==
9318    0, this function is allowed to time out gracefully and return an
9319    indication of this to the caller.  Otherwise return the number of
9320    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
9321    enough reason to return to the caller.  *IS_NOTIF is an output
9322    boolean that indicates whether *BUF holds a notification or not
9323    (a regular packet).  */
9324
9325 static int
9326 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9327                         int expecting_notif, int *is_notif)
9328 {
9329   struct remote_state *rs = get_remote_state ();
9330   int c;
9331   int tries;
9332   int timeout;
9333   int val = -1;
9334
9335   /* We're reading a new response.  Make sure we don't look at a
9336      previously cached response.  */
9337   rs->cached_wait_status = 0;
9338
9339   strcpy (*buf, "timeout");
9340
9341   if (forever)
9342     timeout = watchdog > 0 ? watchdog : -1;
9343   else if (expecting_notif)
9344     timeout = 0; /* There should already be a char in the buffer.  If
9345                     not, bail out.  */
9346   else
9347     timeout = remote_timeout;
9348
9349 #define MAX_TRIES 3
9350
9351   /* Process any number of notifications, and then return when
9352      we get a packet.  */
9353   for (;;)
9354     {
9355       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9356          times.  */
9357       for (tries = 1; tries <= MAX_TRIES; tries++)
9358         {
9359           /* This can loop forever if the remote side sends us
9360              characters continuously, but if it pauses, we'll get
9361              SERIAL_TIMEOUT from readchar because of timeout.  Then
9362              we'll count that as a retry.
9363
9364              Note that even when forever is set, we will only wait
9365              forever prior to the start of a packet.  After that, we
9366              expect characters to arrive at a brisk pace.  They should
9367              show up within remote_timeout intervals.  */
9368           do
9369             c = readchar (timeout);
9370           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9371
9372           if (c == SERIAL_TIMEOUT)
9373             {
9374               if (expecting_notif)
9375                 return -1; /* Don't complain, it's normal to not get
9376                               anything in this case.  */
9377
9378               if (forever)      /* Watchdog went off?  Kill the target.  */
9379                 {
9380                   remote_unpush_target ();
9381                   throw_error (TARGET_CLOSE_ERROR,
9382                                _("Watchdog timeout has expired.  "
9383                                  "Target detached."));
9384                 }
9385               if (remote_debug)
9386                 fputs_filtered ("Timed out.\n", gdb_stdlog);
9387             }
9388           else
9389             {
9390               /* We've found the start of a packet or notification.
9391                  Now collect the data.  */
9392               val = read_frame (buf, sizeof_buf);
9393               if (val >= 0)
9394                 break;
9395             }
9396
9397           remote_serial_write ("-", 1);
9398         }
9399
9400       if (tries > MAX_TRIES)
9401         {
9402           /* We have tried hard enough, and just can't receive the
9403              packet/notification.  Give up.  */
9404           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9405
9406           /* Skip the ack char if we're in no-ack mode.  */
9407           if (!rs->noack_mode)
9408             remote_serial_write ("+", 1);
9409           return -1;
9410         }
9411
9412       /* If we got an ordinary packet, return that to our caller.  */
9413       if (c == '$')
9414         {
9415           if (remote_debug)
9416             {
9417               std::string str
9418                 = escape_buffer (*buf,
9419                                  std::min (val, REMOTE_DEBUG_MAX_CHAR));
9420
9421               fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9422                                   str.c_str ());
9423
9424               if (val > REMOTE_DEBUG_MAX_CHAR)
9425                 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9426                                     val - REMOTE_DEBUG_MAX_CHAR);
9427
9428               fprintf_unfiltered (gdb_stdlog, "\n");
9429             }
9430
9431           /* Skip the ack char if we're in no-ack mode.  */
9432           if (!rs->noack_mode)
9433             remote_serial_write ("+", 1);
9434           if (is_notif != NULL)
9435             *is_notif = 0;
9436           return val;
9437         }
9438
9439        /* If we got a notification, handle it, and go back to looking
9440          for a packet.  */
9441       else
9442         {
9443           gdb_assert (c == '%');
9444
9445           if (remote_debug)
9446             {
9447               std::string str = escape_buffer (*buf, val);
9448
9449               fprintf_unfiltered (gdb_stdlog,
9450                                   "  Notification received: %s\n",
9451                                   str.c_str ());
9452             }
9453           if (is_notif != NULL)
9454             *is_notif = 1;
9455
9456           handle_notification (rs->notif_state, *buf);
9457
9458           /* Notifications require no acknowledgement.  */
9459
9460           if (expecting_notif)
9461             return val;
9462         }
9463     }
9464 }
9465
9466 static int
9467 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9468 {
9469   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9470 }
9471
9472 static int
9473 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9474                       int *is_notif)
9475 {
9476   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9477                                  is_notif);
9478 }
9479
9480 /* Check whether EVENT is a fork event for the process specified
9481    by the pid passed in DATA, and if it is, kill the fork child.  */
9482
9483 static int
9484 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9485                             QUEUE_ITER (stop_reply_p) *iter,
9486                             stop_reply_p event,
9487                             void *data)
9488 {
9489   struct queue_iter_param *param = (struct queue_iter_param *) data;
9490   int parent_pid = *(int *) param->input;
9491
9492   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9493     {
9494       struct remote_state *rs = get_remote_state ();
9495       int child_pid = ptid_get_pid (event->ws.value.related_pid);
9496       int res;
9497
9498       res = remote_vkill (child_pid, rs);
9499       if (res != 0)
9500         error (_("Can't kill fork child process %d"), child_pid);
9501     }
9502
9503   return 1;
9504 }
9505
9506 /* Kill any new fork children of process PID that haven't been
9507    processed by follow_fork.  */
9508
9509 static void
9510 kill_new_fork_children (int pid, struct remote_state *rs)
9511 {
9512   struct thread_info *thread;
9513   struct notif_client *notif = &notif_client_stop;
9514   struct queue_iter_param param;
9515
9516   /* Kill the fork child threads of any threads in process PID
9517      that are stopped at a fork event.  */
9518   ALL_NON_EXITED_THREADS (thread)
9519     {
9520       struct target_waitstatus *ws = &thread->pending_follow;
9521
9522       if (is_pending_fork_parent (ws, pid, thread->ptid))
9523         {
9524           struct remote_state *rs = get_remote_state ();
9525           int child_pid = ptid_get_pid (ws->value.related_pid);
9526           int res;
9527
9528           res = remote_vkill (child_pid, rs);
9529           if (res != 0)
9530             error (_("Can't kill fork child process %d"), child_pid);
9531         }
9532     }
9533
9534   /* Check for any pending fork events (not reported or processed yet)
9535      in process PID and kill those fork child threads as well.  */
9536   remote_notif_get_pending_events (notif);
9537   param.input = &pid;
9538   param.output = NULL;
9539   QUEUE_iterate (stop_reply_p, stop_reply_queue,
9540                  kill_child_of_pending_fork, &param);
9541 }
9542
9543 \f
9544 /* Target hook to kill the current inferior.  */
9545
9546 void
9547 remote_target::kill ()
9548 {
9549   int res = -1;
9550   int pid = ptid_get_pid (inferior_ptid);
9551   struct remote_state *rs = get_remote_state ();
9552
9553   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9554     {
9555       /* If we're stopped while forking and we haven't followed yet,
9556          kill the child task.  We need to do this before killing the
9557          parent task because if this is a vfork then the parent will
9558          be sleeping.  */
9559       kill_new_fork_children (pid, rs);
9560
9561       res = remote_vkill (pid, rs);
9562       if (res == 0)
9563         {
9564           target_mourn_inferior (inferior_ptid);
9565           return;
9566         }
9567     }
9568
9569   /* If we are in 'target remote' mode and we are killing the only
9570      inferior, then we will tell gdbserver to exit and unpush the
9571      target.  */
9572   if (res == -1 && !remote_multi_process_p (rs)
9573       && number_of_live_inferiors () == 1)
9574     {
9575       remote_kill_k ();
9576
9577       /* We've killed the remote end, we get to mourn it.  If we are
9578          not in extended mode, mourning the inferior also unpushes
9579          remote_ops from the target stack, which closes the remote
9580          connection.  */
9581       target_mourn_inferior (inferior_ptid);
9582
9583       return;
9584     }
9585
9586   error (_("Can't kill process"));
9587 }
9588
9589 /* Send a kill request to the target using the 'vKill' packet.  */
9590
9591 static int
9592 remote_vkill (int pid, struct remote_state *rs)
9593 {
9594   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9595     return -1;
9596
9597   /* Tell the remote target to detach.  */
9598   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9599   putpkt (rs->buf);
9600   getpkt (&rs->buf, &rs->buf_size, 0);
9601
9602   switch (packet_ok (rs->buf,
9603                      &remote_protocol_packets[PACKET_vKill]))
9604     {
9605     case PACKET_OK:
9606       return 0;
9607     case PACKET_ERROR:
9608       return 1;
9609     case PACKET_UNKNOWN:
9610       return -1;
9611     default:
9612       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9613     }
9614 }
9615
9616 /* Send a kill request to the target using the 'k' packet.  */
9617
9618 static void
9619 remote_kill_k (void)
9620 {
9621   /* Catch errors so the user can quit from gdb even when we
9622      aren't on speaking terms with the remote system.  */
9623   TRY
9624     {
9625       putpkt ("k");
9626     }
9627   CATCH (ex, RETURN_MASK_ERROR)
9628     {
9629       if (ex.error == TARGET_CLOSE_ERROR)
9630         {
9631           /* If we got an (EOF) error that caused the target
9632              to go away, then we're done, that's what we wanted.
9633              "k" is susceptible to cause a premature EOF, given
9634              that the remote server isn't actually required to
9635              reply to "k", and it can happen that it doesn't
9636              even get to reply ACK to the "k".  */
9637           return;
9638         }
9639
9640       /* Otherwise, something went wrong.  We didn't actually kill
9641          the target.  Just propagate the exception, and let the
9642          user or higher layers decide what to do.  */
9643       throw_exception (ex);
9644     }
9645   END_CATCH
9646 }
9647
9648 void
9649 remote_target::mourn_inferior ()
9650 {
9651   struct remote_state *rs = get_remote_state ();
9652
9653   /* In 'target remote' mode with one inferior, we close the connection.  */
9654   if (!rs->extended && number_of_live_inferiors () <= 1)
9655     {
9656       unpush_target (this);
9657
9658       /* remote_close takes care of doing most of the clean up.  */
9659       generic_mourn_inferior ();
9660       return;
9661     }
9662
9663   /* In case we got here due to an error, but we're going to stay
9664      connected.  */
9665   rs->waiting_for_stop_reply = 0;
9666
9667   /* If the current general thread belonged to the process we just
9668      detached from or has exited, the remote side current general
9669      thread becomes undefined.  Considering a case like this:
9670
9671      - We just got here due to a detach.
9672      - The process that we're detaching from happens to immediately
9673        report a global breakpoint being hit in non-stop mode, in the
9674        same thread we had selected before.
9675      - GDB attaches to this process again.
9676      - This event happens to be the next event we handle.
9677
9678      GDB would consider that the current general thread didn't need to
9679      be set on the stub side (with Hg), since for all it knew,
9680      GENERAL_THREAD hadn't changed.
9681
9682      Notice that although in all-stop mode, the remote server always
9683      sets the current thread to the thread reporting the stop event,
9684      that doesn't happen in non-stop mode; in non-stop, the stub *must
9685      not* change the current thread when reporting a breakpoint hit,
9686      due to the decoupling of event reporting and event handling.
9687
9688      To keep things simple, we always invalidate our notion of the
9689      current thread.  */
9690   record_currthread (rs, minus_one_ptid);
9691
9692   /* Call common code to mark the inferior as not running.  */
9693   generic_mourn_inferior ();
9694
9695   if (!have_inferiors ())
9696     {
9697       if (!remote_multi_process_p (rs))
9698         {
9699           /* Check whether the target is running now - some remote stubs
9700              automatically restart after kill.  */
9701           putpkt ("?");
9702           getpkt (&rs->buf, &rs->buf_size, 0);
9703
9704           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9705             {
9706               /* Assume that the target has been restarted.  Set
9707                  inferior_ptid so that bits of core GDB realizes
9708                  there's something here, e.g., so that the user can
9709                  say "kill" again.  */
9710               inferior_ptid = magic_null_ptid;
9711             }
9712         }
9713     }
9714 }
9715
9716 bool
9717 extended_remote_target::supports_disable_randomization ()
9718 {
9719   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9720 }
9721
9722 static void
9723 extended_remote_disable_randomization (int val)
9724 {
9725   struct remote_state *rs = get_remote_state ();
9726   char *reply;
9727
9728   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9729              val);
9730   putpkt (rs->buf);
9731   reply = remote_get_noisy_reply ();
9732   if (*reply == '\0')
9733     error (_("Target does not support QDisableRandomization."));
9734   if (strcmp (reply, "OK") != 0)
9735     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9736 }
9737
9738 static int
9739 extended_remote_run (const std::string &args)
9740 {
9741   struct remote_state *rs = get_remote_state ();
9742   int len;
9743   const char *remote_exec_file = get_remote_exec_file ();
9744
9745   /* If the user has disabled vRun support, or we have detected that
9746      support is not available, do not try it.  */
9747   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9748     return -1;
9749
9750   strcpy (rs->buf, "vRun;");
9751   len = strlen (rs->buf);
9752
9753   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9754     error (_("Remote file name too long for run packet"));
9755   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9756                       strlen (remote_exec_file));
9757
9758   if (!args.empty ())
9759     {
9760       int i;
9761
9762       gdb_argv argv (args.c_str ());
9763       for (i = 0; argv[i] != NULL; i++)
9764         {
9765           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9766             error (_("Argument list too long for run packet"));
9767           rs->buf[len++] = ';';
9768           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9769                               strlen (argv[i]));
9770         }
9771     }
9772
9773   rs->buf[len++] = '\0';
9774
9775   putpkt (rs->buf);
9776   getpkt (&rs->buf, &rs->buf_size, 0);
9777
9778   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9779     {
9780     case PACKET_OK:
9781       /* We have a wait response.  All is well.  */
9782       return 0;
9783     case PACKET_UNKNOWN:
9784       return -1;
9785     case PACKET_ERROR:
9786       if (remote_exec_file[0] == '\0')
9787         error (_("Running the default executable on the remote target failed; "
9788                  "try \"set remote exec-file\"?"));
9789       else
9790         error (_("Running \"%s\" on the remote target failed"),
9791                remote_exec_file);
9792     default:
9793       gdb_assert_not_reached (_("bad switch"));
9794     }
9795 }
9796
9797 /* Helper function to send set/unset environment packets.  ACTION is
9798    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
9799    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
9800    sent.  */
9801
9802 static void
9803 send_environment_packet (struct remote_state *rs,
9804                          const char *action,
9805                          const char *packet,
9806                          const char *value)
9807 {
9808   /* Convert the environment variable to an hex string, which
9809      is the best format to be transmitted over the wire.  */
9810   std::string encoded_value = bin2hex ((const gdb_byte *) value,
9811                                          strlen (value));
9812
9813   xsnprintf (rs->buf, get_remote_packet_size (),
9814              "%s:%s", packet, encoded_value.c_str ());
9815
9816   putpkt (rs->buf);
9817   getpkt (&rs->buf, &rs->buf_size, 0);
9818   if (strcmp (rs->buf, "OK") != 0)
9819     warning (_("Unable to %s environment variable '%s' on remote."),
9820              action, value);
9821 }
9822
9823 /* Helper function to handle the QEnvironment* packets.  */
9824
9825 static void
9826 extended_remote_environment_support (struct remote_state *rs)
9827 {
9828   if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9829     {
9830       putpkt ("QEnvironmentReset");
9831       getpkt (&rs->buf, &rs->buf_size, 0);
9832       if (strcmp (rs->buf, "OK") != 0)
9833         warning (_("Unable to reset environment on remote."));
9834     }
9835
9836   gdb_environ *e = &current_inferior ()->environment;
9837
9838   if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9839     for (const std::string &el : e->user_set_env ())
9840       send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9841                                el.c_str ());
9842
9843   if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9844     for (const std::string &el : e->user_unset_env ())
9845       send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9846 }
9847
9848 /* Helper function to set the current working directory for the
9849    inferior in the remote target.  */
9850
9851 static void
9852 extended_remote_set_inferior_cwd (struct remote_state *rs)
9853 {
9854   if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9855     {
9856       const char *inferior_cwd = get_inferior_cwd ();
9857
9858       if (inferior_cwd != NULL)
9859         {
9860           std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9861                                          strlen (inferior_cwd));
9862
9863           xsnprintf (rs->buf, get_remote_packet_size (),
9864                      "QSetWorkingDir:%s", hexpath.c_str ());
9865         }
9866       else
9867         {
9868           /* An empty inferior_cwd means that the user wants us to
9869              reset the remote server's inferior's cwd.  */
9870           xsnprintf (rs->buf, get_remote_packet_size (),
9871                      "QSetWorkingDir:");
9872         }
9873
9874       putpkt (rs->buf);
9875       getpkt (&rs->buf, &rs->buf_size, 0);
9876       if (packet_ok (rs->buf,
9877                      &remote_protocol_packets[PACKET_QSetWorkingDir])
9878           != PACKET_OK)
9879         error (_("\
9880 Remote replied unexpectedly while setting the inferior's working\n\
9881 directory: %s"),
9882                rs->buf);
9883
9884     }
9885 }
9886
9887 /* In the extended protocol we want to be able to do things like
9888    "run" and have them basically work as expected.  So we need
9889    a special create_inferior function.  We support changing the
9890    executable file and the command line arguments, but not the
9891    environment.  */
9892
9893 void
9894 extended_remote_target::create_inferior (const char *exec_file,
9895                                          const std::string &args,
9896                                          char **env, int from_tty)
9897 {
9898   int run_worked;
9899   char *stop_reply;
9900   struct remote_state *rs = get_remote_state ();
9901   const char *remote_exec_file = get_remote_exec_file ();
9902
9903   /* If running asynchronously, register the target file descriptor
9904      with the event loop.  */
9905   if (target_can_async_p ())
9906     target_async (1);
9907
9908   /* Disable address space randomization if requested (and supported).  */
9909   if (supports_disable_randomization ())
9910     extended_remote_disable_randomization (disable_randomization);
9911
9912   /* If startup-with-shell is on, we inform gdbserver to start the
9913      remote inferior using a shell.  */
9914   if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9915     {
9916       xsnprintf (rs->buf, get_remote_packet_size (),
9917                  "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9918       putpkt (rs->buf);
9919       getpkt (&rs->buf, &rs->buf_size, 0);
9920       if (strcmp (rs->buf, "OK") != 0)
9921         error (_("\
9922 Remote replied unexpectedly while setting startup-with-shell: %s"),
9923                rs->buf);
9924     }
9925
9926   extended_remote_environment_support (rs);
9927
9928   extended_remote_set_inferior_cwd (rs);
9929
9930   /* Now restart the remote server.  */
9931   run_worked = extended_remote_run (args) != -1;
9932   if (!run_worked)
9933     {
9934       /* vRun was not supported.  Fail if we need it to do what the
9935          user requested.  */
9936       if (remote_exec_file[0])
9937         error (_("Remote target does not support \"set remote exec-file\""));
9938       if (!args.empty ())
9939         error (_("Remote target does not support \"set args\" or run <ARGS>"));
9940
9941       /* Fall back to "R".  */
9942       extended_remote_restart ();
9943     }
9944
9945   if (!have_inferiors ())
9946     {
9947       /* Clean up from the last time we ran, before we mark the target
9948          running again.  This will mark breakpoints uninserted, and
9949          get_offsets may insert breakpoints.  */
9950       init_thread_list ();
9951       init_wait_for_inferior ();
9952     }
9953
9954   /* vRun's success return is a stop reply.  */
9955   stop_reply = run_worked ? rs->buf : NULL;
9956   add_current_inferior_and_thread (stop_reply);
9957
9958   /* Get updated offsets, if the stub uses qOffsets.  */
9959   get_offsets ();
9960 }
9961 \f
9962
9963 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
9964    the list of conditions (in agent expression bytecode format), if any, the
9965    target needs to evaluate.  The output is placed into the packet buffer
9966    started from BUF and ended at BUF_END.  */
9967
9968 static int
9969 remote_add_target_side_condition (struct gdbarch *gdbarch,
9970                                   struct bp_target_info *bp_tgt, char *buf,
9971                                   char *buf_end)
9972 {
9973   if (bp_tgt->conditions.empty ())
9974     return 0;
9975
9976   buf += strlen (buf);
9977   xsnprintf (buf, buf_end - buf, "%s", ";");
9978   buf++;
9979
9980   /* Send conditions to the target.  */
9981   for (agent_expr *aexpr : bp_tgt->conditions)
9982     {
9983       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9984       buf += strlen (buf);
9985       for (int i = 0; i < aexpr->len; ++i)
9986         buf = pack_hex_byte (buf, aexpr->buf[i]);
9987       *buf = '\0';
9988     }
9989   return 0;
9990 }
9991
9992 static void
9993 remote_add_target_side_commands (struct gdbarch *gdbarch,
9994                                  struct bp_target_info *bp_tgt, char *buf)
9995 {
9996   if (bp_tgt->tcommands.empty ())
9997     return;
9998
9999   buf += strlen (buf);
10000
10001   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10002   buf += strlen (buf);
10003
10004   /* Concatenate all the agent expressions that are commands into the
10005      cmds parameter.  */
10006   for (agent_expr *aexpr : bp_tgt->tcommands)
10007     {
10008       sprintf (buf, "X%x,", aexpr->len);
10009       buf += strlen (buf);
10010       for (int i = 0; i < aexpr->len; ++i)
10011         buf = pack_hex_byte (buf, aexpr->buf[i]);
10012       *buf = '\0';
10013     }
10014 }
10015
10016 /* Insert a breakpoint.  On targets that have software breakpoint
10017    support, we ask the remote target to do the work; on targets
10018    which don't, we insert a traditional memory breakpoint.  */
10019
10020 int
10021 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10022                                   struct bp_target_info *bp_tgt)
10023 {
10024   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10025      If it succeeds, then set the support to PACKET_ENABLE.  If it
10026      fails, and the user has explicitly requested the Z support then
10027      report an error, otherwise, mark it disabled and go on.  */
10028
10029   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10030     {
10031       CORE_ADDR addr = bp_tgt->reqstd_address;
10032       struct remote_state *rs;
10033       char *p, *endbuf;
10034
10035       /* Make sure the remote is pointing at the right process, if
10036          necessary.  */
10037       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10038         set_general_process ();
10039
10040       rs = get_remote_state ();
10041       p = rs->buf;
10042       endbuf = rs->buf + get_remote_packet_size ();
10043
10044       *(p++) = 'Z';
10045       *(p++) = '0';
10046       *(p++) = ',';
10047       addr = (ULONGEST) remote_address_masked (addr);
10048       p += hexnumstr (p, addr);
10049       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10050
10051       if (supports_evaluation_of_breakpoint_conditions ())
10052         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10053
10054       if (can_run_breakpoint_commands ())
10055         remote_add_target_side_commands (gdbarch, bp_tgt, p);
10056
10057       putpkt (rs->buf);
10058       getpkt (&rs->buf, &rs->buf_size, 0);
10059
10060       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10061         {
10062         case PACKET_ERROR:
10063           return -1;
10064         case PACKET_OK:
10065           return 0;
10066         case PACKET_UNKNOWN:
10067           break;
10068         }
10069     }
10070
10071   /* If this breakpoint has target-side commands but this stub doesn't
10072      support Z0 packets, throw error.  */
10073   if (!bp_tgt->tcommands.empty ())
10074     throw_error (NOT_SUPPORTED_ERROR, _("\
10075 Target doesn't support breakpoints that have target side commands."));
10076
10077   return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10078 }
10079
10080 int
10081 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10082                                   struct bp_target_info *bp_tgt,
10083                                   enum remove_bp_reason reason)
10084 {
10085   CORE_ADDR addr = bp_tgt->placed_address;
10086   struct remote_state *rs = get_remote_state ();
10087
10088   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10089     {
10090       char *p = rs->buf;
10091       char *endbuf = rs->buf + get_remote_packet_size ();
10092
10093       /* Make sure the remote is pointing at the right process, if
10094          necessary.  */
10095       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10096         set_general_process ();
10097
10098       *(p++) = 'z';
10099       *(p++) = '0';
10100       *(p++) = ',';
10101
10102       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10103       p += hexnumstr (p, addr);
10104       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10105
10106       putpkt (rs->buf);
10107       getpkt (&rs->buf, &rs->buf_size, 0);
10108
10109       return (rs->buf[0] == 'E');
10110     }
10111
10112   return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10113 }
10114
10115 static enum Z_packet_type
10116 watchpoint_to_Z_packet (int type)
10117 {
10118   switch (type)
10119     {
10120     case hw_write:
10121       return Z_PACKET_WRITE_WP;
10122       break;
10123     case hw_read:
10124       return Z_PACKET_READ_WP;
10125       break;
10126     case hw_access:
10127       return Z_PACKET_ACCESS_WP;
10128       break;
10129     default:
10130       internal_error (__FILE__, __LINE__,
10131                       _("hw_bp_to_z: bad watchpoint type %d"), type);
10132     }
10133 }
10134
10135 int
10136 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10137                                   enum target_hw_bp_type type, struct expression *cond)
10138 {
10139   struct remote_state *rs = get_remote_state ();
10140   char *endbuf = rs->buf + get_remote_packet_size ();
10141   char *p;
10142   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10143
10144   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10145     return 1;
10146
10147   /* Make sure the remote is pointing at the right process, if
10148      necessary.  */
10149   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10150     set_general_process ();
10151
10152   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10153   p = strchr (rs->buf, '\0');
10154   addr = remote_address_masked (addr);
10155   p += hexnumstr (p, (ULONGEST) addr);
10156   xsnprintf (p, endbuf - p, ",%x", len);
10157
10158   putpkt (rs->buf);
10159   getpkt (&rs->buf, &rs->buf_size, 0);
10160
10161   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10162     {
10163     case PACKET_ERROR:
10164       return -1;
10165     case PACKET_UNKNOWN:
10166       return 1;
10167     case PACKET_OK:
10168       return 0;
10169     }
10170   internal_error (__FILE__, __LINE__,
10171                   _("remote_insert_watchpoint: reached end of function"));
10172 }
10173
10174 bool
10175 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10176                                              CORE_ADDR start, int length)
10177 {
10178   CORE_ADDR diff = remote_address_masked (addr - start);
10179
10180   return diff < length;
10181 }
10182
10183
10184 int
10185 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10186                                   enum target_hw_bp_type type, struct expression *cond)
10187 {
10188   struct remote_state *rs = get_remote_state ();
10189   char *endbuf = rs->buf + get_remote_packet_size ();
10190   char *p;
10191   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10192
10193   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10194     return -1;
10195
10196   /* Make sure the remote is pointing at the right process, if
10197      necessary.  */
10198   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10199     set_general_process ();
10200
10201   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10202   p = strchr (rs->buf, '\0');
10203   addr = remote_address_masked (addr);
10204   p += hexnumstr (p, (ULONGEST) addr);
10205   xsnprintf (p, endbuf - p, ",%x", len);
10206   putpkt (rs->buf);
10207   getpkt (&rs->buf, &rs->buf_size, 0);
10208
10209   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10210     {
10211     case PACKET_ERROR:
10212     case PACKET_UNKNOWN:
10213       return -1;
10214     case PACKET_OK:
10215       return 0;
10216     }
10217   internal_error (__FILE__, __LINE__,
10218                   _("remote_remove_watchpoint: reached end of function"));
10219 }
10220
10221
10222 int remote_hw_watchpoint_limit = -1;
10223 int remote_hw_watchpoint_length_limit = -1;
10224 int remote_hw_breakpoint_limit = -1;
10225
10226 int
10227 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10228 {
10229   if (remote_hw_watchpoint_length_limit == 0)
10230     return 0;
10231   else if (remote_hw_watchpoint_length_limit < 0)
10232     return 1;
10233   else if (len <= remote_hw_watchpoint_length_limit)
10234     return 1;
10235   else
10236     return 0;
10237 }
10238
10239 int
10240 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10241 {
10242   if (type == bp_hardware_breakpoint)
10243     {
10244       if (remote_hw_breakpoint_limit == 0)
10245         return 0;
10246       else if (remote_hw_breakpoint_limit < 0)
10247         return 1;
10248       else if (cnt <= remote_hw_breakpoint_limit)
10249         return 1;
10250     }
10251   else
10252     {
10253       if (remote_hw_watchpoint_limit == 0)
10254         return 0;
10255       else if (remote_hw_watchpoint_limit < 0)
10256         return 1;
10257       else if (ot)
10258         return -1;
10259       else if (cnt <= remote_hw_watchpoint_limit)
10260         return 1;
10261     }
10262   return -1;
10263 }
10264
10265 /* The to_stopped_by_sw_breakpoint method of target remote.  */
10266
10267 bool
10268 remote_target::stopped_by_sw_breakpoint ()
10269 {
10270   struct thread_info *thread = inferior_thread ();
10271
10272   return (thread->priv != NULL
10273           && (get_remote_thread_info (thread)->stop_reason
10274               == TARGET_STOPPED_BY_SW_BREAKPOINT));
10275 }
10276
10277 /* The to_supports_stopped_by_sw_breakpoint method of target
10278    remote.  */
10279
10280 bool
10281 remote_target::supports_stopped_by_sw_breakpoint ()
10282 {
10283   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10284 }
10285
10286 /* The to_stopped_by_hw_breakpoint method of target remote.  */
10287
10288 bool
10289 remote_target::stopped_by_hw_breakpoint ()
10290 {
10291   struct thread_info *thread = inferior_thread ();
10292
10293   return (thread->priv != NULL
10294           && (get_remote_thread_info (thread)->stop_reason
10295               == TARGET_STOPPED_BY_HW_BREAKPOINT));
10296 }
10297
10298 /* The to_supports_stopped_by_hw_breakpoint method of target
10299    remote.  */
10300
10301 bool
10302 remote_target::supports_stopped_by_hw_breakpoint ()
10303 {
10304   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10305 }
10306
10307 bool
10308 remote_target::stopped_by_watchpoint ()
10309 {
10310   struct thread_info *thread = inferior_thread ();
10311
10312   return (thread->priv != NULL
10313           && (get_remote_thread_info (thread)->stop_reason
10314               == TARGET_STOPPED_BY_WATCHPOINT));
10315 }
10316
10317 bool
10318 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10319 {
10320   struct thread_info *thread = inferior_thread ();
10321
10322   if (thread->priv != NULL
10323       && (get_remote_thread_info (thread)->stop_reason
10324           == TARGET_STOPPED_BY_WATCHPOINT))
10325     {
10326       *addr_p = get_remote_thread_info (thread)->watch_data_address;
10327       return true;
10328     }
10329
10330   return false;
10331 }
10332
10333
10334 int
10335 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10336                                      struct bp_target_info *bp_tgt)
10337 {
10338   CORE_ADDR addr = bp_tgt->reqstd_address;
10339   struct remote_state *rs;
10340   char *p, *endbuf;
10341   char *message;
10342
10343   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10344     return -1;
10345
10346   /* Make sure the remote is pointing at the right process, if
10347      necessary.  */
10348   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10349     set_general_process ();
10350
10351   rs = get_remote_state ();
10352   p = rs->buf;
10353   endbuf = rs->buf + get_remote_packet_size ();
10354
10355   *(p++) = 'Z';
10356   *(p++) = '1';
10357   *(p++) = ',';
10358
10359   addr = remote_address_masked (addr);
10360   p += hexnumstr (p, (ULONGEST) addr);
10361   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10362
10363   if (supports_evaluation_of_breakpoint_conditions ())
10364     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10365
10366   if (can_run_breakpoint_commands ())
10367     remote_add_target_side_commands (gdbarch, bp_tgt, p);
10368
10369   putpkt (rs->buf);
10370   getpkt (&rs->buf, &rs->buf_size, 0);
10371
10372   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10373     {
10374     case PACKET_ERROR:
10375       if (rs->buf[1] == '.')
10376         {
10377           message = strchr (rs->buf + 2, '.');
10378           if (message)
10379             error (_("Remote failure reply: %s"), message + 1);
10380         }
10381       return -1;
10382     case PACKET_UNKNOWN:
10383       return -1;
10384     case PACKET_OK:
10385       return 0;
10386     }
10387   internal_error (__FILE__, __LINE__,
10388                   _("remote_insert_hw_breakpoint: reached end of function"));
10389 }
10390
10391
10392 int
10393 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10394                                      struct bp_target_info *bp_tgt)
10395 {
10396   CORE_ADDR addr;
10397   struct remote_state *rs = get_remote_state ();
10398   char *p = rs->buf;
10399   char *endbuf = rs->buf + get_remote_packet_size ();
10400
10401   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10402     return -1;
10403
10404   /* Make sure the remote is pointing at the right process, if
10405      necessary.  */
10406   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10407     set_general_process ();
10408
10409   *(p++) = 'z';
10410   *(p++) = '1';
10411   *(p++) = ',';
10412
10413   addr = remote_address_masked (bp_tgt->placed_address);
10414   p += hexnumstr (p, (ULONGEST) addr);
10415   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
10416
10417   putpkt (rs->buf);
10418   getpkt (&rs->buf, &rs->buf_size, 0);
10419
10420   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10421     {
10422     case PACKET_ERROR:
10423     case PACKET_UNKNOWN:
10424       return -1;
10425     case PACKET_OK:
10426       return 0;
10427     }
10428   internal_error (__FILE__, __LINE__,
10429                   _("remote_remove_hw_breakpoint: reached end of function"));
10430 }
10431
10432 /* Verify memory using the "qCRC:" request.  */
10433
10434 int
10435 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10436 {
10437   struct remote_state *rs = get_remote_state ();
10438   unsigned long host_crc, target_crc;
10439   char *tmp;
10440
10441   /* It doesn't make sense to use qCRC if the remote target is
10442      connected but not running.  */
10443   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10444     {
10445       enum packet_result result;
10446
10447       /* Make sure the remote is pointing at the right process.  */
10448       set_general_process ();
10449
10450       /* FIXME: assumes lma can fit into long.  */
10451       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10452                  (long) lma, (long) size);
10453       putpkt (rs->buf);
10454
10455       /* Be clever; compute the host_crc before waiting for target
10456          reply.  */
10457       host_crc = xcrc32 (data, size, 0xffffffff);
10458
10459       getpkt (&rs->buf, &rs->buf_size, 0);
10460
10461       result = packet_ok (rs->buf,
10462                           &remote_protocol_packets[PACKET_qCRC]);
10463       if (result == PACKET_ERROR)
10464         return -1;
10465       else if (result == PACKET_OK)
10466         {
10467           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10468             target_crc = target_crc * 16 + fromhex (*tmp);
10469
10470           return (host_crc == target_crc);
10471         }
10472     }
10473
10474   return simple_verify_memory (this, data, lma, size);
10475 }
10476
10477 /* compare-sections command
10478
10479    With no arguments, compares each loadable section in the exec bfd
10480    with the same memory range on the target, and reports mismatches.
10481    Useful for verifying the image on the target against the exec file.  */
10482
10483 static void
10484 compare_sections_command (const char *args, int from_tty)
10485 {
10486   asection *s;
10487   const char *sectname;
10488   bfd_size_type size;
10489   bfd_vma lma;
10490   int matched = 0;
10491   int mismatched = 0;
10492   int res;
10493   int read_only = 0;
10494
10495   if (!exec_bfd)
10496     error (_("command cannot be used without an exec file"));
10497
10498   /* Make sure the remote is pointing at the right process.  */
10499   set_general_process ();
10500
10501   if (args != NULL && strcmp (args, "-r") == 0)
10502     {
10503       read_only = 1;
10504       args = NULL;
10505     }
10506
10507   for (s = exec_bfd->sections; s; s = s->next)
10508     {
10509       if (!(s->flags & SEC_LOAD))
10510         continue;               /* Skip non-loadable section.  */
10511
10512       if (read_only && (s->flags & SEC_READONLY) == 0)
10513         continue;               /* Skip writeable sections */
10514
10515       size = bfd_get_section_size (s);
10516       if (size == 0)
10517         continue;               /* Skip zero-length section.  */
10518
10519       sectname = bfd_get_section_name (exec_bfd, s);
10520       if (args && strcmp (args, sectname) != 0)
10521         continue;               /* Not the section selected by user.  */
10522
10523       matched = 1;              /* Do this section.  */
10524       lma = s->lma;
10525
10526       gdb::byte_vector sectdata (size);
10527       bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10528
10529       res = target_verify_memory (sectdata.data (), lma, size);
10530
10531       if (res == -1)
10532         error (_("target memory fault, section %s, range %s -- %s"), sectname,
10533                paddress (target_gdbarch (), lma),
10534                paddress (target_gdbarch (), lma + size));
10535
10536       printf_filtered ("Section %s, range %s -- %s: ", sectname,
10537                        paddress (target_gdbarch (), lma),
10538                        paddress (target_gdbarch (), lma + size));
10539       if (res)
10540         printf_filtered ("matched.\n");
10541       else
10542         {
10543           printf_filtered ("MIS-MATCHED!\n");
10544           mismatched++;
10545         }
10546     }
10547   if (mismatched > 0)
10548     warning (_("One or more sections of the target image does not match\n\
10549 the loaded file\n"));
10550   if (args && !matched)
10551     printf_filtered (_("No loaded section named '%s'.\n"), args);
10552 }
10553
10554 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10555    into remote target.  The number of bytes written to the remote
10556    target is returned, or -1 for error.  */
10557
10558 static enum target_xfer_status
10559 remote_write_qxfer (const char *object_name,
10560                     const char *annex, const gdb_byte *writebuf, 
10561                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10562                     struct packet_config *packet)
10563 {
10564   int i, buf_len;
10565   ULONGEST n;
10566   struct remote_state *rs = get_remote_state ();
10567   int max_size = get_memory_write_packet_size (); 
10568
10569   if (packet_config_support (packet) == PACKET_DISABLE)
10570     return TARGET_XFER_E_IO;
10571
10572   /* Insert header.  */
10573   i = snprintf (rs->buf, max_size, 
10574                 "qXfer:%s:write:%s:%s:",
10575                 object_name, annex ? annex : "",
10576                 phex_nz (offset, sizeof offset));
10577   max_size -= (i + 1);
10578
10579   /* Escape as much data as fits into rs->buf.  */
10580   buf_len = remote_escape_output 
10581     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10582
10583   if (putpkt_binary (rs->buf, i + buf_len) < 0
10584       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10585       || packet_ok (rs->buf, packet) != PACKET_OK)
10586     return TARGET_XFER_E_IO;
10587
10588   unpack_varlen_hex (rs->buf, &n);
10589
10590   *xfered_len = n;
10591   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10592 }
10593
10594 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10595    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10596    number of bytes read is returned, or 0 for EOF, or -1 for error.
10597    The number of bytes read may be less than LEN without indicating an
10598    EOF.  PACKET is checked and updated to indicate whether the remote
10599    target supports this object.  */
10600
10601 static enum target_xfer_status
10602 remote_read_qxfer (const char *object_name,
10603                    const char *annex,
10604                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10605                    ULONGEST *xfered_len,
10606                    struct packet_config *packet)
10607 {
10608   struct remote_state *rs = get_remote_state ();
10609   LONGEST i, n, packet_len;
10610
10611   if (packet_config_support (packet) == PACKET_DISABLE)
10612     return TARGET_XFER_E_IO;
10613
10614   /* Check whether we've cached an end-of-object packet that matches
10615      this request.  */
10616   if (rs->finished_object)
10617     {
10618       if (strcmp (object_name, rs->finished_object) == 0
10619           && strcmp (annex ? annex : "", rs->finished_annex) == 0
10620           && offset == rs->finished_offset)
10621         return TARGET_XFER_EOF;
10622
10623
10624       /* Otherwise, we're now reading something different.  Discard
10625          the cache.  */
10626       xfree (rs->finished_object);
10627       xfree (rs->finished_annex);
10628       rs->finished_object = NULL;
10629       rs->finished_annex = NULL;
10630     }
10631
10632   /* Request only enough to fit in a single packet.  The actual data
10633      may not, since we don't know how much of it will need to be escaped;
10634      the target is free to respond with slightly less data.  We subtract
10635      five to account for the response type and the protocol frame.  */
10636   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10637   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10638             object_name, annex ? annex : "",
10639             phex_nz (offset, sizeof offset),
10640             phex_nz (n, sizeof n));
10641   i = putpkt (rs->buf);
10642   if (i < 0)
10643     return TARGET_XFER_E_IO;
10644
10645   rs->buf[0] = '\0';
10646   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10647   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10648     return TARGET_XFER_E_IO;
10649
10650   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10651     error (_("Unknown remote qXfer reply: %s"), rs->buf);
10652
10653   /* 'm' means there is (or at least might be) more data after this
10654      batch.  That does not make sense unless there's at least one byte
10655      of data in this reply.  */
10656   if (rs->buf[0] == 'm' && packet_len == 1)
10657     error (_("Remote qXfer reply contained no data."));
10658
10659   /* Got some data.  */
10660   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10661                              packet_len - 1, readbuf, n);
10662
10663   /* 'l' is an EOF marker, possibly including a final block of data,
10664      or possibly empty.  If we have the final block of a non-empty
10665      object, record this fact to bypass a subsequent partial read.  */
10666   if (rs->buf[0] == 'l' && offset + i > 0)
10667     {
10668       rs->finished_object = xstrdup (object_name);
10669       rs->finished_annex = xstrdup (annex ? annex : "");
10670       rs->finished_offset = offset + i;
10671     }
10672
10673   if (i == 0)
10674     return TARGET_XFER_EOF;
10675   else
10676     {
10677       *xfered_len = i;
10678       return TARGET_XFER_OK;
10679     }
10680 }
10681
10682 enum target_xfer_status
10683 remote_target::xfer_partial (enum target_object object,
10684                              const char *annex, gdb_byte *readbuf,
10685                              const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10686                              ULONGEST *xfered_len)
10687 {
10688   struct remote_state *rs;
10689   int i;
10690   char *p2;
10691   char query_type;
10692   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10693
10694   set_remote_traceframe ();
10695   set_general_thread (inferior_ptid);
10696
10697   rs = get_remote_state ();
10698
10699   /* Handle memory using the standard memory routines.  */
10700   if (object == TARGET_OBJECT_MEMORY)
10701     {
10702       /* If the remote target is connected but not running, we should
10703          pass this request down to a lower stratum (e.g. the executable
10704          file).  */
10705       if (!target_has_execution)
10706         return TARGET_XFER_EOF;
10707
10708       if (writebuf != NULL)
10709         return remote_write_bytes (offset, writebuf, len, unit_size,
10710                                    xfered_len);
10711       else
10712         return remote_read_bytes (this, offset, readbuf, len, unit_size,
10713                                   xfered_len);
10714     }
10715
10716   /* Handle SPU memory using qxfer packets.  */
10717   if (object == TARGET_OBJECT_SPU)
10718     {
10719       if (readbuf)
10720         return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10721                                   xfered_len, &remote_protocol_packets
10722                                   [PACKET_qXfer_spu_read]);
10723       else
10724         return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10725                                    xfered_len, &remote_protocol_packets
10726                                    [PACKET_qXfer_spu_write]);
10727     }
10728
10729   /* Handle extra signal info using qxfer packets.  */
10730   if (object == TARGET_OBJECT_SIGNAL_INFO)
10731     {
10732       if (readbuf)
10733         return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10734                                   xfered_len, &remote_protocol_packets
10735                                   [PACKET_qXfer_siginfo_read]);
10736       else
10737         return remote_write_qxfer ("siginfo", annex,
10738                                    writebuf, offset, len, xfered_len,
10739                                    &remote_protocol_packets
10740                                    [PACKET_qXfer_siginfo_write]);
10741     }
10742
10743   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10744     {
10745       if (readbuf)
10746         return remote_read_qxfer ("statictrace", annex,
10747                                   readbuf, offset, len, xfered_len,
10748                                   &remote_protocol_packets
10749                                   [PACKET_qXfer_statictrace_read]);
10750       else
10751         return TARGET_XFER_E_IO;
10752     }
10753
10754   /* Only handle flash writes.  */
10755   if (writebuf != NULL)
10756     {
10757       switch (object)
10758         {
10759         case TARGET_OBJECT_FLASH:
10760           return remote_flash_write (this, offset, len, xfered_len,
10761                                      writebuf);
10762
10763         default:
10764           return TARGET_XFER_E_IO;
10765         }
10766     }
10767
10768   /* Map pre-existing objects onto letters.  DO NOT do this for new
10769      objects!!!  Instead specify new query packets.  */
10770   switch (object)
10771     {
10772     case TARGET_OBJECT_AVR:
10773       query_type = 'R';
10774       break;
10775
10776     case TARGET_OBJECT_AUXV:
10777       gdb_assert (annex == NULL);
10778       return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10779                                 xfered_len,
10780                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10781
10782     case TARGET_OBJECT_AVAILABLE_FEATURES:
10783       return remote_read_qxfer
10784         ("features", annex, readbuf, offset, len, xfered_len,
10785          &remote_protocol_packets[PACKET_qXfer_features]);
10786
10787     case TARGET_OBJECT_LIBRARIES:
10788       return remote_read_qxfer
10789         ("libraries", annex, readbuf, offset, len, xfered_len,
10790          &remote_protocol_packets[PACKET_qXfer_libraries]);
10791
10792     case TARGET_OBJECT_LIBRARIES_SVR4:
10793       return remote_read_qxfer
10794         ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10795          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10796
10797     case TARGET_OBJECT_MEMORY_MAP:
10798       gdb_assert (annex == NULL);
10799       return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10800                                  xfered_len,
10801                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10802
10803     case TARGET_OBJECT_OSDATA:
10804       /* Should only get here if we're connected.  */
10805       gdb_assert (rs->remote_desc);
10806       return remote_read_qxfer
10807         ("osdata", annex, readbuf, offset, len, xfered_len,
10808         &remote_protocol_packets[PACKET_qXfer_osdata]);
10809
10810     case TARGET_OBJECT_THREADS:
10811       gdb_assert (annex == NULL);
10812       return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10813                                 xfered_len,
10814                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10815
10816     case TARGET_OBJECT_TRACEFRAME_INFO:
10817       gdb_assert (annex == NULL);
10818       return remote_read_qxfer
10819         ("traceframe-info", annex, readbuf, offset, len, xfered_len,
10820          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10821
10822     case TARGET_OBJECT_FDPIC:
10823       return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
10824                                 xfered_len,
10825                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10826
10827     case TARGET_OBJECT_OPENVMS_UIB:
10828       return remote_read_qxfer ("uib", annex, readbuf, offset, len,
10829                                 xfered_len,
10830                                 &remote_protocol_packets[PACKET_qXfer_uib]);
10831
10832     case TARGET_OBJECT_BTRACE:
10833       return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
10834                                 xfered_len,
10835         &remote_protocol_packets[PACKET_qXfer_btrace]);
10836
10837     case TARGET_OBJECT_BTRACE_CONF:
10838       return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
10839                                 len, xfered_len,
10840         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10841
10842     case TARGET_OBJECT_EXEC_FILE:
10843       return remote_read_qxfer ("exec-file", annex, readbuf, offset,
10844                                 len, xfered_len,
10845         &remote_protocol_packets[PACKET_qXfer_exec_file]);
10846
10847     default:
10848       return TARGET_XFER_E_IO;
10849     }
10850
10851   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
10852      large enough let the caller deal with it.  */
10853   if (len < get_remote_packet_size ())
10854     return TARGET_XFER_E_IO;
10855   len = get_remote_packet_size ();
10856
10857   /* Except for querying the minimum buffer size, target must be open.  */
10858   if (!rs->remote_desc)
10859     error (_("remote query is only available after target open"));
10860
10861   gdb_assert (annex != NULL);
10862   gdb_assert (readbuf != NULL);
10863
10864   p2 = rs->buf;
10865   *p2++ = 'q';
10866   *p2++ = query_type;
10867
10868   /* We used one buffer char for the remote protocol q command and
10869      another for the query type.  As the remote protocol encapsulation
10870      uses 4 chars plus one extra in case we are debugging
10871      (remote_debug), we have PBUFZIZ - 7 left to pack the query
10872      string.  */
10873   i = 0;
10874   while (annex[i] && (i < (get_remote_packet_size () - 8)))
10875     {
10876       /* Bad caller may have sent forbidden characters.  */
10877       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10878       *p2++ = annex[i];
10879       i++;
10880     }
10881   *p2 = '\0';
10882   gdb_assert (annex[i] == '\0');
10883
10884   i = putpkt (rs->buf);
10885   if (i < 0)
10886     return TARGET_XFER_E_IO;
10887
10888   getpkt (&rs->buf, &rs->buf_size, 0);
10889   strcpy ((char *) readbuf, rs->buf);
10890
10891   *xfered_len = strlen ((char *) readbuf);
10892   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10893 }
10894
10895 /* Implementation of to_get_memory_xfer_limit.  */
10896
10897 ULONGEST
10898 remote_target::get_memory_xfer_limit ()
10899 {
10900   return get_memory_write_packet_size ();
10901 }
10902
10903 int
10904 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
10905                               const gdb_byte *pattern, ULONGEST pattern_len,
10906                               CORE_ADDR *found_addrp)
10907 {
10908   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10909   struct remote_state *rs = get_remote_state ();
10910   int max_size = get_memory_write_packet_size ();
10911   struct packet_config *packet =
10912     &remote_protocol_packets[PACKET_qSearch_memory];
10913   /* Number of packet bytes used to encode the pattern;
10914      this could be more than PATTERN_LEN due to escape characters.  */
10915   int escaped_pattern_len;
10916   /* Amount of pattern that was encodable in the packet.  */
10917   int used_pattern_len;
10918   int i;
10919   int found;
10920   ULONGEST found_addr;
10921
10922   /* Don't go to the target if we don't have to.  This is done before
10923      checking packet_config_support to avoid the possibility that a
10924      success for this edge case means the facility works in
10925      general.  */
10926   if (pattern_len > search_space_len)
10927     return 0;
10928   if (pattern_len == 0)
10929     {
10930       *found_addrp = start_addr;
10931       return 1;
10932     }
10933
10934   /* If we already know the packet isn't supported, fall back to the simple
10935      way of searching memory.  */
10936
10937   if (packet_config_support (packet) == PACKET_DISABLE)
10938     {
10939       /* Target doesn't provided special support, fall back and use the
10940          standard support (copy memory and do the search here).  */
10941       return simple_search_memory (this, start_addr, search_space_len,
10942                                    pattern, pattern_len, found_addrp);
10943     }
10944
10945   /* Make sure the remote is pointing at the right process.  */
10946   set_general_process ();
10947
10948   /* Insert header.  */
10949   i = snprintf (rs->buf, max_size, 
10950                 "qSearch:memory:%s;%s;",
10951                 phex_nz (start_addr, addr_size),
10952                 phex_nz (search_space_len, sizeof (search_space_len)));
10953   max_size -= (i + 1);
10954
10955   /* Escape as much data as fits into rs->buf.  */
10956   escaped_pattern_len =
10957     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10958                           &used_pattern_len, max_size);
10959
10960   /* Bail if the pattern is too large.  */
10961   if (used_pattern_len != pattern_len)
10962     error (_("Pattern is too large to transmit to remote target."));
10963
10964   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10965       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10966       || packet_ok (rs->buf, packet) != PACKET_OK)
10967     {
10968       /* The request may not have worked because the command is not
10969          supported.  If so, fall back to the simple way.  */
10970       if (packet_config_support (packet) == PACKET_DISABLE)
10971         {
10972           return simple_search_memory (this, start_addr, search_space_len,
10973                                        pattern, pattern_len, found_addrp);
10974         }
10975       return -1;
10976     }
10977
10978   if (rs->buf[0] == '0')
10979     found = 0;
10980   else if (rs->buf[0] == '1')
10981     {
10982       found = 1;
10983       if (rs->buf[1] != ',')
10984         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10985       unpack_varlen_hex (rs->buf + 2, &found_addr);
10986       *found_addrp = found_addr;
10987     }
10988   else
10989     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10990
10991   return found;
10992 }
10993
10994 void
10995 remote_target::rcmd (const char *command, struct ui_file *outbuf)
10996 {
10997   struct remote_state *rs = get_remote_state ();
10998   char *p = rs->buf;
10999
11000   if (!rs->remote_desc)
11001     error (_("remote rcmd is only available after target open"));
11002
11003   /* Send a NULL command across as an empty command.  */
11004   if (command == NULL)
11005     command = "";
11006
11007   /* The query prefix.  */
11008   strcpy (rs->buf, "qRcmd,");
11009   p = strchr (rs->buf, '\0');
11010
11011   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11012       > get_remote_packet_size ())
11013     error (_("\"monitor\" command ``%s'' is too long."), command);
11014
11015   /* Encode the actual command.  */
11016   bin2hex ((const gdb_byte *) command, p, strlen (command));
11017
11018   if (putpkt (rs->buf) < 0)
11019     error (_("Communication problem with target."));
11020
11021   /* get/display the response */
11022   while (1)
11023     {
11024       char *buf;
11025
11026       /* XXX - see also remote_get_noisy_reply().  */
11027       QUIT;                     /* Allow user to bail out with ^C.  */
11028       rs->buf[0] = '\0';
11029       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11030         { 
11031           /* Timeout.  Continue to (try to) read responses.
11032              This is better than stopping with an error, assuming the stub
11033              is still executing the (long) monitor command.
11034              If needed, the user can interrupt gdb using C-c, obtaining
11035              an effect similar to stop on timeout.  */
11036           continue;
11037         }
11038       buf = rs->buf;
11039       if (buf[0] == '\0')
11040         error (_("Target does not support this command."));
11041       if (buf[0] == 'O' && buf[1] != 'K')
11042         {
11043           remote_console_output (buf + 1); /* 'O' message from stub.  */
11044           continue;
11045         }
11046       if (strcmp (buf, "OK") == 0)
11047         break;
11048       if (strlen (buf) == 3 && buf[0] == 'E'
11049           && isdigit (buf[1]) && isdigit (buf[2]))
11050         {
11051           error (_("Protocol error with Rcmd"));
11052         }
11053       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11054         {
11055           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11056
11057           fputc_unfiltered (c, outbuf);
11058         }
11059       break;
11060     }
11061 }
11062
11063 std::vector<mem_region>
11064 remote_target::memory_map ()
11065 {
11066   std::vector<mem_region> result;
11067   gdb::optional<gdb::char_vector> text
11068     = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
11069
11070   if (text)
11071     result = parse_memory_map (text->data ());
11072
11073   return result;
11074 }
11075
11076 static void
11077 packet_command (const char *args, int from_tty)
11078 {
11079   struct remote_state *rs = get_remote_state ();
11080
11081   if (!rs->remote_desc)
11082     error (_("command can only be used with remote target"));
11083
11084   if (!args)
11085     error (_("remote-packet command requires packet text as argument"));
11086
11087   puts_filtered ("sending: ");
11088   print_packet (args);
11089   puts_filtered ("\n");
11090   putpkt (args);
11091
11092   getpkt (&rs->buf, &rs->buf_size, 0);
11093   puts_filtered ("received: ");
11094   print_packet (rs->buf);
11095   puts_filtered ("\n");
11096 }
11097
11098 #if 0
11099 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11100
11101 static void display_thread_info (struct gdb_ext_thread_info *info);
11102
11103 static void threadset_test_cmd (char *cmd, int tty);
11104
11105 static void threadalive_test (char *cmd, int tty);
11106
11107 static void threadlist_test_cmd (char *cmd, int tty);
11108
11109 int get_and_display_threadinfo (threadref *ref);
11110
11111 static void threadinfo_test_cmd (char *cmd, int tty);
11112
11113 static int thread_display_step (threadref *ref, void *context);
11114
11115 static void threadlist_update_test_cmd (char *cmd, int tty);
11116
11117 static void init_remote_threadtests (void);
11118
11119 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
11120
11121 static void
11122 threadset_test_cmd (const char *cmd, int tty)
11123 {
11124   int sample_thread = SAMPLE_THREAD;
11125
11126   printf_filtered (_("Remote threadset test\n"));
11127   set_general_thread (sample_thread);
11128 }
11129
11130
11131 static void
11132 threadalive_test (const char *cmd, int tty)
11133 {
11134   int sample_thread = SAMPLE_THREAD;
11135   int pid = ptid_get_pid (inferior_ptid);
11136   ptid_t ptid = ptid_build (pid, sample_thread, 0);
11137
11138   if (remote_thread_alive (ptid))
11139     printf_filtered ("PASS: Thread alive test\n");
11140   else
11141     printf_filtered ("FAIL: Thread alive test\n");
11142 }
11143
11144 void output_threadid (char *title, threadref *ref);
11145
11146 void
11147 output_threadid (char *title, threadref *ref)
11148 {
11149   char hexid[20];
11150
11151   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
11152   hexid[16] = 0;
11153   printf_filtered ("%s  %s\n", title, (&hexid[0]));
11154 }
11155
11156 static void
11157 threadlist_test_cmd (const char *cmd, int tty)
11158 {
11159   int startflag = 1;
11160   threadref nextthread;
11161   int done, result_count;
11162   threadref threadlist[3];
11163
11164   printf_filtered ("Remote Threadlist test\n");
11165   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11166                               &result_count, &threadlist[0]))
11167     printf_filtered ("FAIL: threadlist test\n");
11168   else
11169     {
11170       threadref *scan = threadlist;
11171       threadref *limit = scan + result_count;
11172
11173       while (scan < limit)
11174         output_threadid (" thread ", scan++);
11175     }
11176 }
11177
11178 void
11179 display_thread_info (struct gdb_ext_thread_info *info)
11180 {
11181   output_threadid ("Threadid: ", &info->threadid);
11182   printf_filtered ("Name: %s\n ", info->shortname);
11183   printf_filtered ("State: %s\n", info->display);
11184   printf_filtered ("other: %s\n\n", info->more_display);
11185 }
11186
11187 int
11188 get_and_display_threadinfo (threadref *ref)
11189 {
11190   int result;
11191   int set;
11192   struct gdb_ext_thread_info threadinfo;
11193
11194   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11195     | TAG_MOREDISPLAY | TAG_DISPLAY;
11196   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11197     display_thread_info (&threadinfo);
11198   return result;
11199 }
11200
11201 static void
11202 threadinfo_test_cmd (const char *cmd, int tty)
11203 {
11204   int athread = SAMPLE_THREAD;
11205   threadref thread;
11206   int set;
11207
11208   int_to_threadref (&thread, athread);
11209   printf_filtered ("Remote Threadinfo test\n");
11210   if (!get_and_display_threadinfo (&thread))
11211     printf_filtered ("FAIL cannot get thread info\n");
11212 }
11213
11214 static int
11215 thread_display_step (threadref *ref, void *context)
11216 {
11217   /* output_threadid(" threadstep ",ref); *//* simple test */
11218   return get_and_display_threadinfo (ref);
11219 }
11220
11221 static void
11222 threadlist_update_test_cmd (const char *cmd, int tty)
11223 {
11224   printf_filtered ("Remote Threadlist update test\n");
11225   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11226 }
11227
11228 static void
11229 init_remote_threadtests (void)
11230 {
11231   add_com ("tlist", class_obscure, threadlist_test_cmd,
11232            _("Fetch and print the remote list of "
11233              "thread identifiers, one pkt only"));
11234   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11235            _("Fetch and display info about one thread"));
11236   add_com ("tset", class_obscure, threadset_test_cmd,
11237            _("Test setting to a different thread"));
11238   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11239            _("Iterate through updating all remote thread info"));
11240   add_com ("talive", class_obscure, threadalive_test,
11241            _(" Remote thread alive test "));
11242 }
11243
11244 #endif /* 0 */
11245
11246 /* Convert a thread ID to a string.  Returns the string in a static
11247    buffer.  */
11248
11249 const char *
11250 remote_target::pid_to_str (ptid_t ptid)
11251 {
11252   static char buf[64];
11253   struct remote_state *rs = get_remote_state ();
11254
11255   if (ptid_equal (ptid, null_ptid))
11256     return normal_pid_to_str (ptid);
11257   else if (ptid_is_pid (ptid))
11258     {
11259       /* Printing an inferior target id.  */
11260
11261       /* When multi-process extensions are off, there's no way in the
11262          remote protocol to know the remote process id, if there's any
11263          at all.  There's one exception --- when we're connected with
11264          target extended-remote, and we manually attached to a process
11265          with "attach PID".  We don't record anywhere a flag that
11266          allows us to distinguish that case from the case of
11267          connecting with extended-remote and the stub already being
11268          attached to a process, and reporting yes to qAttached, hence
11269          no smart special casing here.  */
11270       if (!remote_multi_process_p (rs))
11271         {
11272           xsnprintf (buf, sizeof buf, "Remote target");
11273           return buf;
11274         }
11275
11276       return normal_pid_to_str (ptid);
11277     }
11278   else
11279     {
11280       if (ptid_equal (magic_null_ptid, ptid))
11281         xsnprintf (buf, sizeof buf, "Thread <main>");
11282       else if (remote_multi_process_p (rs))
11283         if (ptid_get_lwp (ptid) == 0)
11284           return normal_pid_to_str (ptid);
11285         else
11286           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11287                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
11288       else
11289         xsnprintf (buf, sizeof buf, "Thread %ld",
11290                    ptid_get_lwp (ptid));
11291       return buf;
11292     }
11293 }
11294
11295 /* Get the address of the thread local variable in OBJFILE which is
11296    stored at OFFSET within the thread local storage for thread PTID.  */
11297
11298 CORE_ADDR
11299 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11300                                          CORE_ADDR offset)
11301 {
11302   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11303     {
11304       struct remote_state *rs = get_remote_state ();
11305       char *p = rs->buf;
11306       char *endp = rs->buf + get_remote_packet_size ();
11307       enum packet_result result;
11308
11309       strcpy (p, "qGetTLSAddr:");
11310       p += strlen (p);
11311       p = write_ptid (p, endp, ptid);
11312       *p++ = ',';
11313       p += hexnumstr (p, offset);
11314       *p++ = ',';
11315       p += hexnumstr (p, lm);
11316       *p++ = '\0';
11317
11318       putpkt (rs->buf);
11319       getpkt (&rs->buf, &rs->buf_size, 0);
11320       result = packet_ok (rs->buf,
11321                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
11322       if (result == PACKET_OK)
11323         {
11324           ULONGEST result;
11325
11326           unpack_varlen_hex (rs->buf, &result);
11327           return result;
11328         }
11329       else if (result == PACKET_UNKNOWN)
11330         throw_error (TLS_GENERIC_ERROR,
11331                      _("Remote target doesn't support qGetTLSAddr packet"));
11332       else
11333         throw_error (TLS_GENERIC_ERROR,
11334                      _("Remote target failed to process qGetTLSAddr request"));
11335     }
11336   else
11337     throw_error (TLS_GENERIC_ERROR,
11338                  _("TLS not supported or disabled on this target"));
11339   /* Not reached.  */
11340   return 0;
11341 }
11342
11343 /* Provide thread local base, i.e. Thread Information Block address.
11344    Returns 1 if ptid is found and thread_local_base is non zero.  */
11345
11346 bool
11347 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11348 {
11349   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11350     {
11351       struct remote_state *rs = get_remote_state ();
11352       char *p = rs->buf;
11353       char *endp = rs->buf + get_remote_packet_size ();
11354       enum packet_result result;
11355
11356       strcpy (p, "qGetTIBAddr:");
11357       p += strlen (p);
11358       p = write_ptid (p, endp, ptid);
11359       *p++ = '\0';
11360
11361       putpkt (rs->buf);
11362       getpkt (&rs->buf, &rs->buf_size, 0);
11363       result = packet_ok (rs->buf,
11364                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
11365       if (result == PACKET_OK)
11366         {
11367           ULONGEST result;
11368
11369           unpack_varlen_hex (rs->buf, &result);
11370           if (addr)
11371             *addr = (CORE_ADDR) result;
11372           return true;
11373         }
11374       else if (result == PACKET_UNKNOWN)
11375         error (_("Remote target doesn't support qGetTIBAddr packet"));
11376       else
11377         error (_("Remote target failed to process qGetTIBAddr request"));
11378     }
11379   else
11380     error (_("qGetTIBAddr not supported or disabled on this target"));
11381   /* Not reached.  */
11382   return false;
11383 }
11384
11385 /* Support for inferring a target description based on the current
11386    architecture and the size of a 'g' packet.  While the 'g' packet
11387    can have any size (since optional registers can be left off the
11388    end), some sizes are easily recognizable given knowledge of the
11389    approximate architecture.  */
11390
11391 struct remote_g_packet_guess
11392 {
11393   int bytes;
11394   const struct target_desc *tdesc;
11395 };
11396 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11397 DEF_VEC_O(remote_g_packet_guess_s);
11398
11399 struct remote_g_packet_data
11400 {
11401   VEC(remote_g_packet_guess_s) *guesses;
11402 };
11403
11404 static struct gdbarch_data *remote_g_packet_data_handle;
11405
11406 static void *
11407 remote_g_packet_data_init (struct obstack *obstack)
11408 {
11409   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11410 }
11411
11412 void
11413 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11414                                 const struct target_desc *tdesc)
11415 {
11416   struct remote_g_packet_data *data
11417     = ((struct remote_g_packet_data *)
11418        gdbarch_data (gdbarch, remote_g_packet_data_handle));
11419   struct remote_g_packet_guess new_guess, *guess;
11420   int ix;
11421
11422   gdb_assert (tdesc != NULL);
11423
11424   for (ix = 0;
11425        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11426        ix++)
11427     if (guess->bytes == bytes)
11428       internal_error (__FILE__, __LINE__,
11429                       _("Duplicate g packet description added for size %d"),
11430                       bytes);
11431
11432   new_guess.bytes = bytes;
11433   new_guess.tdesc = tdesc;
11434   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11435 }
11436
11437 /* Return 1 if remote_read_description would do anything on this target
11438    and architecture, 0 otherwise.  */
11439
11440 static int
11441 remote_read_description_p (struct target_ops *target)
11442 {
11443   struct remote_g_packet_data *data
11444     = ((struct remote_g_packet_data *)
11445        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11446
11447   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11448     return 1;
11449
11450   return 0;
11451 }
11452
11453 const struct target_desc *
11454 remote_target::read_description ()
11455 {
11456   struct remote_g_packet_data *data
11457     = ((struct remote_g_packet_data *)
11458        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11459
11460   /* Do not try this during initial connection, when we do not know
11461      whether there is a running but stopped thread.  */
11462   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11463     return beneath->read_description ();
11464
11465   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11466     {
11467       struct remote_g_packet_guess *guess;
11468       int ix;
11469       int bytes = send_g_packet ();
11470
11471       for (ix = 0;
11472            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11473            ix++)
11474         if (guess->bytes == bytes)
11475           return guess->tdesc;
11476
11477       /* We discard the g packet.  A minor optimization would be to
11478          hold on to it, and fill the register cache once we have selected
11479          an architecture, but it's too tricky to do safely.  */
11480     }
11481
11482   return beneath->read_description ();
11483 }
11484
11485 /* Remote file transfer support.  This is host-initiated I/O, not
11486    target-initiated; for target-initiated, see remote-fileio.c.  */
11487
11488 /* If *LEFT is at least the length of STRING, copy STRING to
11489    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11490    decrease *LEFT.  Otherwise raise an error.  */
11491
11492 static void
11493 remote_buffer_add_string (char **buffer, int *left, const char *string)
11494 {
11495   int len = strlen (string);
11496
11497   if (len > *left)
11498     error (_("Packet too long for target."));
11499
11500   memcpy (*buffer, string, len);
11501   *buffer += len;
11502   *left -= len;
11503
11504   /* NUL-terminate the buffer as a convenience, if there is
11505      room.  */
11506   if (*left)
11507     **buffer = '\0';
11508 }
11509
11510 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11511    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11512    decrease *LEFT.  Otherwise raise an error.  */
11513
11514 static void
11515 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11516                          int len)
11517 {
11518   if (2 * len > *left)
11519     error (_("Packet too long for target."));
11520
11521   bin2hex (bytes, *buffer, len);
11522   *buffer += 2 * len;
11523   *left -= 2 * len;
11524
11525   /* NUL-terminate the buffer as a convenience, if there is
11526      room.  */
11527   if (*left)
11528     **buffer = '\0';
11529 }
11530
11531 /* If *LEFT is large enough, convert VALUE to hex and add it to
11532    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11533    decrease *LEFT.  Otherwise raise an error.  */
11534
11535 static void
11536 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11537 {
11538   int len = hexnumlen (value);
11539
11540   if (len > *left)
11541     error (_("Packet too long for target."));
11542
11543   hexnumstr (*buffer, value);
11544   *buffer += len;
11545   *left -= len;
11546
11547   /* NUL-terminate the buffer as a convenience, if there is
11548      room.  */
11549   if (*left)
11550     **buffer = '\0';
11551 }
11552
11553 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
11554    value, *REMOTE_ERRNO to the remote error number or zero if none
11555    was included, and *ATTACHMENT to point to the start of the annex
11556    if any.  The length of the packet isn't needed here; there may
11557    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11558
11559    Return 0 if the packet could be parsed, -1 if it could not.  If
11560    -1 is returned, the other variables may not be initialized.  */
11561
11562 static int
11563 remote_hostio_parse_result (char *buffer, int *retcode,
11564                             int *remote_errno, char **attachment)
11565 {
11566   char *p, *p2;
11567
11568   *remote_errno = 0;
11569   *attachment = NULL;
11570
11571   if (buffer[0] != 'F')
11572     return -1;
11573
11574   errno = 0;
11575   *retcode = strtol (&buffer[1], &p, 16);
11576   if (errno != 0 || p == &buffer[1])
11577     return -1;
11578
11579   /* Check for ",errno".  */
11580   if (*p == ',')
11581     {
11582       errno = 0;
11583       *remote_errno = strtol (p + 1, &p2, 16);
11584       if (errno != 0 || p + 1 == p2)
11585         return -1;
11586       p = p2;
11587     }
11588
11589   /* Check for ";attachment".  If there is no attachment, the
11590      packet should end here.  */
11591   if (*p == ';')
11592     {
11593       *attachment = p + 1;
11594       return 0;
11595     }
11596   else if (*p == '\0')
11597     return 0;
11598   else
11599     return -1;
11600 }
11601
11602 /* Send a prepared I/O packet to the target and read its response.
11603    The prepared packet is in the global RS->BUF before this function
11604    is called, and the answer is there when we return.
11605
11606    COMMAND_BYTES is the length of the request to send, which may include
11607    binary data.  WHICH_PACKET is the packet configuration to check
11608    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
11609    is set to the error number and -1 is returned.  Otherwise the value
11610    returned by the function is returned.
11611
11612    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11613    attachment is expected; an error will be reported if there's a
11614    mismatch.  If one is found, *ATTACHMENT will be set to point into
11615    the packet buffer and *ATTACHMENT_LEN will be set to the
11616    attachment's length.  */
11617
11618 static int
11619 remote_hostio_send_command (int command_bytes, int which_packet,
11620                             int *remote_errno, char **attachment,
11621                             int *attachment_len)
11622 {
11623   struct remote_state *rs = get_remote_state ();
11624   int ret, bytes_read;
11625   char *attachment_tmp;
11626
11627   if (packet_support (which_packet) == PACKET_DISABLE)
11628     {
11629       *remote_errno = FILEIO_ENOSYS;
11630       return -1;
11631     }
11632
11633   putpkt_binary (rs->buf, command_bytes);
11634   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11635
11636   /* If it timed out, something is wrong.  Don't try to parse the
11637      buffer.  */
11638   if (bytes_read < 0)
11639     {
11640       *remote_errno = FILEIO_EINVAL;
11641       return -1;
11642     }
11643
11644   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11645     {
11646     case PACKET_ERROR:
11647       *remote_errno = FILEIO_EINVAL;
11648       return -1;
11649     case PACKET_UNKNOWN:
11650       *remote_errno = FILEIO_ENOSYS;
11651       return -1;
11652     case PACKET_OK:
11653       break;
11654     }
11655
11656   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11657                                   &attachment_tmp))
11658     {
11659       *remote_errno = FILEIO_EINVAL;
11660       return -1;
11661     }
11662
11663   /* Make sure we saw an attachment if and only if we expected one.  */
11664   if ((attachment_tmp == NULL && attachment != NULL)
11665       || (attachment_tmp != NULL && attachment == NULL))
11666     {
11667       *remote_errno = FILEIO_EINVAL;
11668       return -1;
11669     }
11670
11671   /* If an attachment was found, it must point into the packet buffer;
11672      work out how many bytes there were.  */
11673   if (attachment_tmp != NULL)
11674     {
11675       *attachment = attachment_tmp;
11676       *attachment_len = bytes_read - (*attachment - rs->buf);
11677     }
11678
11679   return ret;
11680 }
11681
11682 /* See declaration.h.  */
11683
11684 void
11685 readahead_cache::invalidate ()
11686 {
11687   this->fd = -1;
11688 }
11689
11690 /* See declaration.h.  */
11691
11692 void
11693 readahead_cache::invalidate_fd (int fd)
11694 {
11695   if (this->fd == fd)
11696     this->fd = -1;
11697 }
11698
11699 /* Set the filesystem remote_hostio functions that take FILENAME
11700    arguments will use.  Return 0 on success, or -1 if an error
11701    occurs (and set *REMOTE_ERRNO).  */
11702
11703 static int
11704 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11705 {
11706   struct remote_state *rs = get_remote_state ();
11707   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11708   char *p = rs->buf;
11709   int left = get_remote_packet_size () - 1;
11710   char arg[9];
11711   int ret;
11712
11713   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11714     return 0;
11715
11716   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11717     return 0;
11718
11719   remote_buffer_add_string (&p, &left, "vFile:setfs:");
11720
11721   xsnprintf (arg, sizeof (arg), "%x", required_pid);
11722   remote_buffer_add_string (&p, &left, arg);
11723
11724   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11725                                     remote_errno, NULL, NULL);
11726
11727   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11728     return 0;
11729
11730   if (ret == 0)
11731     rs->fs_pid = required_pid;
11732
11733   return ret;
11734 }
11735
11736 /* Implementation of to_fileio_open.  */
11737
11738 static int
11739 remote_hostio_open (struct target_ops *self,
11740                     struct inferior *inf, const char *filename,
11741                     int flags, int mode, int warn_if_slow,
11742                     int *remote_errno)
11743 {
11744   struct remote_state *rs = get_remote_state ();
11745   char *p = rs->buf;
11746   int left = get_remote_packet_size () - 1;
11747
11748   if (warn_if_slow)
11749     {
11750       static int warning_issued = 0;
11751
11752       printf_unfiltered (_("Reading %s from remote target...\n"),
11753                          filename);
11754
11755       if (!warning_issued)
11756         {
11757           warning (_("File transfers from remote targets can be slow."
11758                      " Use \"set sysroot\" to access files locally"
11759                      " instead."));
11760           warning_issued = 1;
11761         }
11762     }
11763
11764   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11765     return -1;
11766
11767   remote_buffer_add_string (&p, &left, "vFile:open:");
11768
11769   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11770                            strlen (filename));
11771   remote_buffer_add_string (&p, &left, ",");
11772
11773   remote_buffer_add_int (&p, &left, flags);
11774   remote_buffer_add_string (&p, &left, ",");
11775
11776   remote_buffer_add_int (&p, &left, mode);
11777
11778   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11779                                      remote_errno, NULL, NULL);
11780 }
11781
11782 int
11783 remote_target::fileio_open (struct inferior *inf, const char *filename,
11784                             int flags, int mode, int warn_if_slow,
11785                             int *remote_errno)
11786 {
11787   return remote_hostio_open (this, inf, filename, flags, mode, warn_if_slow,
11788                              remote_errno);
11789 }
11790
11791 /* Implementation of to_fileio_pwrite.  */
11792
11793 static int
11794 remote_hostio_pwrite (struct target_ops *self,
11795                       int fd, const gdb_byte *write_buf, int len,
11796                       ULONGEST offset, int *remote_errno)
11797 {
11798   struct remote_state *rs = get_remote_state ();
11799   char *p = rs->buf;
11800   int left = get_remote_packet_size ();
11801   int out_len;
11802
11803   rs->readahead_cache.invalidate_fd (fd);
11804
11805   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11806
11807   remote_buffer_add_int (&p, &left, fd);
11808   remote_buffer_add_string (&p, &left, ",");
11809
11810   remote_buffer_add_int (&p, &left, offset);
11811   remote_buffer_add_string (&p, &left, ",");
11812
11813   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11814                              get_remote_packet_size () - (p - rs->buf));
11815
11816   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11817                                      remote_errno, NULL, NULL);
11818 }
11819
11820 int
11821 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
11822                               ULONGEST offset, int *remote_errno)
11823 {
11824   return remote_hostio_pwrite (this, fd, write_buf, len, offset, remote_errno);
11825 }
11826
11827 /* Helper for the implementation of to_fileio_pread.  Read the file
11828    from the remote side with vFile:pread.  */
11829
11830 static int
11831 remote_hostio_pread_vFile (struct target_ops *self,
11832                            int fd, gdb_byte *read_buf, int len,
11833                            ULONGEST offset, int *remote_errno)
11834 {
11835   struct remote_state *rs = get_remote_state ();
11836   char *p = rs->buf;
11837   char *attachment;
11838   int left = get_remote_packet_size ();
11839   int ret, attachment_len;
11840   int read_len;
11841
11842   remote_buffer_add_string (&p, &left, "vFile:pread:");
11843
11844   remote_buffer_add_int (&p, &left, fd);
11845   remote_buffer_add_string (&p, &left, ",");
11846
11847   remote_buffer_add_int (&p, &left, len);
11848   remote_buffer_add_string (&p, &left, ",");
11849
11850   remote_buffer_add_int (&p, &left, offset);
11851
11852   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11853                                     remote_errno, &attachment,
11854                                     &attachment_len);
11855
11856   if (ret < 0)
11857     return ret;
11858
11859   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11860                                     read_buf, len);
11861   if (read_len != ret)
11862     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11863
11864   return ret;
11865 }
11866
11867 /* See declaration.h.  */
11868
11869 int
11870 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
11871                         ULONGEST offset)
11872 {
11873   if (this->fd == fd
11874       && this->offset <= offset
11875       && offset < this->offset + this->bufsize)
11876     {
11877       ULONGEST max = this->offset + this->bufsize;
11878
11879       if (offset + len > max)
11880         len = max - offset;
11881
11882       memcpy (read_buf, this->buf + offset - this->offset, len);
11883       return len;
11884     }
11885
11886   return 0;
11887 }
11888
11889 /* Implementation of to_fileio_pread.  */
11890
11891 static int
11892 remote_hostio_pread (struct target_ops *self,
11893                      int fd, gdb_byte *read_buf, int len,
11894                      ULONGEST offset, int *remote_errno)
11895 {
11896   int ret;
11897   struct remote_state *rs = get_remote_state ();
11898   readahead_cache *cache = &rs->readahead_cache;
11899
11900   ret = cache->pread (fd, read_buf, len, offset);
11901   if (ret > 0)
11902     {
11903       cache->hit_count++;
11904
11905       if (remote_debug)
11906         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11907                             pulongest (cache->hit_count));
11908       return ret;
11909     }
11910
11911   cache->miss_count++;
11912   if (remote_debug)
11913     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11914                         pulongest (cache->miss_count));
11915
11916   cache->fd = fd;
11917   cache->offset = offset;
11918   cache->bufsize = get_remote_packet_size ();
11919   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11920
11921   ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11922                                    cache->offset, remote_errno);
11923   if (ret <= 0)
11924     {
11925       cache->invalidate_fd (fd);
11926       return ret;
11927     }
11928
11929   cache->bufsize = ret;
11930   return cache->pread (fd, read_buf, len, offset);
11931 }
11932
11933 int
11934 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
11935                              ULONGEST offset, int *remote_errno)
11936 {
11937   return remote_hostio_pread (this, fd, read_buf, len, offset, remote_errno);
11938 }
11939
11940 /* Implementation of to_fileio_close.  */
11941
11942 static int
11943 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11944 {
11945   struct remote_state *rs = get_remote_state ();
11946   char *p = rs->buf;
11947   int left = get_remote_packet_size () - 1;
11948
11949   rs->readahead_cache.invalidate_fd (fd);
11950
11951   remote_buffer_add_string (&p, &left, "vFile:close:");
11952
11953   remote_buffer_add_int (&p, &left, fd);
11954
11955   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11956                                      remote_errno, NULL, NULL);
11957 }
11958
11959 int
11960 remote_target::fileio_close (int fd, int *remote_errno)
11961 {
11962   return remote_hostio_close (this, fd, remote_errno);
11963 }
11964
11965 /* Implementation of to_fileio_unlink.  */
11966
11967 static int
11968 remote_hostio_unlink (struct target_ops *self,
11969                       struct inferior *inf, const char *filename,
11970                       int *remote_errno)
11971 {
11972   struct remote_state *rs = get_remote_state ();
11973   char *p = rs->buf;
11974   int left = get_remote_packet_size () - 1;
11975
11976   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11977     return -1;
11978
11979   remote_buffer_add_string (&p, &left, "vFile:unlink:");
11980
11981   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11982                            strlen (filename));
11983
11984   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11985                                      remote_errno, NULL, NULL);
11986 }
11987
11988 int
11989 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
11990                               int *remote_errno)
11991 {
11992   return remote_hostio_unlink (this, inf, filename, remote_errno);
11993 }
11994
11995 /* Implementation of to_fileio_readlink.  */
11996
11997 gdb::optional<std::string>
11998 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
11999                                 int *remote_errno)
12000 {
12001   struct remote_state *rs = get_remote_state ();
12002   char *p = rs->buf;
12003   char *attachment;
12004   int left = get_remote_packet_size ();
12005   int len, attachment_len;
12006   int read_len;
12007
12008   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12009     return {};
12010
12011   remote_buffer_add_string (&p, &left, "vFile:readlink:");
12012
12013   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12014                            strlen (filename));
12015
12016   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12017                                     remote_errno, &attachment,
12018                                     &attachment_len);
12019
12020   if (len < 0)
12021     return {};
12022
12023   std::string ret (len, '\0');
12024
12025   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12026                                     (gdb_byte *) &ret[0], len);
12027   if (read_len != len)
12028     error (_("Readlink returned %d, but %d bytes."), len, read_len);
12029
12030   return ret;
12031 }
12032
12033 /* Implementation of to_fileio_fstat.  */
12034
12035 int
12036 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12037 {
12038   struct remote_state *rs = get_remote_state ();
12039   char *p = rs->buf;
12040   int left = get_remote_packet_size ();
12041   int attachment_len, ret;
12042   char *attachment;
12043   struct fio_stat fst;
12044   int read_len;
12045
12046   remote_buffer_add_string (&p, &left, "vFile:fstat:");
12047
12048   remote_buffer_add_int (&p, &left, fd);
12049
12050   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12051                                     remote_errno, &attachment,
12052                                     &attachment_len);
12053   if (ret < 0)
12054     {
12055       if (*remote_errno != FILEIO_ENOSYS)
12056         return ret;
12057
12058       /* Strictly we should return -1, ENOSYS here, but when
12059          "set sysroot remote:" was implemented in August 2008
12060          BFD's need for a stat function was sidestepped with
12061          this hack.  This was not remedied until March 2015
12062          so we retain the previous behavior to avoid breaking
12063          compatibility.
12064
12065          Note that the memset is a March 2015 addition; older
12066          GDBs set st_size *and nothing else* so the structure
12067          would have garbage in all other fields.  This might
12068          break something but retaining the previous behavior
12069          here would be just too wrong.  */
12070
12071       memset (st, 0, sizeof (struct stat));
12072       st->st_size = INT_MAX;
12073       return 0;
12074     }
12075
12076   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12077                                     (gdb_byte *) &fst, sizeof (fst));
12078
12079   if (read_len != ret)
12080     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12081
12082   if (read_len != sizeof (fst))
12083     error (_("vFile:fstat returned %d bytes, but expecting %d."),
12084            read_len, (int) sizeof (fst));
12085
12086   remote_fileio_to_host_stat (&fst, st);
12087
12088   return 0;
12089 }
12090
12091 /* Implementation of to_filesystem_is_local.  */
12092
12093 bool
12094 remote_target::filesystem_is_local ()
12095 {
12096   /* Valgrind GDB presents itself as a remote target but works
12097      on the local filesystem: it does not implement remote get
12098      and users are not expected to set a sysroot.  To handle
12099      this case we treat the remote filesystem as local if the
12100      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12101      does not support vFile:open.  */
12102   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12103     {
12104       enum packet_support ps = packet_support (PACKET_vFile_open);
12105
12106       if (ps == PACKET_SUPPORT_UNKNOWN)
12107         {
12108           int fd, remote_errno;
12109
12110           /* Try opening a file to probe support.  The supplied
12111              filename is irrelevant, we only care about whether
12112              the stub recognizes the packet or not.  */
12113           fd = remote_hostio_open (this, NULL, "just probing",
12114                                    FILEIO_O_RDONLY, 0700, 0,
12115                                    &remote_errno);
12116
12117           if (fd >= 0)
12118             remote_hostio_close (this, fd, &remote_errno);
12119
12120           ps = packet_support (PACKET_vFile_open);
12121         }
12122
12123       if (ps == PACKET_DISABLE)
12124         {
12125           static int warning_issued = 0;
12126
12127           if (!warning_issued)
12128             {
12129               warning (_("remote target does not support file"
12130                          " transfer, attempting to access files"
12131                          " from local filesystem."));
12132               warning_issued = 1;
12133             }
12134
12135           return true;
12136         }
12137     }
12138
12139   return false;
12140 }
12141
12142 static int
12143 remote_fileio_errno_to_host (int errnum)
12144 {
12145   switch (errnum)
12146     {
12147       case FILEIO_EPERM:
12148         return EPERM;
12149       case FILEIO_ENOENT:
12150         return ENOENT;
12151       case FILEIO_EINTR:
12152         return EINTR;
12153       case FILEIO_EIO:
12154         return EIO;
12155       case FILEIO_EBADF:
12156         return EBADF;
12157       case FILEIO_EACCES:
12158         return EACCES;
12159       case FILEIO_EFAULT:
12160         return EFAULT;
12161       case FILEIO_EBUSY:
12162         return EBUSY;
12163       case FILEIO_EEXIST:
12164         return EEXIST;
12165       case FILEIO_ENODEV:
12166         return ENODEV;
12167       case FILEIO_ENOTDIR:
12168         return ENOTDIR;
12169       case FILEIO_EISDIR:
12170         return EISDIR;
12171       case FILEIO_EINVAL:
12172         return EINVAL;
12173       case FILEIO_ENFILE:
12174         return ENFILE;
12175       case FILEIO_EMFILE:
12176         return EMFILE;
12177       case FILEIO_EFBIG:
12178         return EFBIG;
12179       case FILEIO_ENOSPC:
12180         return ENOSPC;
12181       case FILEIO_ESPIPE:
12182         return ESPIPE;
12183       case FILEIO_EROFS:
12184         return EROFS;
12185       case FILEIO_ENOSYS:
12186         return ENOSYS;
12187       case FILEIO_ENAMETOOLONG:
12188         return ENAMETOOLONG;
12189     }
12190   return -1;
12191 }
12192
12193 static char *
12194 remote_hostio_error (int errnum)
12195 {
12196   int host_error = remote_fileio_errno_to_host (errnum);
12197
12198   if (host_error == -1)
12199     error (_("Unknown remote I/O error %d"), errnum);
12200   else
12201     error (_("Remote I/O error: %s"), safe_strerror (host_error));
12202 }
12203
12204 /* A RAII wrapper around a remote file descriptor.  */
12205
12206 class scoped_remote_fd
12207 {
12208 public:
12209   explicit scoped_remote_fd (int fd)
12210     : m_fd (fd)
12211   {
12212   }
12213
12214   ~scoped_remote_fd ()
12215   {
12216     if (m_fd != -1)
12217       {
12218         try
12219           {
12220             int remote_errno;
12221             remote_hostio_close (find_target_at (process_stratum),
12222                                  m_fd, &remote_errno);
12223           }
12224         catch (...)
12225           {
12226             /* Swallow exception before it escapes the dtor.  If
12227                something goes wrong, likely the connection is gone,
12228                and there's nothing else that can be done.  */
12229           }
12230       }
12231   }
12232
12233   DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12234
12235   /* Release ownership of the file descriptor, and return it.  */
12236   int release () noexcept
12237   {
12238     int fd = m_fd;
12239     m_fd = -1;
12240     return fd;
12241   }
12242
12243   /* Return the owned file descriptor.  */
12244   int get () const noexcept
12245   {
12246     return m_fd;
12247   }
12248
12249 private:
12250   /* The owned remote I/O file descriptor.  */
12251   int m_fd;
12252 };
12253
12254 void
12255 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12256 {
12257   struct cleanup *back_to;
12258   int retcode, remote_errno, bytes, io_size;
12259   gdb_byte *buffer;
12260   int bytes_in_buffer;
12261   int saw_eof;
12262   ULONGEST offset;
12263   struct remote_state *rs = get_remote_state ();
12264
12265   if (!rs->remote_desc)
12266     error (_("command can only be used with remote target"));
12267
12268   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12269   if (file == NULL)
12270     perror_with_name (local_file);
12271
12272   scoped_remote_fd fd
12273     (remote_hostio_open (find_target_at (process_stratum), NULL,
12274                          remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12275                                        | FILEIO_O_TRUNC),
12276                          0700, 0, &remote_errno));
12277   if (fd.get () == -1)
12278     remote_hostio_error (remote_errno);
12279
12280   /* Send up to this many bytes at once.  They won't all fit in the
12281      remote packet limit, so we'll transfer slightly fewer.  */
12282   io_size = get_remote_packet_size ();
12283   buffer = (gdb_byte *) xmalloc (io_size);
12284   back_to = make_cleanup (xfree, buffer);
12285
12286   bytes_in_buffer = 0;
12287   saw_eof = 0;
12288   offset = 0;
12289   while (bytes_in_buffer || !saw_eof)
12290     {
12291       if (!saw_eof)
12292         {
12293           bytes = fread (buffer + bytes_in_buffer, 1,
12294                          io_size - bytes_in_buffer,
12295                          file.get ());
12296           if (bytes == 0)
12297             {
12298               if (ferror (file.get ()))
12299                 error (_("Error reading %s."), local_file);
12300               else
12301                 {
12302                   /* EOF.  Unless there is something still in the
12303                      buffer from the last iteration, we are done.  */
12304                   saw_eof = 1;
12305                   if (bytes_in_buffer == 0)
12306                     break;
12307                 }
12308             }
12309         }
12310       else
12311         bytes = 0;
12312
12313       bytes += bytes_in_buffer;
12314       bytes_in_buffer = 0;
12315
12316       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12317                                       fd.get (), buffer, bytes,
12318                                       offset, &remote_errno);
12319
12320       if (retcode < 0)
12321         remote_hostio_error (remote_errno);
12322       else if (retcode == 0)
12323         error (_("Remote write of %d bytes returned 0!"), bytes);
12324       else if (retcode < bytes)
12325         {
12326           /* Short write.  Save the rest of the read data for the next
12327              write.  */
12328           bytes_in_buffer = bytes - retcode;
12329           memmove (buffer, buffer + retcode, bytes_in_buffer);
12330         }
12331
12332       offset += retcode;
12333     }
12334
12335   if (remote_hostio_close (find_target_at (process_stratum),
12336                            fd.release (), &remote_errno))
12337     remote_hostio_error (remote_errno);
12338
12339   if (from_tty)
12340     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12341   do_cleanups (back_to);
12342 }
12343
12344 void
12345 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12346 {
12347   struct cleanup *back_to;
12348   int remote_errno, bytes, io_size;
12349   gdb_byte *buffer;
12350   ULONGEST offset;
12351   struct remote_state *rs = get_remote_state ();
12352
12353   if (!rs->remote_desc)
12354     error (_("command can only be used with remote target"));
12355
12356   scoped_remote_fd fd
12357     (remote_hostio_open (find_target_at (process_stratum), NULL,
12358                          remote_file, FILEIO_O_RDONLY, 0, 0,
12359                          &remote_errno));
12360   if (fd.get () == -1)
12361     remote_hostio_error (remote_errno);
12362
12363   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12364   if (file == NULL)
12365     perror_with_name (local_file);
12366
12367   /* Send up to this many bytes at once.  They won't all fit in the
12368      remote packet limit, so we'll transfer slightly fewer.  */
12369   io_size = get_remote_packet_size ();
12370   buffer = (gdb_byte *) xmalloc (io_size);
12371   back_to = make_cleanup (xfree, buffer);
12372
12373   offset = 0;
12374   while (1)
12375     {
12376       bytes = remote_hostio_pread (find_target_at (process_stratum),
12377                                    fd.get (), buffer, io_size, offset,
12378                                    &remote_errno);
12379       if (bytes == 0)
12380         /* Success, but no bytes, means end-of-file.  */
12381         break;
12382       if (bytes == -1)
12383         remote_hostio_error (remote_errno);
12384
12385       offset += bytes;
12386
12387       bytes = fwrite (buffer, 1, bytes, file.get ());
12388       if (bytes == 0)
12389         perror_with_name (local_file);
12390     }
12391
12392   if (remote_hostio_close (find_target_at (process_stratum),
12393                            fd.release (), &remote_errno))
12394     remote_hostio_error (remote_errno);
12395
12396   if (from_tty)
12397     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12398   do_cleanups (back_to);
12399 }
12400
12401 void
12402 remote_file_delete (const char *remote_file, int from_tty)
12403 {
12404   int retcode, remote_errno;
12405   struct remote_state *rs = get_remote_state ();
12406
12407   if (!rs->remote_desc)
12408     error (_("command can only be used with remote target"));
12409
12410   retcode = remote_hostio_unlink (find_target_at (process_stratum),
12411                                   NULL, remote_file, &remote_errno);
12412   if (retcode == -1)
12413     remote_hostio_error (remote_errno);
12414
12415   if (from_tty)
12416     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12417 }
12418
12419 static void
12420 remote_put_command (const char *args, int from_tty)
12421 {
12422   if (args == NULL)
12423     error_no_arg (_("file to put"));
12424
12425   gdb_argv argv (args);
12426   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12427     error (_("Invalid parameters to remote put"));
12428
12429   remote_file_put (argv[0], argv[1], from_tty);
12430 }
12431
12432 static void
12433 remote_get_command (const char *args, int from_tty)
12434 {
12435   if (args == NULL)
12436     error_no_arg (_("file to get"));
12437
12438   gdb_argv argv (args);
12439   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12440     error (_("Invalid parameters to remote get"));
12441
12442   remote_file_get (argv[0], argv[1], from_tty);
12443 }
12444
12445 static void
12446 remote_delete_command (const char *args, int from_tty)
12447 {
12448   if (args == NULL)
12449     error_no_arg (_("file to delete"));
12450
12451   gdb_argv argv (args);
12452   if (argv[0] == NULL || argv[1] != NULL)
12453     error (_("Invalid parameters to remote delete"));
12454
12455   remote_file_delete (argv[0], from_tty);
12456 }
12457
12458 static void
12459 remote_command (const char *args, int from_tty)
12460 {
12461   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12462 }
12463
12464 bool
12465 remote_target::can_execute_reverse ()
12466 {
12467   if (packet_support (PACKET_bs) == PACKET_ENABLE
12468       || packet_support (PACKET_bc) == PACKET_ENABLE)
12469     return true;
12470   else
12471     return false;
12472 }
12473
12474 bool
12475 remote_target::supports_non_stop ()
12476 {
12477   return true;
12478 }
12479
12480 bool
12481 remote_target::supports_disable_randomization ()
12482 {
12483   /* Only supported in extended mode.  */
12484   return false;
12485 }
12486
12487 bool
12488 remote_target::supports_multi_process ()
12489 {
12490   struct remote_state *rs = get_remote_state ();
12491
12492   return remote_multi_process_p (rs);
12493 }
12494
12495 static int
12496 remote_supports_cond_tracepoints ()
12497 {
12498   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12499 }
12500
12501 bool
12502 remote_target::supports_evaluation_of_breakpoint_conditions ()
12503 {
12504   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12505 }
12506
12507 static int
12508 remote_supports_fast_tracepoints ()
12509 {
12510   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12511 }
12512
12513 static int
12514 remote_supports_static_tracepoints ()
12515 {
12516   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12517 }
12518
12519 static int
12520 remote_supports_install_in_trace ()
12521 {
12522   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12523 }
12524
12525 bool
12526 remote_target::supports_enable_disable_tracepoint ()
12527 {
12528   return (packet_support (PACKET_EnableDisableTracepoints_feature)
12529           == PACKET_ENABLE);
12530 }
12531
12532 bool
12533 remote_target::supports_string_tracing ()
12534 {
12535   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12536 }
12537
12538 bool
12539 remote_target::can_run_breakpoint_commands ()
12540 {
12541   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12542 }
12543
12544 void
12545 remote_target::trace_init ()
12546 {
12547   struct remote_state *rs = get_remote_state ();
12548
12549   putpkt ("QTinit");
12550   remote_get_noisy_reply ();
12551   if (strcmp (rs->buf, "OK") != 0)
12552     error (_("Target does not support this command."));
12553 }
12554
12555 /* Recursive routine to walk through command list including loops, and
12556    download packets for each command.  */
12557
12558 static void
12559 remote_download_command_source (int num, ULONGEST addr,
12560                                 struct command_line *cmds)
12561 {
12562   struct remote_state *rs = get_remote_state ();
12563   struct command_line *cmd;
12564
12565   for (cmd = cmds; cmd; cmd = cmd->next)
12566     {
12567       QUIT;     /* Allow user to bail out with ^C.  */
12568       strcpy (rs->buf, "QTDPsrc:");
12569       encode_source_string (num, addr, "cmd", cmd->line,
12570                             rs->buf + strlen (rs->buf),
12571                             rs->buf_size - strlen (rs->buf));
12572       putpkt (rs->buf);
12573       remote_get_noisy_reply ();
12574       if (strcmp (rs->buf, "OK"))
12575         warning (_("Target does not support source download."));
12576
12577       if (cmd->control_type == while_control
12578           || cmd->control_type == while_stepping_control)
12579         {
12580           remote_download_command_source (num, addr, cmd->body_list_0.get ());
12581
12582           QUIT; /* Allow user to bail out with ^C.  */
12583           strcpy (rs->buf, "QTDPsrc:");
12584           encode_source_string (num, addr, "cmd", "end",
12585                                 rs->buf + strlen (rs->buf),
12586                                 rs->buf_size - strlen (rs->buf));
12587           putpkt (rs->buf);
12588           remote_get_noisy_reply ();
12589           if (strcmp (rs->buf, "OK"))
12590             warning (_("Target does not support source download."));
12591         }
12592     }
12593 }
12594
12595 void
12596 remote_target::download_tracepoint (struct bp_location *loc)
12597 {
12598 #define BUF_SIZE 2048
12599
12600   CORE_ADDR tpaddr;
12601   char addrbuf[40];
12602   char buf[BUF_SIZE];
12603   std::vector<std::string> tdp_actions;
12604   std::vector<std::string> stepping_actions;
12605   char *pkt;
12606   struct breakpoint *b = loc->owner;
12607   struct tracepoint *t = (struct tracepoint *) b;
12608   struct remote_state *rs = get_remote_state ();
12609
12610   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12611
12612   tpaddr = loc->address;
12613   sprintf_vma (addrbuf, tpaddr);
12614   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12615              addrbuf, /* address */
12616              (b->enable_state == bp_enabled ? 'E' : 'D'),
12617              t->step_count, t->pass_count);
12618   /* Fast tracepoints are mostly handled by the target, but we can
12619      tell the target how big of an instruction block should be moved
12620      around.  */
12621   if (b->type == bp_fast_tracepoint)
12622     {
12623       /* Only test for support at download time; we may not know
12624          target capabilities at definition time.  */
12625       if (remote_supports_fast_tracepoints ())
12626         {
12627           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12628                                                 NULL))
12629             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12630                        gdb_insn_length (loc->gdbarch, tpaddr));
12631           else
12632             /* If it passed validation at definition but fails now,
12633                something is very wrong.  */
12634             internal_error (__FILE__, __LINE__,
12635                             _("Fast tracepoint not "
12636                               "valid during download"));
12637         }
12638       else
12639         /* Fast tracepoints are functionally identical to regular
12640            tracepoints, so don't take lack of support as a reason to
12641            give up on the trace run.  */
12642         warning (_("Target does not support fast tracepoints, "
12643                    "downloading %d as regular tracepoint"), b->number);
12644     }
12645   else if (b->type == bp_static_tracepoint)
12646     {
12647       /* Only test for support at download time; we may not know
12648          target capabilities at definition time.  */
12649       if (remote_supports_static_tracepoints ())
12650         {
12651           struct static_tracepoint_marker marker;
12652
12653           if (target_static_tracepoint_marker_at (tpaddr, &marker))
12654             strcat (buf, ":S");
12655           else
12656             error (_("Static tracepoint not valid during download"));
12657         }
12658       else
12659         /* Fast tracepoints are functionally identical to regular
12660            tracepoints, so don't take lack of support as a reason
12661            to give up on the trace run.  */
12662         error (_("Target does not support static tracepoints"));
12663     }
12664   /* If the tracepoint has a conditional, make it into an agent
12665      expression and append to the definition.  */
12666   if (loc->cond)
12667     {
12668       /* Only test support at download time, we may not know target
12669          capabilities at definition time.  */
12670       if (remote_supports_cond_tracepoints ())
12671         {
12672           agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12673           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12674                      aexpr->len);
12675           pkt = buf + strlen (buf);
12676           for (int ndx = 0; ndx < aexpr->len; ++ndx)
12677             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12678           *pkt = '\0';
12679         }
12680       else
12681         warning (_("Target does not support conditional tracepoints, "
12682                    "ignoring tp %d cond"), b->number);
12683     }
12684
12685   if (b->commands || *default_collect)
12686     strcat (buf, "-");
12687   putpkt (buf);
12688   remote_get_noisy_reply ();
12689   if (strcmp (rs->buf, "OK"))
12690     error (_("Target does not support tracepoints."));
12691
12692   /* do_single_steps (t); */
12693   for (auto action_it = tdp_actions.begin ();
12694        action_it != tdp_actions.end (); action_it++)
12695     {
12696       QUIT;     /* Allow user to bail out with ^C.  */
12697
12698       bool has_more = (action_it != tdp_actions.end ()
12699                        || !stepping_actions.empty ());
12700
12701       xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12702                  b->number, addrbuf, /* address */
12703                  action_it->c_str (),
12704                  has_more ? '-' : 0);
12705       putpkt (buf);
12706       remote_get_noisy_reply ();
12707       if (strcmp (rs->buf, "OK"))
12708         error (_("Error on target while setting tracepoints."));
12709     }
12710
12711     for (auto action_it = stepping_actions.begin ();
12712          action_it != stepping_actions.end (); action_it++)
12713       {
12714         QUIT;   /* Allow user to bail out with ^C.  */
12715
12716         bool is_first = action_it == stepping_actions.begin ();
12717         bool has_more = action_it != stepping_actions.end ();
12718
12719         xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12720                    b->number, addrbuf, /* address */
12721                    is_first ? "S" : "",
12722                    action_it->c_str (),
12723                    has_more ? "-" : "");
12724         putpkt (buf);
12725         remote_get_noisy_reply ();
12726         if (strcmp (rs->buf, "OK"))
12727           error (_("Error on target while setting tracepoints."));
12728       }
12729
12730   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12731     {
12732       if (b->location != NULL)
12733         {
12734           strcpy (buf, "QTDPsrc:");
12735           encode_source_string (b->number, loc->address, "at",
12736                                 event_location_to_string (b->location.get ()),
12737                                 buf + strlen (buf), 2048 - strlen (buf));
12738           putpkt (buf);
12739           remote_get_noisy_reply ();
12740           if (strcmp (rs->buf, "OK"))
12741             warning (_("Target does not support source download."));
12742         }
12743       if (b->cond_string)
12744         {
12745           strcpy (buf, "QTDPsrc:");
12746           encode_source_string (b->number, loc->address,
12747                                 "cond", b->cond_string, buf + strlen (buf),
12748                                 2048 - strlen (buf));
12749           putpkt (buf);
12750           remote_get_noisy_reply ();
12751           if (strcmp (rs->buf, "OK"))
12752             warning (_("Target does not support source download."));
12753         }
12754       remote_download_command_source (b->number, loc->address,
12755                                       breakpoint_commands (b));
12756     }
12757 }
12758
12759 bool
12760 remote_target::can_download_tracepoint ()
12761 {
12762   struct remote_state *rs = get_remote_state ();
12763   struct trace_status *ts;
12764   int status;
12765
12766   /* Don't try to install tracepoints until we've relocated our
12767      symbols, and fetched and merged the target's tracepoint list with
12768      ours.  */
12769   if (rs->starting_up)
12770     return false;
12771
12772   ts = current_trace_status ();
12773   status = get_trace_status (ts);
12774
12775   if (status == -1 || !ts->running_known || !ts->running)
12776     return false;
12777
12778   /* If we are in a tracing experiment, but remote stub doesn't support
12779      installing tracepoint in trace, we have to return.  */
12780   if (!remote_supports_install_in_trace ())
12781     return false;
12782
12783   return true;
12784 }
12785
12786
12787 void
12788 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12789 {
12790   struct remote_state *rs = get_remote_state ();
12791   char *p;
12792
12793   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12794              tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12795              tsv.builtin);
12796   p = rs->buf + strlen (rs->buf);
12797   if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12798     error (_("Trace state variable name too long for tsv definition packet"));
12799   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12800   *p++ = '\0';
12801   putpkt (rs->buf);
12802   remote_get_noisy_reply ();
12803   if (*rs->buf == '\0')
12804     error (_("Target does not support this command."));
12805   if (strcmp (rs->buf, "OK") != 0)
12806     error (_("Error on target while downloading trace state variable."));
12807 }
12808
12809 void
12810 remote_target::enable_tracepoint (struct bp_location *location)
12811 {
12812   struct remote_state *rs = get_remote_state ();
12813   char addr_buf[40];
12814
12815   sprintf_vma (addr_buf, location->address);
12816   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12817              location->owner->number, addr_buf);
12818   putpkt (rs->buf);
12819   remote_get_noisy_reply ();
12820   if (*rs->buf == '\0')
12821     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12822   if (strcmp (rs->buf, "OK") != 0)
12823     error (_("Error on target while enabling tracepoint."));
12824 }
12825
12826 void
12827 remote_target::disable_tracepoint (struct bp_location *location)
12828 {
12829   struct remote_state *rs = get_remote_state ();
12830   char addr_buf[40];
12831
12832   sprintf_vma (addr_buf, location->address);
12833   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12834              location->owner->number, addr_buf);
12835   putpkt (rs->buf);
12836   remote_get_noisy_reply ();
12837   if (*rs->buf == '\0')
12838     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12839   if (strcmp (rs->buf, "OK") != 0)
12840     error (_("Error on target while disabling tracepoint."));
12841 }
12842
12843 void
12844 remote_target::trace_set_readonly_regions ()
12845 {
12846   asection *s;
12847   bfd *abfd = NULL;
12848   bfd_size_type size;
12849   bfd_vma vma;
12850   int anysecs = 0;
12851   int offset = 0;
12852
12853   if (!exec_bfd)
12854     return;                     /* No information to give.  */
12855
12856   struct remote_state *rs = get_remote_state ();
12857
12858   strcpy (rs->buf, "QTro");
12859   offset = strlen (rs->buf);
12860   for (s = exec_bfd->sections; s; s = s->next)
12861     {
12862       char tmp1[40], tmp2[40];
12863       int sec_length;
12864
12865       if ((s->flags & SEC_LOAD) == 0 ||
12866       /*  (s->flags & SEC_CODE) == 0 || */
12867           (s->flags & SEC_READONLY) == 0)
12868         continue;
12869
12870       anysecs = 1;
12871       vma = bfd_get_section_vma (abfd, s);
12872       size = bfd_get_section_size (s);
12873       sprintf_vma (tmp1, vma);
12874       sprintf_vma (tmp2, vma + size);
12875       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12876       if (offset + sec_length + 1 > rs->buf_size)
12877         {
12878           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12879             warning (_("\
12880 Too many sections for read-only sections definition packet."));
12881           break;
12882         }
12883       xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
12884                  tmp1, tmp2);
12885       offset += sec_length;
12886     }
12887   if (anysecs)
12888     {
12889       putpkt (rs->buf);
12890       getpkt (&rs->buf, &rs->buf_size, 0);
12891     }
12892 }
12893
12894 void
12895 remote_target::trace_start ()
12896 {
12897   struct remote_state *rs = get_remote_state ();
12898
12899   putpkt ("QTStart");
12900   remote_get_noisy_reply ();
12901   if (*rs->buf == '\0')
12902     error (_("Target does not support this command."));
12903   if (strcmp (rs->buf, "OK") != 0)
12904     error (_("Bogus reply from target: %s"), rs->buf);
12905 }
12906
12907 int
12908 remote_target::get_trace_status (struct trace_status *ts)
12909 {
12910   /* Initialize it just to avoid a GCC false warning.  */
12911   char *p = NULL;
12912   /* FIXME we need to get register block size some other way.  */
12913   extern int trace_regblock_size;
12914   enum packet_result result;
12915   struct remote_state *rs = get_remote_state ();
12916
12917   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12918     return -1;
12919
12920   trace_regblock_size
12921     = get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
12922
12923   putpkt ("qTStatus");
12924
12925   TRY
12926     {
12927       p = remote_get_noisy_reply ();
12928     }
12929   CATCH (ex, RETURN_MASK_ERROR)
12930     {
12931       if (ex.error != TARGET_CLOSE_ERROR)
12932         {
12933           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12934           return -1;
12935         }
12936       throw_exception (ex);
12937     }
12938   END_CATCH
12939
12940   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12941
12942   /* If the remote target doesn't do tracing, flag it.  */
12943   if (result == PACKET_UNKNOWN)
12944     return -1;
12945
12946   /* We're working with a live target.  */
12947   ts->filename = NULL;
12948
12949   if (*p++ != 'T')
12950     error (_("Bogus trace status reply from target: %s"), rs->buf);
12951
12952   /* Function 'parse_trace_status' sets default value of each field of
12953      'ts' at first, so we don't have to do it here.  */
12954   parse_trace_status (p, ts);
12955
12956   return ts->running;
12957 }
12958
12959 void
12960 remote_target::get_tracepoint_status (struct breakpoint *bp,
12961                                       struct uploaded_tp *utp)
12962 {
12963   struct remote_state *rs = get_remote_state ();
12964   char *reply;
12965   struct bp_location *loc;
12966   struct tracepoint *tp = (struct tracepoint *) bp;
12967   size_t size = get_remote_packet_size ();
12968
12969   if (tp)
12970     {
12971       tp->hit_count = 0;
12972       tp->traceframe_usage = 0;
12973       for (loc = tp->loc; loc; loc = loc->next)
12974         {
12975           /* If the tracepoint was never downloaded, don't go asking for
12976              any status.  */
12977           if (tp->number_on_target == 0)
12978             continue;
12979           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12980                      phex_nz (loc->address, 0));
12981           putpkt (rs->buf);
12982           reply = remote_get_noisy_reply ();
12983           if (reply && *reply)
12984             {
12985               if (*reply == 'V')
12986                 parse_tracepoint_status (reply + 1, bp, utp);
12987             }
12988         }
12989     }
12990   else if (utp)
12991     {
12992       utp->hit_count = 0;
12993       utp->traceframe_usage = 0;
12994       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12995                  phex_nz (utp->addr, 0));
12996       putpkt (rs->buf);
12997       reply = remote_get_noisy_reply ();
12998       if (reply && *reply)
12999         {
13000           if (*reply == 'V')
13001             parse_tracepoint_status (reply + 1, bp, utp);
13002         }
13003     }
13004 }
13005
13006 void
13007 remote_target::trace_stop ()
13008 {
13009   struct remote_state *rs = get_remote_state ();
13010
13011   putpkt ("QTStop");
13012   remote_get_noisy_reply ();
13013   if (*rs->buf == '\0')
13014     error (_("Target does not support this command."));
13015   if (strcmp (rs->buf, "OK") != 0)
13016     error (_("Bogus reply from target: %s"), rs->buf);
13017 }
13018
13019 int
13020 remote_target::trace_find (enum trace_find_type type, int num,
13021                            CORE_ADDR addr1, CORE_ADDR addr2,
13022                            int *tpp)
13023 {
13024   struct remote_state *rs = get_remote_state ();
13025   char *endbuf = rs->buf + get_remote_packet_size ();
13026   char *p, *reply;
13027   int target_frameno = -1, target_tracept = -1;
13028
13029   /* Lookups other than by absolute frame number depend on the current
13030      trace selected, so make sure it is correct on the remote end
13031      first.  */
13032   if (type != tfind_number)
13033     set_remote_traceframe ();
13034
13035   p = rs->buf;
13036   strcpy (p, "QTFrame:");
13037   p = strchr (p, '\0');
13038   switch (type)
13039     {
13040     case tfind_number:
13041       xsnprintf (p, endbuf - p, "%x", num);
13042       break;
13043     case tfind_pc:
13044       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13045       break;
13046     case tfind_tp:
13047       xsnprintf (p, endbuf - p, "tdp:%x", num);
13048       break;
13049     case tfind_range:
13050       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13051                  phex_nz (addr2, 0));
13052       break;
13053     case tfind_outside:
13054       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13055                  phex_nz (addr2, 0));
13056       break;
13057     default:
13058       error (_("Unknown trace find type %d"), type);
13059     }
13060
13061   putpkt (rs->buf);
13062   reply = remote_get_noisy_reply ();
13063   if (*reply == '\0')
13064     error (_("Target does not support this command."));
13065
13066   while (reply && *reply)
13067     switch (*reply)
13068       {
13069       case 'F':
13070         p = ++reply;
13071         target_frameno = (int) strtol (p, &reply, 16);
13072         if (reply == p)
13073           error (_("Unable to parse trace frame number"));
13074         /* Don't update our remote traceframe number cache on failure
13075            to select a remote traceframe.  */
13076         if (target_frameno == -1)
13077           return -1;
13078         break;
13079       case 'T':
13080         p = ++reply;
13081         target_tracept = (int) strtol (p, &reply, 16);
13082         if (reply == p)
13083           error (_("Unable to parse tracepoint number"));
13084         break;
13085       case 'O':         /* "OK"? */
13086         if (reply[1] == 'K' && reply[2] == '\0')
13087           reply += 2;
13088         else
13089           error (_("Bogus reply from target: %s"), reply);
13090         break;
13091       default:
13092         error (_("Bogus reply from target: %s"), reply);
13093       }
13094   if (tpp)
13095     *tpp = target_tracept;
13096
13097   rs->remote_traceframe_number = target_frameno;
13098   return target_frameno;
13099 }
13100
13101 bool
13102 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13103 {
13104   struct remote_state *rs = get_remote_state ();
13105   char *reply;
13106   ULONGEST uval;
13107
13108   set_remote_traceframe ();
13109
13110   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13111   putpkt (rs->buf);
13112   reply = remote_get_noisy_reply ();
13113   if (reply && *reply)
13114     {
13115       if (*reply == 'V')
13116         {
13117           unpack_varlen_hex (reply + 1, &uval);
13118           *val = (LONGEST) uval;
13119           return true;
13120         }
13121     }
13122   return false;
13123 }
13124
13125 int
13126 remote_target::save_trace_data (const char *filename)
13127 {
13128   struct remote_state *rs = get_remote_state ();
13129   char *p, *reply;
13130
13131   p = rs->buf;
13132   strcpy (p, "QTSave:");
13133   p += strlen (p);
13134   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13135     error (_("Remote file name too long for trace save packet"));
13136   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13137   *p++ = '\0';
13138   putpkt (rs->buf);
13139   reply = remote_get_noisy_reply ();
13140   if (*reply == '\0')
13141     error (_("Target does not support this command."));
13142   if (strcmp (reply, "OK") != 0)
13143     error (_("Bogus reply from target: %s"), reply);
13144   return 0;
13145 }
13146
13147 /* This is basically a memory transfer, but needs to be its own packet
13148    because we don't know how the target actually organizes its trace
13149    memory, plus we want to be able to ask for as much as possible, but
13150    not be unhappy if we don't get as much as we ask for.  */
13151
13152 LONGEST
13153 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13154 {
13155   struct remote_state *rs = get_remote_state ();
13156   char *reply;
13157   char *p;
13158   int rslt;
13159
13160   p = rs->buf;
13161   strcpy (p, "qTBuffer:");
13162   p += strlen (p);
13163   p += hexnumstr (p, offset);
13164   *p++ = ',';
13165   p += hexnumstr (p, len);
13166   *p++ = '\0';
13167
13168   putpkt (rs->buf);
13169   reply = remote_get_noisy_reply ();
13170   if (reply && *reply)
13171     {
13172       /* 'l' by itself means we're at the end of the buffer and
13173          there is nothing more to get.  */
13174       if (*reply == 'l')
13175         return 0;
13176
13177       /* Convert the reply into binary.  Limit the number of bytes to
13178          convert according to our passed-in buffer size, rather than
13179          what was returned in the packet; if the target is
13180          unexpectedly generous and gives us a bigger reply than we
13181          asked for, we don't want to crash.  */
13182       rslt = hex2bin (reply, buf, len);
13183       return rslt;
13184     }
13185
13186   /* Something went wrong, flag as an error.  */
13187   return -1;
13188 }
13189
13190 void
13191 remote_target::set_disconnected_tracing (int val)
13192 {
13193   struct remote_state *rs = get_remote_state ();
13194
13195   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13196     {
13197       char *reply;
13198
13199       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13200       putpkt (rs->buf);
13201       reply = remote_get_noisy_reply ();
13202       if (*reply == '\0')
13203         error (_("Target does not support this command."));
13204       if (strcmp (reply, "OK") != 0)
13205         error (_("Bogus reply from target: %s"), reply);
13206     }
13207   else if (val)
13208     warning (_("Target does not support disconnected tracing."));
13209 }
13210
13211 int
13212 remote_target::core_of_thread (ptid_t ptid)
13213 {
13214   struct thread_info *info = find_thread_ptid (ptid);
13215
13216   if (info != NULL && info->priv != NULL)
13217     return get_remote_thread_info (info)->core;
13218
13219   return -1;
13220 }
13221
13222 void
13223 remote_target::set_circular_trace_buffer (int val)
13224 {
13225   struct remote_state *rs = get_remote_state ();
13226   char *reply;
13227
13228   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13229   putpkt (rs->buf);
13230   reply = remote_get_noisy_reply ();
13231   if (*reply == '\0')
13232     error (_("Target does not support this command."));
13233   if (strcmp (reply, "OK") != 0)
13234     error (_("Bogus reply from target: %s"), reply);
13235 }
13236
13237 traceframe_info_up
13238 remote_target::traceframe_info ()
13239 {
13240   gdb::optional<gdb::char_vector> text
13241     = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
13242                             NULL);
13243   if (text)
13244     return parse_traceframe_info (text->data ());
13245
13246   return NULL;
13247 }
13248
13249 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
13250    instruction on which a fast tracepoint may be placed.  Returns -1
13251    if the packet is not supported, and 0 if the minimum instruction
13252    length is unknown.  */
13253
13254 int
13255 remote_target::get_min_fast_tracepoint_insn_len ()
13256 {
13257   struct remote_state *rs = get_remote_state ();
13258   char *reply;
13259
13260   /* If we're not debugging a process yet, the IPA can't be
13261      loaded.  */
13262   if (!target_has_execution)
13263     return 0;
13264
13265   /* Make sure the remote is pointing at the right process.  */
13266   set_general_process ();
13267
13268   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13269   putpkt (rs->buf);
13270   reply = remote_get_noisy_reply ();
13271   if (*reply == '\0')
13272     return -1;
13273   else
13274     {
13275       ULONGEST min_insn_len;
13276
13277       unpack_varlen_hex (reply, &min_insn_len);
13278
13279       return (int) min_insn_len;
13280     }
13281 }
13282
13283 void
13284 remote_target::set_trace_buffer_size (LONGEST val)
13285 {
13286   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13287     {
13288       struct remote_state *rs = get_remote_state ();
13289       char *buf = rs->buf;
13290       char *endbuf = rs->buf + get_remote_packet_size ();
13291       enum packet_result result;
13292
13293       gdb_assert (val >= 0 || val == -1);
13294       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13295       /* Send -1 as literal "-1" to avoid host size dependency.  */
13296       if (val < 0)
13297         {
13298           *buf++ = '-';
13299           buf += hexnumstr (buf, (ULONGEST) -val);
13300         }
13301       else
13302         buf += hexnumstr (buf, (ULONGEST) val);
13303
13304       putpkt (rs->buf);
13305       remote_get_noisy_reply ();
13306       result = packet_ok (rs->buf,
13307                   &remote_protocol_packets[PACKET_QTBuffer_size]);
13308
13309       if (result != PACKET_OK)
13310         warning (_("Bogus reply from target: %s"), rs->buf);
13311     }
13312 }
13313
13314 bool
13315 remote_target::set_trace_notes (const char *user, const char *notes,
13316                                 const char *stop_notes)
13317 {
13318   struct remote_state *rs = get_remote_state ();
13319   char *reply;
13320   char *buf = rs->buf;
13321   char *endbuf = rs->buf + get_remote_packet_size ();
13322   int nbytes;
13323
13324   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13325   if (user)
13326     {
13327       buf += xsnprintf (buf, endbuf - buf, "user:");
13328       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13329       buf += 2 * nbytes;
13330       *buf++ = ';';
13331     }
13332   if (notes)
13333     {
13334       buf += xsnprintf (buf, endbuf - buf, "notes:");
13335       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13336       buf += 2 * nbytes;
13337       *buf++ = ';';
13338     }
13339   if (stop_notes)
13340     {
13341       buf += xsnprintf (buf, endbuf - buf, "tstop:");
13342       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13343       buf += 2 * nbytes;
13344       *buf++ = ';';
13345     }
13346   /* Ensure the buffer is terminated.  */
13347   *buf = '\0';
13348
13349   putpkt (rs->buf);
13350   reply = remote_get_noisy_reply ();
13351   if (*reply == '\0')
13352     return false;
13353
13354   if (strcmp (reply, "OK") != 0)
13355     error (_("Bogus reply from target: %s"), reply);
13356
13357   return true;
13358 }
13359
13360 bool
13361 remote_target::use_agent (bool use)
13362 {
13363   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13364     {
13365       struct remote_state *rs = get_remote_state ();
13366
13367       /* If the stub supports QAgent.  */
13368       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13369       putpkt (rs->buf);
13370       getpkt (&rs->buf, &rs->buf_size, 0);
13371
13372       if (strcmp (rs->buf, "OK") == 0)
13373         {
13374           ::use_agent = use;
13375           return true;
13376         }
13377     }
13378
13379   return false;
13380 }
13381
13382 bool
13383 remote_target::can_use_agent ()
13384 {
13385   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13386 }
13387
13388 struct btrace_target_info
13389 {
13390   /* The ptid of the traced thread.  */
13391   ptid_t ptid;
13392
13393   /* The obtained branch trace configuration.  */
13394   struct btrace_config conf;
13395 };
13396
13397 /* Reset our idea of our target's btrace configuration.  */
13398
13399 static void
13400 remote_btrace_reset (void)
13401 {
13402   struct remote_state *rs = get_remote_state ();
13403
13404   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13405 }
13406
13407 /* Synchronize the configuration with the target.  */
13408
13409 static void
13410 btrace_sync_conf (const struct btrace_config *conf)
13411 {
13412   struct packet_config *packet;
13413   struct remote_state *rs;
13414   char *buf, *pos, *endbuf;
13415
13416   rs = get_remote_state ();
13417   buf = rs->buf;
13418   endbuf = buf + get_remote_packet_size ();
13419
13420   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13421   if (packet_config_support (packet) == PACKET_ENABLE
13422       && conf->bts.size != rs->btrace_config.bts.size)
13423     {
13424       pos = buf;
13425       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13426                         conf->bts.size);
13427
13428       putpkt (buf);
13429       getpkt (&buf, &rs->buf_size, 0);
13430
13431       if (packet_ok (buf, packet) == PACKET_ERROR)
13432         {
13433           if (buf[0] == 'E' && buf[1] == '.')
13434             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13435           else
13436             error (_("Failed to configure the BTS buffer size."));
13437         }
13438
13439       rs->btrace_config.bts.size = conf->bts.size;
13440     }
13441
13442   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13443   if (packet_config_support (packet) == PACKET_ENABLE
13444       && conf->pt.size != rs->btrace_config.pt.size)
13445     {
13446       pos = buf;
13447       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13448                         conf->pt.size);
13449
13450       putpkt (buf);
13451       getpkt (&buf, &rs->buf_size, 0);
13452
13453       if (packet_ok (buf, packet) == PACKET_ERROR)
13454         {
13455           if (buf[0] == 'E' && buf[1] == '.')
13456             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13457           else
13458             error (_("Failed to configure the trace buffer size."));
13459         }
13460
13461       rs->btrace_config.pt.size = conf->pt.size;
13462     }
13463 }
13464
13465 /* Read the current thread's btrace configuration from the target and
13466    store it into CONF.  */
13467
13468 static void
13469 btrace_read_config (struct btrace_config *conf)
13470 {
13471   gdb::optional<gdb::char_vector> xml
13472     = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
13473   if (xml)
13474     parse_xml_btrace_conf (conf, xml->data ());
13475 }
13476
13477 /* Maybe reopen target btrace.  */
13478
13479 static void
13480 remote_btrace_maybe_reopen (void)
13481 {
13482   struct remote_state *rs = get_remote_state ();
13483   struct thread_info *tp;
13484   int btrace_target_pushed = 0;
13485   int warned = 0;
13486
13487   scoped_restore_current_thread restore_thread;
13488
13489   ALL_NON_EXITED_THREADS (tp)
13490     {
13491       set_general_thread (tp->ptid);
13492
13493       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13494       btrace_read_config (&rs->btrace_config);
13495
13496       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13497         continue;
13498
13499 #if !defined (HAVE_LIBIPT)
13500       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13501         {
13502           if (!warned)
13503             {
13504               warned = 1;
13505               warning (_("Target is recording using Intel Processor Trace "
13506                          "but support was disabled at compile time."));
13507             }
13508
13509           continue;
13510         }
13511 #endif /* !defined (HAVE_LIBIPT) */
13512
13513       /* Push target, once, but before anything else happens.  This way our
13514          changes to the threads will be cleaned up by unpushing the target
13515          in case btrace_read_config () throws.  */
13516       if (!btrace_target_pushed)
13517         {
13518           btrace_target_pushed = 1;
13519           record_btrace_push_target ();
13520           printf_filtered (_("Target is recording using %s.\n"),
13521                            btrace_format_string (rs->btrace_config.format));
13522         }
13523
13524       tp->btrace.target = XCNEW (struct btrace_target_info);
13525       tp->btrace.target->ptid = tp->ptid;
13526       tp->btrace.target->conf = rs->btrace_config;
13527     }
13528 }
13529
13530 /* Enable branch tracing.  */
13531
13532 struct btrace_target_info *
13533 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13534 {
13535   struct btrace_target_info *tinfo = NULL;
13536   struct packet_config *packet = NULL;
13537   struct remote_state *rs = get_remote_state ();
13538   char *buf = rs->buf;
13539   char *endbuf = rs->buf + get_remote_packet_size ();
13540
13541   switch (conf->format)
13542     {
13543       case BTRACE_FORMAT_BTS:
13544         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13545         break;
13546
13547       case BTRACE_FORMAT_PT:
13548         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13549         break;
13550     }
13551
13552   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13553     error (_("Target does not support branch tracing."));
13554
13555   btrace_sync_conf (conf);
13556
13557   set_general_thread (ptid);
13558
13559   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13560   putpkt (rs->buf);
13561   getpkt (&rs->buf, &rs->buf_size, 0);
13562
13563   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13564     {
13565       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13566         error (_("Could not enable branch tracing for %s: %s"),
13567                target_pid_to_str (ptid), rs->buf + 2);
13568       else
13569         error (_("Could not enable branch tracing for %s."),
13570                target_pid_to_str (ptid));
13571     }
13572
13573   tinfo = XCNEW (struct btrace_target_info);
13574   tinfo->ptid = ptid;
13575
13576   /* If we fail to read the configuration, we lose some information, but the
13577      tracing itself is not impacted.  */
13578   TRY
13579     {
13580       btrace_read_config (&tinfo->conf);
13581     }
13582   CATCH (err, RETURN_MASK_ERROR)
13583     {
13584       if (err.message != NULL)
13585         warning ("%s", err.message);
13586     }
13587   END_CATCH
13588
13589   return tinfo;
13590 }
13591
13592 /* Disable branch tracing.  */
13593
13594 void
13595 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13596 {
13597   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13598   struct remote_state *rs = get_remote_state ();
13599   char *buf = rs->buf;
13600   char *endbuf = rs->buf + get_remote_packet_size ();
13601
13602   if (packet_config_support (packet) != PACKET_ENABLE)
13603     error (_("Target does not support branch tracing."));
13604
13605   set_general_thread (tinfo->ptid);
13606
13607   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13608   putpkt (rs->buf);
13609   getpkt (&rs->buf, &rs->buf_size, 0);
13610
13611   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13612     {
13613       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13614         error (_("Could not disable branch tracing for %s: %s"),
13615                target_pid_to_str (tinfo->ptid), rs->buf + 2);
13616       else
13617         error (_("Could not disable branch tracing for %s."),
13618                target_pid_to_str (tinfo->ptid));
13619     }
13620
13621   xfree (tinfo);
13622 }
13623
13624 /* Teardown branch tracing.  */
13625
13626 void
13627 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13628 {
13629   /* We must not talk to the target during teardown.  */
13630   xfree (tinfo);
13631 }
13632
13633 /* Read the branch trace.  */
13634
13635 enum btrace_error
13636 remote_target::read_btrace (struct btrace_data *btrace,
13637                             struct btrace_target_info *tinfo,
13638                             enum btrace_read_type type)
13639 {
13640   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13641   const char *annex;
13642
13643   if (packet_config_support (packet) != PACKET_ENABLE)
13644     error (_("Target does not support branch tracing."));
13645
13646 #if !defined(HAVE_LIBEXPAT)
13647   error (_("Cannot process branch tracing result. XML parsing not supported."));
13648 #endif
13649
13650   switch (type)
13651     {
13652     case BTRACE_READ_ALL:
13653       annex = "all";
13654       break;
13655     case BTRACE_READ_NEW:
13656       annex = "new";
13657       break;
13658     case BTRACE_READ_DELTA:
13659       annex = "delta";
13660       break;
13661     default:
13662       internal_error (__FILE__, __LINE__,
13663                       _("Bad branch tracing read type: %u."),
13664                       (unsigned int) type);
13665     }
13666
13667   gdb::optional<gdb::char_vector> xml
13668     = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
13669   if (!xml)
13670     return BTRACE_ERR_UNKNOWN;
13671
13672   parse_xml_btrace (btrace, xml->data ());
13673
13674   return BTRACE_ERR_NONE;
13675 }
13676
13677 const struct btrace_config *
13678 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13679 {
13680   return &tinfo->conf;
13681 }
13682
13683 bool
13684 remote_target::augmented_libraries_svr4_read ()
13685 {
13686   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13687           == PACKET_ENABLE);
13688 }
13689
13690 /* Implementation of to_load.  */
13691
13692 void
13693 remote_target::load (const char *name, int from_tty)
13694 {
13695   generic_load (name, from_tty);
13696 }
13697
13698 /* Accepts an integer PID; returns a string representing a file that
13699    can be opened on the remote side to get the symbols for the child
13700    process.  Returns NULL if the operation is not supported.  */
13701
13702 char *
13703 remote_target::pid_to_exec_file (int pid)
13704 {
13705   static gdb::optional<gdb::char_vector> filename;
13706   struct inferior *inf;
13707   char *annex = NULL;
13708
13709   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13710     return NULL;
13711
13712   inf = find_inferior_pid (pid);
13713   if (inf == NULL)
13714     internal_error (__FILE__, __LINE__,
13715                     _("not currently attached to process %d"), pid);
13716
13717   if (!inf->fake_pid_p)
13718     {
13719       const int annex_size = 9;
13720
13721       annex = (char *) alloca (annex_size);
13722       xsnprintf (annex, annex_size, "%x", pid);
13723     }
13724
13725   filename = target_read_stralloc (target_stack,
13726                                    TARGET_OBJECT_EXEC_FILE, annex);
13727
13728   return filename ? filename->data () : nullptr;
13729 }
13730
13731 /* Implement the to_can_do_single_step target_ops method.  */
13732
13733 int
13734 remote_target::can_do_single_step ()
13735 {
13736   /* We can only tell whether target supports single step or not by
13737      supported s and S vCont actions if the stub supports vContSupported
13738      feature.  If the stub doesn't support vContSupported feature,
13739      we have conservatively to think target doesn't supports single
13740      step.  */
13741   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13742     {
13743       struct remote_state *rs = get_remote_state ();
13744
13745       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13746         remote_vcont_probe (rs);
13747
13748       return rs->supports_vCont.s && rs->supports_vCont.S;
13749     }
13750   else
13751     return 0;
13752 }
13753
13754 /* Implementation of the to_execution_direction method for the remote
13755    target.  */
13756
13757 enum exec_direction_kind
13758 remote_target::execution_direction ()
13759 {
13760   struct remote_state *rs = get_remote_state ();
13761
13762   return rs->last_resume_exec_dir;
13763 }
13764
13765 /* Return pointer to the thread_info struct which corresponds to
13766    THREAD_HANDLE (having length HANDLE_LEN).  */
13767
13768 thread_info *
13769 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13770                                              int handle_len,
13771                                              inferior *inf)
13772 {
13773   struct thread_info *tp;
13774
13775   ALL_NON_EXITED_THREADS (tp)
13776     {
13777       remote_thread_info *priv = get_remote_thread_info (tp);
13778
13779       if (tp->inf == inf && priv != NULL)
13780         {
13781           if (handle_len != priv->thread_handle.size ())
13782             error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13783                    handle_len, priv->thread_handle.size ());
13784           if (memcmp (thread_handle, priv->thread_handle.data (),
13785                       handle_len) == 0)
13786             return tp;
13787         }
13788     }
13789
13790   return NULL;
13791 }
13792
13793 bool
13794 remote_target::can_async_p ()
13795 {
13796   struct remote_state *rs = get_remote_state ();
13797
13798   /* We don't go async if the user has explicitly prevented it with the
13799      "maint set target-async" command.  */
13800   if (!target_async_permitted)
13801     return false;
13802
13803   /* We're async whenever the serial device is.  */
13804   return serial_can_async_p (rs->remote_desc);
13805 }
13806
13807 bool
13808 remote_target::is_async_p ()
13809 {
13810   struct remote_state *rs = get_remote_state ();
13811
13812   if (!target_async_permitted)
13813     /* We only enable async when the user specifically asks for it.  */
13814     return false;
13815
13816   /* We're async whenever the serial device is.  */
13817   return serial_is_async_p (rs->remote_desc);
13818 }
13819
13820 /* Pass the SERIAL event on and up to the client.  One day this code
13821    will be able to delay notifying the client of an event until the
13822    point where an entire packet has been received.  */
13823
13824 static serial_event_ftype remote_async_serial_handler;
13825
13826 static void
13827 remote_async_serial_handler (struct serial *scb, void *context)
13828 {
13829   /* Don't propogate error information up to the client.  Instead let
13830      the client find out about the error by querying the target.  */
13831   inferior_event_handler (INF_REG_EVENT, NULL);
13832 }
13833
13834 static void
13835 remote_async_inferior_event_handler (gdb_client_data data)
13836 {
13837   inferior_event_handler (INF_REG_EVENT, NULL);
13838 }
13839
13840 void
13841 remote_target::async (int enable)
13842 {
13843   struct remote_state *rs = get_remote_state ();
13844
13845   if (enable)
13846     {
13847       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13848
13849       /* If there are pending events in the stop reply queue tell the
13850          event loop to process them.  */
13851       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13852         mark_async_event_handler (remote_async_inferior_event_token);
13853       /* For simplicity, below we clear the pending events token
13854          without remembering whether it is marked, so here we always
13855          mark it.  If there's actually no pending notification to
13856          process, this ends up being a no-op (other than a spurious
13857          event-loop wakeup).  */
13858       if (target_is_non_stop_p ())
13859         mark_async_event_handler (rs->notif_state->get_pending_events_token);
13860     }
13861   else
13862     {
13863       serial_async (rs->remote_desc, NULL, NULL);
13864       /* If the core is disabling async, it doesn't want to be
13865          disturbed with target events.  Clear all async event sources
13866          too.  */
13867       clear_async_event_handler (remote_async_inferior_event_token);
13868       if (target_is_non_stop_p ())
13869         clear_async_event_handler (rs->notif_state->get_pending_events_token);
13870     }
13871 }
13872
13873 /* Implementation of the to_thread_events method.  */
13874
13875 void
13876 remote_target::thread_events (int enable)
13877 {
13878   struct remote_state *rs = get_remote_state ();
13879   size_t size = get_remote_packet_size ();
13880
13881   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13882     return;
13883
13884   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13885   putpkt (rs->buf);
13886   getpkt (&rs->buf, &rs->buf_size, 0);
13887
13888   switch (packet_ok (rs->buf,
13889                      &remote_protocol_packets[PACKET_QThreadEvents]))
13890     {
13891     case PACKET_OK:
13892       if (strcmp (rs->buf, "OK") != 0)
13893         error (_("Remote refused setting thread events: %s"), rs->buf);
13894       break;
13895     case PACKET_ERROR:
13896       warning (_("Remote failure reply: %s"), rs->buf);
13897       break;
13898     case PACKET_UNKNOWN:
13899       break;
13900     }
13901 }
13902
13903 static void
13904 set_remote_cmd (const char *args, int from_tty)
13905 {
13906   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13907 }
13908
13909 static void
13910 show_remote_cmd (const char *args, int from_tty)
13911 {
13912   /* We can't just use cmd_show_list here, because we want to skip
13913      the redundant "show remote Z-packet" and the legacy aliases.  */
13914   struct cmd_list_element *list = remote_show_cmdlist;
13915   struct ui_out *uiout = current_uiout;
13916
13917   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13918   for (; list != NULL; list = list->next)
13919     if (strcmp (list->name, "Z-packet") == 0)
13920       continue;
13921     else if (list->type == not_set_cmd)
13922       /* Alias commands are exactly like the original, except they
13923          don't have the normal type.  */
13924       continue;
13925     else
13926       {
13927         ui_out_emit_tuple option_emitter (uiout, "option");
13928
13929         uiout->field_string ("name", list->name);
13930         uiout->text (":  ");
13931         if (list->type == show_cmd)
13932           do_show_command (NULL, from_tty, list);
13933         else
13934           cmd_func (list, NULL, from_tty);
13935       }
13936 }
13937
13938
13939 /* Function to be called whenever a new objfile (shlib) is detected.  */
13940 static void
13941 remote_new_objfile (struct objfile *objfile)
13942 {
13943   struct remote_state *rs = get_remote_state ();
13944
13945   if (rs->remote_desc != 0)             /* Have a remote connection.  */
13946     remote_check_symbols ();
13947 }
13948
13949 /* Pull all the tracepoints defined on the target and create local
13950    data structures representing them.  We don't want to create real
13951    tracepoints yet, we don't want to mess up the user's existing
13952    collection.  */
13953   
13954 int
13955 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
13956 {
13957   struct remote_state *rs = get_remote_state ();
13958   char *p;
13959
13960   /* Ask for a first packet of tracepoint definition.  */
13961   putpkt ("qTfP");
13962   getpkt (&rs->buf, &rs->buf_size, 0);
13963   p = rs->buf;
13964   while (*p && *p != 'l')
13965     {
13966       parse_tracepoint_definition (p, utpp);
13967       /* Ask for another packet of tracepoint definition.  */
13968       putpkt ("qTsP");
13969       getpkt (&rs->buf, &rs->buf_size, 0);
13970       p = rs->buf;
13971     }
13972   return 0;
13973 }
13974
13975 int
13976 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
13977 {
13978   struct remote_state *rs = get_remote_state ();
13979   char *p;
13980
13981   /* Ask for a first packet of variable definition.  */
13982   putpkt ("qTfV");
13983   getpkt (&rs->buf, &rs->buf_size, 0);
13984   p = rs->buf;
13985   while (*p && *p != 'l')
13986     {
13987       parse_tsv_definition (p, utsvp);
13988       /* Ask for another packet of variable definition.  */
13989       putpkt ("qTsV");
13990       getpkt (&rs->buf, &rs->buf_size, 0);
13991       p = rs->buf;
13992     }
13993   return 0;
13994 }
13995
13996 /* The "set/show range-stepping" show hook.  */
13997
13998 static void
13999 show_range_stepping (struct ui_file *file, int from_tty,
14000                      struct cmd_list_element *c,
14001                      const char *value)
14002 {
14003   fprintf_filtered (file,
14004                     _("Debugger's willingness to use range stepping "
14005                       "is %s.\n"), value);
14006 }
14007
14008 /* The "set/show range-stepping" set hook.  */
14009
14010 static void
14011 set_range_stepping (const char *ignore_args, int from_tty,
14012                     struct cmd_list_element *c)
14013 {
14014   struct remote_state *rs = get_remote_state ();
14015
14016   /* Whene enabling, check whether range stepping is actually
14017      supported by the target, and warn if not.  */
14018   if (use_range_stepping)
14019     {
14020       if (rs->remote_desc != NULL)
14021         {
14022           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14023             remote_vcont_probe (rs);
14024
14025           if (packet_support (PACKET_vCont) == PACKET_ENABLE
14026               && rs->supports_vCont.r)
14027             return;
14028         }
14029
14030       warning (_("Range stepping is not supported by the current target"));
14031     }
14032 }
14033
14034 void
14035 _initialize_remote (void)
14036 {
14037   struct cmd_list_element *cmd;
14038   const char *cmd_name;
14039
14040   /* architecture specific data */
14041   remote_gdbarch_data_handle =
14042     gdbarch_data_register_post_init (init_remote_state);
14043   remote_g_packet_data_handle =
14044     gdbarch_data_register_pre_init (remote_g_packet_data_init);
14045
14046   remote_pspace_data
14047     = register_program_space_data_with_cleanup (NULL,
14048                                                 remote_pspace_data_cleanup);
14049
14050   /* Initialize the per-target state.  At the moment there is only one
14051      of these, not one per target.  Only one target is active at a
14052      time.  */
14053   remote_state = new struct remote_state ();
14054
14055   add_target (remote_target_info, remote_target::open);
14056   add_target (extended_remote_target_info, extended_remote_target::open);
14057
14058   /* Hook into new objfile notification.  */
14059   gdb::observers::new_objfile.attach (remote_new_objfile);
14060   /* We're no longer interested in notification events of an inferior
14061      when it exits.  */
14062   gdb::observers::inferior_exit.attach (discard_pending_stop_replies);
14063
14064 #if 0
14065   init_remote_threadtests ();
14066 #endif
14067
14068   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14069   /* set/show remote ...  */
14070
14071   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14072 Remote protocol specific variables\n\
14073 Configure various remote-protocol specific variables such as\n\
14074 the packets being used"),
14075                   &remote_set_cmdlist, "set remote ",
14076                   0 /* allow-unknown */, &setlist);
14077   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14078 Remote protocol specific variables\n\
14079 Configure various remote-protocol specific variables such as\n\
14080 the packets being used"),
14081                   &remote_show_cmdlist, "show remote ",
14082                   0 /* allow-unknown */, &showlist);
14083
14084   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14085 Compare section data on target to the exec file.\n\
14086 Argument is a single section name (default: all loaded sections).\n\
14087 To compare only read-only loaded sections, specify the -r option."),
14088            &cmdlist);
14089
14090   add_cmd ("packet", class_maintenance, packet_command, _("\
14091 Send an arbitrary packet to a remote target.\n\
14092    maintenance packet TEXT\n\
14093 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14094 this command sends the string TEXT to the inferior, and displays the\n\
14095 response packet.  GDB supplies the initial `$' character, and the\n\
14096 terminating `#' character and checksum."),
14097            &maintenancelist);
14098
14099   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14100 Set whether to send break if interrupted."), _("\
14101 Show whether to send break if interrupted."), _("\
14102 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14103                            set_remotebreak, show_remotebreak,
14104                            &setlist, &showlist);
14105   cmd_name = "remotebreak";
14106   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14107   deprecate_cmd (cmd, "set remote interrupt-sequence");
14108   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14109   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14110   deprecate_cmd (cmd, "show remote interrupt-sequence");
14111
14112   add_setshow_enum_cmd ("interrupt-sequence", class_support,
14113                         interrupt_sequence_modes, &interrupt_sequence_mode,
14114                         _("\
14115 Set interrupt sequence to remote target."), _("\
14116 Show interrupt sequence to remote target."), _("\
14117 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14118                         NULL, show_interrupt_sequence,
14119                         &remote_set_cmdlist,
14120                         &remote_show_cmdlist);
14121
14122   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14123                            &interrupt_on_connect, _("\
14124 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
14125 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
14126 If set, interrupt sequence is sent to remote target."),
14127                            NULL, NULL,
14128                            &remote_set_cmdlist, &remote_show_cmdlist);
14129
14130   /* Install commands for configuring memory read/write packets.  */
14131
14132   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14133 Set the maximum number of bytes per memory write packet (deprecated)."),
14134            &setlist);
14135   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14136 Show the maximum number of bytes per memory write packet (deprecated)."),
14137            &showlist);
14138   add_cmd ("memory-write-packet-size", no_class,
14139            set_memory_write_packet_size, _("\
14140 Set the maximum number of bytes per memory-write packet.\n\
14141 Specify the number of bytes in a packet or 0 (zero) for the\n\
14142 default packet size.  The actual limit is further reduced\n\
14143 dependent on the target.  Specify ``fixed'' to disable the\n\
14144 further restriction and ``limit'' to enable that restriction."),
14145            &remote_set_cmdlist);
14146   add_cmd ("memory-read-packet-size", no_class,
14147            set_memory_read_packet_size, _("\
14148 Set the maximum number of bytes per memory-read packet.\n\
14149 Specify the number of bytes in a packet or 0 (zero) for the\n\
14150 default packet size.  The actual limit is further reduced\n\
14151 dependent on the target.  Specify ``fixed'' to disable the\n\
14152 further restriction and ``limit'' to enable that restriction."),
14153            &remote_set_cmdlist);
14154   add_cmd ("memory-write-packet-size", no_class,
14155            show_memory_write_packet_size,
14156            _("Show the maximum number of bytes per memory-write packet."),
14157            &remote_show_cmdlist);
14158   add_cmd ("memory-read-packet-size", no_class,
14159            show_memory_read_packet_size,
14160            _("Show the maximum number of bytes per memory-read packet."),
14161            &remote_show_cmdlist);
14162
14163   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14164                             &remote_hw_watchpoint_limit, _("\
14165 Set the maximum number of target hardware watchpoints."), _("\
14166 Show the maximum number of target hardware watchpoints."), _("\
14167 Specify a negative limit for unlimited."),
14168                             NULL, NULL, /* FIXME: i18n: The maximum
14169                                            number of target hardware
14170                                            watchpoints is %s.  */
14171                             &remote_set_cmdlist, &remote_show_cmdlist);
14172   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14173                             &remote_hw_watchpoint_length_limit, _("\
14174 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14175 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14176 Specify a negative limit for unlimited."),
14177                             NULL, NULL, /* FIXME: i18n: The maximum
14178                                            length (in bytes) of a target
14179                                            hardware watchpoint is %s.  */
14180                             &remote_set_cmdlist, &remote_show_cmdlist);
14181   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14182                             &remote_hw_breakpoint_limit, _("\
14183 Set the maximum number of target hardware breakpoints."), _("\
14184 Show the maximum number of target hardware breakpoints."), _("\
14185 Specify a negative limit for unlimited."),
14186                             NULL, NULL, /* FIXME: i18n: The maximum
14187                                            number of target hardware
14188                                            breakpoints is %s.  */
14189                             &remote_set_cmdlist, &remote_show_cmdlist);
14190
14191   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14192                              &remote_address_size, _("\
14193 Set the maximum size of the address (in bits) in a memory packet."), _("\
14194 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14195                              NULL,
14196                              NULL, /* FIXME: i18n: */
14197                              &setlist, &showlist);
14198
14199   init_all_packet_configs ();
14200
14201   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14202                          "X", "binary-download", 1);
14203
14204   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14205                          "vCont", "verbose-resume", 0);
14206
14207   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14208                          "QPassSignals", "pass-signals", 0);
14209
14210   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14211                          "QCatchSyscalls", "catch-syscalls", 0);
14212
14213   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14214                          "QProgramSignals", "program-signals", 0);
14215
14216   add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14217                          "QSetWorkingDir", "set-working-dir", 0);
14218
14219   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14220                          "QStartupWithShell", "startup-with-shell", 0);
14221
14222   add_packet_config_cmd (&remote_protocol_packets
14223                          [PACKET_QEnvironmentHexEncoded],
14224                          "QEnvironmentHexEncoded", "environment-hex-encoded",
14225                          0);
14226
14227   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14228                          "QEnvironmentReset", "environment-reset",
14229                          0);
14230
14231   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14232                          "QEnvironmentUnset", "environment-unset",
14233                          0);
14234
14235   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14236                          "qSymbol", "symbol-lookup", 0);
14237
14238   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14239                          "P", "set-register", 1);
14240
14241   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14242                          "p", "fetch-register", 1);
14243
14244   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14245                          "Z0", "software-breakpoint", 0);
14246
14247   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14248                          "Z1", "hardware-breakpoint", 0);
14249
14250   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14251                          "Z2", "write-watchpoint", 0);
14252
14253   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14254                          "Z3", "read-watchpoint", 0);
14255
14256   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14257                          "Z4", "access-watchpoint", 0);
14258
14259   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14260                          "qXfer:auxv:read", "read-aux-vector", 0);
14261
14262   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14263                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
14264
14265   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14266                          "qXfer:features:read", "target-features", 0);
14267
14268   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14269                          "qXfer:libraries:read", "library-info", 0);
14270
14271   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14272                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14273
14274   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14275                          "qXfer:memory-map:read", "memory-map", 0);
14276
14277   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14278                          "qXfer:spu:read", "read-spu-object", 0);
14279
14280   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14281                          "qXfer:spu:write", "write-spu-object", 0);
14282
14283   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14284                         "qXfer:osdata:read", "osdata", 0);
14285
14286   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14287                          "qXfer:threads:read", "threads", 0);
14288
14289   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14290                          "qXfer:siginfo:read", "read-siginfo-object", 0);
14291
14292   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14293                          "qXfer:siginfo:write", "write-siginfo-object", 0);
14294
14295   add_packet_config_cmd
14296     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14297      "qXfer:traceframe-info:read", "traceframe-info", 0);
14298
14299   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14300                          "qXfer:uib:read", "unwind-info-block", 0);
14301
14302   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14303                          "qGetTLSAddr", "get-thread-local-storage-address",
14304                          0);
14305
14306   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14307                          "qGetTIBAddr", "get-thread-information-block-address",
14308                          0);
14309
14310   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14311                          "bc", "reverse-continue", 0);
14312
14313   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14314                          "bs", "reverse-step", 0);
14315
14316   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14317                          "qSupported", "supported-packets", 0);
14318
14319   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14320                          "qSearch:memory", "search-memory", 0);
14321
14322   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14323                          "qTStatus", "trace-status", 0);
14324
14325   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14326                          "vFile:setfs", "hostio-setfs", 0);
14327
14328   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14329                          "vFile:open", "hostio-open", 0);
14330
14331   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14332                          "vFile:pread", "hostio-pread", 0);
14333
14334   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14335                          "vFile:pwrite", "hostio-pwrite", 0);
14336
14337   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14338                          "vFile:close", "hostio-close", 0);
14339
14340   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14341                          "vFile:unlink", "hostio-unlink", 0);
14342
14343   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14344                          "vFile:readlink", "hostio-readlink", 0);
14345
14346   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14347                          "vFile:fstat", "hostio-fstat", 0);
14348
14349   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14350                          "vAttach", "attach", 0);
14351
14352   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14353                          "vRun", "run", 0);
14354
14355   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14356                          "QStartNoAckMode", "noack", 0);
14357
14358   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14359                          "vKill", "kill", 0);
14360
14361   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14362                          "qAttached", "query-attached", 0);
14363
14364   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14365                          "ConditionalTracepoints",
14366                          "conditional-tracepoints", 0);
14367
14368   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14369                          "ConditionalBreakpoints",
14370                          "conditional-breakpoints", 0);
14371
14372   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14373                          "BreakpointCommands",
14374                          "breakpoint-commands", 0);
14375
14376   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14377                          "FastTracepoints", "fast-tracepoints", 0);
14378
14379   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14380                          "TracepointSource", "TracepointSource", 0);
14381
14382   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14383                          "QAllow", "allow", 0);
14384
14385   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14386                          "StaticTracepoints", "static-tracepoints", 0);
14387
14388   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14389                          "InstallInTrace", "install-in-trace", 0);
14390
14391   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14392                          "qXfer:statictrace:read", "read-sdata-object", 0);
14393
14394   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14395                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14396
14397   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14398                          "QDisableRandomization", "disable-randomization", 0);
14399
14400   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14401                          "QAgent", "agent", 0);
14402
14403   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14404                          "QTBuffer:size", "trace-buffer-size", 0);
14405
14406   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14407        "Qbtrace:off", "disable-btrace", 0);
14408
14409   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14410        "Qbtrace:bts", "enable-btrace-bts", 0);
14411
14412   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14413        "Qbtrace:pt", "enable-btrace-pt", 0);
14414
14415   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14416        "qXfer:btrace", "read-btrace", 0);
14417
14418   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14419        "qXfer:btrace-conf", "read-btrace-conf", 0);
14420
14421   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14422        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14423
14424   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14425        "multiprocess-feature", "multiprocess-feature", 0);
14426
14427   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14428                          "swbreak-feature", "swbreak-feature", 0);
14429
14430   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14431                          "hwbreak-feature", "hwbreak-feature", 0);
14432
14433   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14434                          "fork-event-feature", "fork-event-feature", 0);
14435
14436   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14437                          "vfork-event-feature", "vfork-event-feature", 0);
14438
14439   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14440        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14441
14442   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14443                          "vContSupported", "verbose-resume-supported", 0);
14444
14445   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14446                          "exec-event-feature", "exec-event-feature", 0);
14447
14448   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14449                          "vCtrlC", "ctrl-c", 0);
14450
14451   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14452                          "QThreadEvents", "thread-events", 0);
14453
14454   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14455                          "N stop reply", "no-resumed-stop-reply", 0);
14456
14457   /* Assert that we've registered "set remote foo-packet" commands
14458      for all packet configs.  */
14459   {
14460     int i;
14461
14462     for (i = 0; i < PACKET_MAX; i++)
14463       {
14464         /* Ideally all configs would have a command associated.  Some
14465            still don't though.  */
14466         int excepted;
14467
14468         switch (i)
14469           {
14470           case PACKET_QNonStop:
14471           case PACKET_EnableDisableTracepoints_feature:
14472           case PACKET_tracenz_feature:
14473           case PACKET_DisconnectedTracing_feature:
14474           case PACKET_augmented_libraries_svr4_read_feature:
14475           case PACKET_qCRC:
14476             /* Additions to this list need to be well justified:
14477                pre-existing packets are OK; new packets are not.  */
14478             excepted = 1;
14479             break;
14480           default:
14481             excepted = 0;
14482             break;
14483           }
14484
14485         /* This catches both forgetting to add a config command, and
14486            forgetting to remove a packet from the exception list.  */
14487         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14488       }
14489   }
14490
14491   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
14492      Z sub-packet has its own set and show commands, but users may
14493      have sets to this variable in their .gdbinit files (or in their
14494      documentation).  */
14495   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14496                                 &remote_Z_packet_detect, _("\
14497 Set use of remote protocol `Z' packets"), _("\
14498 Show use of remote protocol `Z' packets "), _("\
14499 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14500 packets."),
14501                                 set_remote_protocol_Z_packet_cmd,
14502                                 show_remote_protocol_Z_packet_cmd,
14503                                 /* FIXME: i18n: Use of remote protocol
14504                                    `Z' packets is %s.  */
14505                                 &remote_set_cmdlist, &remote_show_cmdlist);
14506
14507   add_prefix_cmd ("remote", class_files, remote_command, _("\
14508 Manipulate files on the remote system\n\
14509 Transfer files to and from the remote target system."),
14510                   &remote_cmdlist, "remote ",
14511                   0 /* allow-unknown */, &cmdlist);
14512
14513   add_cmd ("put", class_files, remote_put_command,
14514            _("Copy a local file to the remote system."),
14515            &remote_cmdlist);
14516
14517   add_cmd ("get", class_files, remote_get_command,
14518            _("Copy a remote file to the local system."),
14519            &remote_cmdlist);
14520
14521   add_cmd ("delete", class_files, remote_delete_command,
14522            _("Delete a remote file."),
14523            &remote_cmdlist);
14524
14525   add_setshow_string_noescape_cmd ("exec-file", class_files,
14526                                    &remote_exec_file_var, _("\
14527 Set the remote pathname for \"run\""), _("\
14528 Show the remote pathname for \"run\""), NULL,
14529                                    set_remote_exec_file,
14530                                    show_remote_exec_file,
14531                                    &remote_set_cmdlist,
14532                                    &remote_show_cmdlist);
14533
14534   add_setshow_boolean_cmd ("range-stepping", class_run,
14535                            &use_range_stepping, _("\
14536 Enable or disable range stepping."), _("\
14537 Show whether target-assisted range stepping is enabled."), _("\
14538 If on, and the target supports it, when stepping a source line, GDB\n\
14539 tells the target to step the corresponding range of addresses itself instead\n\
14540 of issuing multiple single-steps.  This speeds up source level\n\
14541 stepping.  If off, GDB always issues single-steps, even if range\n\
14542 stepping is supported by the target.  The default is on."),
14543                            set_range_stepping,
14544                            show_range_stepping,
14545                            &setlist,
14546                            &showlist);
14547
14548   /* Eventually initialize fileio.  See fileio.c */
14549   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14550
14551   /* Take advantage of the fact that the TID field is not used, to tag
14552      special ptids with it set to != 0.  */
14553   magic_null_ptid = ptid_build (42000, -1, 1);
14554   not_sent_ptid = ptid_build (42000, -2, 1);
14555   any_thread_ptid = ptid_build (42000, 0, 1);
14556 }