Workaround gdbserver<7.7 for setfs
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2016 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 "observer.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
74 /* Temp hacks for tracepoint encoding migration.  */
75 static char *target_buf;
76 static long target_buf_size;
77
78 /* Per-program-space data key.  */
79 static const struct program_space_data *remote_pspace_data;
80
81 /* The variable registered as the control variable used by the
82    remote exec-file commands.  While the remote exec-file setting is
83    per-program-space, the set/show machinery uses this as the 
84    location of the remote exec-file value.  */
85 static char *remote_exec_file_var;
86
87 /* The size to align memory write packets, when practical.  The protocol
88    does not guarantee any alignment, and gdb will generate short
89    writes and unaligned writes, but even as a best-effort attempt this
90    can improve bulk transfers.  For instance, if a write is misaligned
91    relative to the target's data bus, the stub may need to make an extra
92    round trip fetching data from the target.  This doesn't make a
93    huge difference, but it's easy to do, so we try to be helpful.
94
95    The alignment chosen is arbitrary; usually data bus width is
96    important here, not the possibly larger cache line size.  */
97 enum { REMOTE_ALIGN_WRITES = 16 };
98
99 /* Prototypes for local functions.  */
100 static void async_cleanup_sigint_signal_handler (void *dummy);
101 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
102 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
103                                  int forever, int *is_notif);
104
105 static void async_handle_remote_sigint (int);
106 static void async_handle_remote_sigint_twice (int);
107
108 static void remote_files_info (struct target_ops *ignore);
109
110 static void remote_prepare_to_store (struct target_ops *self,
111                                      struct regcache *regcache);
112
113 static void remote_open_1 (const char *, int, struct target_ops *,
114                            int extended_p);
115
116 static void remote_close (struct target_ops *self);
117
118 struct remote_state;
119
120 static int remote_vkill (int pid, struct remote_state *rs);
121
122 static void remote_kill_k (void);
123
124 static void remote_mourn (struct target_ops *ops);
125
126 static void extended_remote_restart (void);
127
128 static void remote_send (char **buf, long *sizeof_buf_p);
129
130 static int readchar (int timeout);
131
132 static void remote_serial_write (const char *str, int len);
133
134 static void remote_kill (struct target_ops *ops);
135
136 static int remote_can_async_p (struct target_ops *);
137
138 static int remote_is_async_p (struct target_ops *);
139
140 static void remote_async (struct target_ops *ops, int enable);
141
142 static void remote_thread_events (struct target_ops *ops, int enable);
143
144 static void sync_remote_interrupt_twice (int signo);
145
146 static void interrupt_query (void);
147
148 static void set_general_thread (struct ptid ptid);
149 static void set_continue_thread (struct ptid ptid);
150
151 static void get_offsets (void);
152
153 static void skip_frame (void);
154
155 static long read_frame (char **buf_p, long *sizeof_buf);
156
157 static int hexnumlen (ULONGEST num);
158
159 static void init_remote_ops (void);
160
161 static void init_extended_remote_ops (void);
162
163 static void remote_stop (struct target_ops *self, ptid_t);
164
165 static int stubhex (int ch);
166
167 static int hexnumstr (char *, ULONGEST);
168
169 static int hexnumnstr (char *, ULONGEST, int);
170
171 static CORE_ADDR remote_address_masked (CORE_ADDR);
172
173 static void print_packet (const char *);
174
175 static void compare_sections_command (char *, int);
176
177 static void packet_command (char *, int);
178
179 static int stub_unpack_int (char *buff, int fieldlength);
180
181 static ptid_t remote_current_thread (ptid_t oldptid);
182
183 static int putpkt_binary (const char *buf, int cnt);
184
185 static void check_binary_download (CORE_ADDR addr);
186
187 struct packet_config;
188
189 static void show_packet_config_cmd (struct packet_config *config);
190
191 static void show_remote_protocol_packet_cmd (struct ui_file *file,
192                                              int from_tty,
193                                              struct cmd_list_element *c,
194                                              const char *value);
195
196 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
197 static ptid_t read_ptid (char *buf, char **obuf);
198
199 static void remote_set_permissions (struct target_ops *self);
200
201 static int remote_get_trace_status (struct target_ops *self,
202                                     struct trace_status *ts);
203
204 static int remote_upload_tracepoints (struct target_ops *self,
205                                       struct uploaded_tp **utpp);
206
207 static int remote_upload_trace_state_variables (struct target_ops *self,
208                                                 struct uploaded_tsv **utsvp);
209   
210 static void remote_query_supported (void);
211
212 static void remote_check_symbols (void);
213
214 void _initialize_remote (void);
215
216 struct stop_reply;
217 static void stop_reply_xfree (struct stop_reply *);
218 static void remote_parse_stop_reply (char *, struct stop_reply *);
219 static void push_stop_reply (struct stop_reply *);
220 static void discard_pending_stop_replies_in_queue (struct remote_state *);
221 static int peek_stop_reply (ptid_t ptid);
222
223 struct threads_listing_context;
224 static void remove_new_fork_children (struct threads_listing_context *);
225
226 static void remote_async_inferior_event_handler (gdb_client_data);
227
228 static void remote_terminal_ours (struct target_ops *self);
229
230 static int remote_read_description_p (struct target_ops *target);
231
232 static void remote_console_output (char *msg);
233
234 static int remote_supports_cond_breakpoints (struct target_ops *self);
235
236 static int remote_can_run_breakpoint_commands (struct target_ops *self);
237
238 static void remote_btrace_reset (void);
239
240 static int stop_reply_queue_length (void);
241
242 static void readahead_cache_invalidate (void);
243
244 /* For "remote".  */
245
246 static struct cmd_list_element *remote_cmdlist;
247
248 /* For "set remote" and "show remote".  */
249
250 static struct cmd_list_element *remote_set_cmdlist;
251 static struct cmd_list_element *remote_show_cmdlist;
252
253 /* Stub vCont actions support.
254
255    Each field is a boolean flag indicating whether the stub reports
256    support for the corresponding action.  */
257
258 struct vCont_action_support
259 {
260   /* vCont;t */
261   int t;
262
263   /* vCont;r */
264   int r;
265
266   /* vCont;s */
267   int s;
268
269   /* vCont;S */
270   int S;
271 };
272
273 /* Controls whether GDB is willing to use range stepping.  */
274
275 static int use_range_stepping = 1;
276
277 #define OPAQUETHREADBYTES 8
278
279 /* a 64 bit opaque identifier */
280 typedef unsigned char threadref[OPAQUETHREADBYTES];
281
282 /* About this many threadisds fit in a packet.  */
283
284 #define MAXTHREADLISTRESULTS 32
285
286 /* Data for the vFile:pread readahead cache.  */
287
288 struct readahead_cache
289 {
290   /* The file descriptor for the file that is being cached.  -1 if the
291      cache is invalid.  */
292   int fd;
293
294   /* The offset into the file that the cache buffer corresponds
295      to.  */
296   ULONGEST offset;
297
298   /* The buffer holding the cache contents.  */
299   gdb_byte *buf;
300   /* The buffer's size.  We try to read as much as fits into a packet
301      at a time.  */
302   size_t bufsize;
303
304   /* Cache hit and miss counters.  */
305   ULONGEST hit_count;
306   ULONGEST miss_count;
307 };
308
309 /* Description of the remote protocol state for the currently
310    connected target.  This is per-target state, and independent of the
311    selected architecture.  */
312
313 struct remote_state
314 {
315   /* A buffer to use for incoming packets, and its current size.  The
316      buffer is grown dynamically for larger incoming packets.
317      Outgoing packets may also be constructed in this buffer.
318      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
320      packets.  */
321   char *buf;
322   long buf_size;
323
324   /* True if we're going through initial connection setup (finding out
325      about the remote side's threads, relocating symbols, etc.).  */
326   int starting_up;
327
328   /* If we negotiated packet size explicitly (and thus can bypass
329      heuristics for the largest packet size that will not overflow
330      a buffer in the stub), this will be set to that packet size.
331      Otherwise zero, meaning to use the guessed size.  */
332   long explicit_packet_size;
333
334   /* remote_wait is normally called when the target is running and
335      waits for a stop reply packet.  But sometimes we need to call it
336      when the target is already stopped.  We can send a "?" packet
337      and have remote_wait read the response.  Or, if we already have
338      the response, we can stash it in BUF and tell remote_wait to
339      skip calling getpkt.  This flag is set when BUF contains a
340      stop reply packet and the target is not waiting.  */
341   int cached_wait_status;
342
343   /* True, if in no ack mode.  That is, neither GDB nor the stub will
344      expect acks from each other.  The connection is assumed to be
345      reliable.  */
346   int noack_mode;
347
348   /* True if we're connected in extended remote mode.  */
349   int extended;
350
351   /* True if we resumed the target and we're waiting for the target to
352      stop.  In the mean time, we can't start another command/query.
353      The remote server wouldn't be ready to process it, so we'd
354      timeout waiting for a reply that would never come and eventually
355      we'd close the connection.  This can happen in asynchronous mode
356      because we allow GDB commands while the target is running.  */
357   int waiting_for_stop_reply;
358
359   /* The status of the stub support for the various vCont actions.  */
360   struct vCont_action_support supports_vCont;
361
362   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363      responded to that.  */
364   int ctrlc_pending_p;
365
366   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
367      remote_open knows that we don't have a file open when the program
368      starts.  */
369   struct serial *remote_desc;
370
371   /* These are the threads which we last sent to the remote system.  The
372      TID member will be -1 for all or -2 for not sent yet.  */
373   ptid_t general_thread;
374   ptid_t continue_thread;
375
376   /* This is the traceframe which we last selected on the remote system.
377      It will be -1 if no traceframe is selected.  */
378   int remote_traceframe_number;
379
380   char *last_pass_packet;
381
382   /* The last QProgramSignals packet sent to the target.  We bypass
383      sending a new program signals list down to the target if the new
384      packet is exactly the same as the last we sent.  IOW, we only let
385      the target know about program signals list changes.  */
386   char *last_program_signals_packet;
387
388   enum gdb_signal last_sent_signal;
389
390   int last_sent_step;
391
392   char *finished_object;
393   char *finished_annex;
394   ULONGEST finished_offset;
395
396   /* Should we try the 'ThreadInfo' query packet?
397
398      This variable (NOT available to the user: auto-detect only!)
399      determines whether GDB will use the new, simpler "ThreadInfo"
400      query or the older, more complex syntax for thread queries.
401      This is an auto-detect variable (set to true at each connect,
402      and set to false when the target fails to recognize it).  */
403   int use_threadinfo_query;
404   int use_threadextra_query;
405
406   threadref echo_nextthread;
407   threadref nextthread;
408   threadref resultthreadlist[MAXTHREADLISTRESULTS];
409
410   /* The state of remote notification.  */
411   struct remote_notif_state *notif_state;
412
413   /* The branch trace configuration.  */
414   struct btrace_config btrace_config;
415
416   /* The argument to the last "vFile:setfs:" packet we sent, used
417      to avoid sending repeated unnecessary "vFile:setfs:" packets.
418      Initialized to -1 to indicate that no "vFile:setfs:" packet
419      has yet been sent.  */
420   int fs_pid;
421
422   /* A readahead cache for vFile:pread.  Often, reading a binary
423      involves a sequence of small reads.  E.g., when parsing an ELF
424      file.  A readahead cache helps mostly the case of remote
425      debugging on a connection with higher latency, due to the
426      request/reply nature of the RSP.  We only cache data for a single
427      file descriptor at a time.  */
428   struct readahead_cache readahead_cache;
429
430   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
431      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
432      as a reply to known packet.  For packet "vFile:setfs:" it is an
433      invalid reply and GDB would return error in
434      remote_hostio_set_filesystem, making remote files access impossible.
435      If this variable is non-zero it means the remote gdbserver is buggy
436      and any not yet detected packets are assumed as unsupported.  */
437   int unknown_v_replies_ok;
438 };
439
440 /* Private data that we'll store in (struct thread_info)->private.  */
441 struct private_thread_info
442 {
443   char *extra;
444   char *name;
445   int core;
446
447   /* Whether the target stopped for a breakpoint/watchpoint.  */
448   enum target_stop_reason stop_reason;
449
450   /* This is set to the data address of the access causing the target
451      to stop for a watchpoint.  */
452   CORE_ADDR watch_data_address;
453 };
454
455 static void
456 free_private_thread_info (struct private_thread_info *info)
457 {
458   xfree (info->extra);
459   xfree (info->name);
460   xfree (info);
461 }
462
463 /* This data could be associated with a target, but we do not always
464    have access to the current target when we need it, so for now it is
465    static.  This will be fine for as long as only one target is in use
466    at a time.  */
467 static struct remote_state *remote_state;
468
469 static struct remote_state *
470 get_remote_state_raw (void)
471 {
472   return remote_state;
473 }
474
475 /* Allocate a new struct remote_state with xmalloc, initialize it, and
476    return it.  */
477
478 static struct remote_state *
479 new_remote_state (void)
480 {
481   struct remote_state *result = XCNEW (struct remote_state);
482
483   /* The default buffer size is unimportant; it will be expanded
484      whenever a larger buffer is needed. */
485   result->buf_size = 400;
486   result->buf = (char *) xmalloc (result->buf_size);
487   result->remote_traceframe_number = -1;
488   result->last_sent_signal = GDB_SIGNAL_0;
489   result->fs_pid = -1;
490
491   return result;
492 }
493
494 /* Description of the remote protocol for a given architecture.  */
495
496 struct packet_reg
497 {
498   long offset; /* Offset into G packet.  */
499   long regnum; /* GDB's internal register number.  */
500   LONGEST pnum; /* Remote protocol register number.  */
501   int in_g_packet; /* Always part of G packet.  */
502   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
503      at present.  */
504   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
505      at present.  */
506 };
507
508 struct remote_arch_state
509 {
510   /* Description of the remote protocol registers.  */
511   long sizeof_g_packet;
512
513   /* Description of the remote protocol registers indexed by REGNUM
514      (making an array gdbarch_num_regs in size).  */
515   struct packet_reg *regs;
516
517   /* This is the size (in chars) of the first response to the ``g''
518      packet.  It is used as a heuristic when determining the maximum
519      size of memory-read and memory-write packets.  A target will
520      typically only reserve a buffer large enough to hold the ``g''
521      packet.  The size does not include packet overhead (headers and
522      trailers).  */
523   long actual_register_packet_size;
524
525   /* This is the maximum size (in chars) of a non read/write packet.
526      It is also used as a cap on the size of read/write packets.  */
527   long remote_packet_size;
528 };
529
530 /* Utility: generate error from an incoming stub packet.  */
531 static void
532 trace_error (char *buf)
533 {
534   if (*buf++ != 'E')
535     return;                     /* not an error msg */
536   switch (*buf)
537     {
538     case '1':                   /* malformed packet error */
539       if (*++buf == '0')        /*   general case: */
540         error (_("remote.c: error in outgoing packet."));
541       else
542         error (_("remote.c: error in outgoing packet at field #%ld."),
543                strtol (buf, NULL, 16));
544     default:
545       error (_("Target returns error code '%s'."), buf);
546     }
547 }
548
549 /* Utility: wait for reply from stub, while accepting "O" packets.  */
550 static char *
551 remote_get_noisy_reply (char **buf_p,
552                         long *sizeof_buf)
553 {
554   do                            /* Loop on reply from remote stub.  */
555     {
556       char *buf;
557
558       QUIT;                     /* Allow user to bail out with ^C.  */
559       getpkt (buf_p, sizeof_buf, 0);
560       buf = *buf_p;
561       if (buf[0] == 'E')
562         trace_error (buf);
563       else if (startswith (buf, "qRelocInsn:"))
564         {
565           ULONGEST ul;
566           CORE_ADDR from, to, org_to;
567           char *p, *pp;
568           int adjusted_size = 0;
569           int relocated = 0;
570
571           p = buf + strlen ("qRelocInsn:");
572           pp = unpack_varlen_hex (p, &ul);
573           if (*pp != ';')
574             error (_("invalid qRelocInsn packet: %s"), buf);
575           from = ul;
576
577           p = pp + 1;
578           unpack_varlen_hex (p, &ul);
579           to = ul;
580
581           org_to = to;
582
583           TRY
584             {
585               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
586               relocated = 1;
587             }
588           CATCH (ex, RETURN_MASK_ALL)
589             {
590               if (ex.error == MEMORY_ERROR)
591                 {
592                   /* Propagate memory errors silently back to the
593                      target.  The stub may have limited the range of
594                      addresses we can write to, for example.  */
595                 }
596               else
597                 {
598                   /* Something unexpectedly bad happened.  Be verbose
599                      so we can tell what, and propagate the error back
600                      to the stub, so it doesn't get stuck waiting for
601                      a response.  */
602                   exception_fprintf (gdb_stderr, ex,
603                                      _("warning: relocating instruction: "));
604                 }
605               putpkt ("E01");
606             }
607           END_CATCH
608
609           if (relocated)
610             {
611               adjusted_size = to - org_to;
612
613               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
614               putpkt (buf);
615             }
616         }
617       else if (buf[0] == 'O' && buf[1] != 'K')
618         remote_console_output (buf + 1);        /* 'O' message from stub */
619       else
620         return buf;             /* Here's the actual reply.  */
621     }
622   while (1);
623 }
624
625 /* Handle for retreving the remote protocol data from gdbarch.  */
626 static struct gdbarch_data *remote_gdbarch_data_handle;
627
628 static struct remote_arch_state *
629 get_remote_arch_state (void)
630 {
631   gdb_assert (target_gdbarch () != NULL);
632   return ((struct remote_arch_state *)
633           gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
634 }
635
636 /* Fetch the global remote target state.  */
637
638 static struct remote_state *
639 get_remote_state (void)
640 {
641   /* Make sure that the remote architecture state has been
642      initialized, because doing so might reallocate rs->buf.  Any
643      function which calls getpkt also needs to be mindful of changes
644      to rs->buf, but this call limits the number of places which run
645      into trouble.  */
646   get_remote_arch_state ();
647
648   return get_remote_state_raw ();
649 }
650
651 /* Cleanup routine for the remote module's pspace data.  */
652
653 static void
654 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
655 {
656   char *remote_exec_file = (char *) arg;
657
658   xfree (remote_exec_file);
659 }
660
661 /* Fetch the remote exec-file from the current program space.  */
662
663 static const char *
664 get_remote_exec_file (void)
665 {
666   char *remote_exec_file;
667
668   remote_exec_file
669     = (char *) program_space_data (current_program_space,
670                                    remote_pspace_data);
671   if (remote_exec_file == NULL)
672     return "";
673
674   return remote_exec_file;
675 }
676
677 /* Set the remote exec file for PSPACE.  */
678
679 static void
680 set_pspace_remote_exec_file (struct program_space *pspace,
681                         char *remote_exec_file)
682 {
683   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
684
685   xfree (old_file);
686   set_program_space_data (pspace, remote_pspace_data,
687                           xstrdup (remote_exec_file));
688 }
689
690 /* The "set/show remote exec-file" set command hook.  */
691
692 static void
693 set_remote_exec_file (char *ignored, int from_tty,
694                       struct cmd_list_element *c)
695 {
696   gdb_assert (remote_exec_file_var != NULL);
697   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
698 }
699
700 /* The "set/show remote exec-file" show command hook.  */
701
702 static void
703 show_remote_exec_file (struct ui_file *file, int from_tty,
704                        struct cmd_list_element *cmd, const char *value)
705 {
706   fprintf_filtered (file, "%s\n", remote_exec_file_var);
707 }
708
709 static int
710 compare_pnums (const void *lhs_, const void *rhs_)
711 {
712   const struct packet_reg * const *lhs
713     = (const struct packet_reg * const *) lhs_;
714   const struct packet_reg * const *rhs
715     = (const struct packet_reg * const *) rhs_;
716
717   if ((*lhs)->pnum < (*rhs)->pnum)
718     return -1;
719   else if ((*lhs)->pnum == (*rhs)->pnum)
720     return 0;
721   else
722     return 1;
723 }
724
725 static int
726 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
727 {
728   int regnum, num_remote_regs, offset;
729   struct packet_reg **remote_regs;
730
731   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
732     {
733       struct packet_reg *r = &regs[regnum];
734
735       if (register_size (gdbarch, regnum) == 0)
736         /* Do not try to fetch zero-sized (placeholder) registers.  */
737         r->pnum = -1;
738       else
739         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
740
741       r->regnum = regnum;
742     }
743
744   /* Define the g/G packet format as the contents of each register
745      with a remote protocol number, in order of ascending protocol
746      number.  */
747
748   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
749   for (num_remote_regs = 0, regnum = 0;
750        regnum < gdbarch_num_regs (gdbarch);
751        regnum++)
752     if (regs[regnum].pnum != -1)
753       remote_regs[num_remote_regs++] = &regs[regnum];
754
755   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
756          compare_pnums);
757
758   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
759     {
760       remote_regs[regnum]->in_g_packet = 1;
761       remote_regs[regnum]->offset = offset;
762       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
763     }
764
765   return offset;
766 }
767
768 /* Given the architecture described by GDBARCH, return the remote
769    protocol register's number and the register's offset in the g/G
770    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
771    If the target does not have a mapping for REGNUM, return false,
772    otherwise, return true.  */
773
774 int
775 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
776                                    int *pnum, int *poffset)
777 {
778   struct packet_reg *regs;
779   struct cleanup *old_chain;
780
781   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
782
783   regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
784   old_chain = make_cleanup (xfree, regs);
785
786   map_regcache_remote_table (gdbarch, regs);
787
788   *pnum = regs[regnum].pnum;
789   *poffset = regs[regnum].offset;
790
791   do_cleanups (old_chain);
792
793   return *pnum != -1;
794 }
795
796 static void *
797 init_remote_state (struct gdbarch *gdbarch)
798 {
799   struct remote_state *rs = get_remote_state_raw ();
800   struct remote_arch_state *rsa;
801
802   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
803
804   /* Use the architecture to build a regnum<->pnum table, which will be
805      1:1 unless a feature set specifies otherwise.  */
806   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
807                                       gdbarch_num_regs (gdbarch),
808                                       struct packet_reg);
809
810   /* Record the maximum possible size of the g packet - it may turn out
811      to be smaller.  */
812   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
813
814   /* Default maximum number of characters in a packet body.  Many
815      remote stubs have a hardwired buffer size of 400 bytes
816      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
817      as the maximum packet-size to ensure that the packet and an extra
818      NUL character can always fit in the buffer.  This stops GDB
819      trashing stubs that try to squeeze an extra NUL into what is
820      already a full buffer (As of 1999-12-04 that was most stubs).  */
821   rsa->remote_packet_size = 400 - 1;
822
823   /* This one is filled in when a ``g'' packet is received.  */
824   rsa->actual_register_packet_size = 0;
825
826   /* Should rsa->sizeof_g_packet needs more space than the
827      default, adjust the size accordingly.  Remember that each byte is
828      encoded as two characters.  32 is the overhead for the packet
829      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
830      (``$NN:G...#NN'') is a better guess, the below has been padded a
831      little.  */
832   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
833     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
834
835   /* Make sure that the packet buffer is plenty big enough for
836      this architecture.  */
837   if (rs->buf_size < rsa->remote_packet_size)
838     {
839       rs->buf_size = 2 * rsa->remote_packet_size;
840       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
841     }
842
843   return rsa;
844 }
845
846 /* Return the current allowed size of a remote packet.  This is
847    inferred from the current architecture, and should be used to
848    limit the length of outgoing packets.  */
849 static long
850 get_remote_packet_size (void)
851 {
852   struct remote_state *rs = get_remote_state ();
853   struct remote_arch_state *rsa = get_remote_arch_state ();
854
855   if (rs->explicit_packet_size)
856     return rs->explicit_packet_size;
857
858   return rsa->remote_packet_size;
859 }
860
861 static struct packet_reg *
862 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
863 {
864   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
865     return NULL;
866   else
867     {
868       struct packet_reg *r = &rsa->regs[regnum];
869
870       gdb_assert (r->regnum == regnum);
871       return r;
872     }
873 }
874
875 static struct packet_reg *
876 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
877 {
878   int i;
879
880   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
881     {
882       struct packet_reg *r = &rsa->regs[i];
883
884       if (r->pnum == pnum)
885         return r;
886     }
887   return NULL;
888 }
889
890 static struct target_ops remote_ops;
891
892 static struct target_ops extended_remote_ops;
893
894 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
895    ``forever'' still use the normal timeout mechanism.  This is
896    currently used by the ASYNC code to guarentee that target reads
897    during the initial connect always time-out.  Once getpkt has been
898    modified to return a timeout indication and, in turn
899    remote_wait()/wait_for_inferior() have gained a timeout parameter
900    this can go away.  */
901 static int wait_forever_enabled_p = 1;
902
903 /* Allow the user to specify what sequence to send to the remote
904    when he requests a program interruption: Although ^C is usually
905    what remote systems expect (this is the default, here), it is
906    sometimes preferable to send a break.  On other systems such
907    as the Linux kernel, a break followed by g, which is Magic SysRq g
908    is required in order to interrupt the execution.  */
909 const char interrupt_sequence_control_c[] = "Ctrl-C";
910 const char interrupt_sequence_break[] = "BREAK";
911 const char interrupt_sequence_break_g[] = "BREAK-g";
912 static const char *const interrupt_sequence_modes[] =
913   {
914     interrupt_sequence_control_c,
915     interrupt_sequence_break,
916     interrupt_sequence_break_g,
917     NULL
918   };
919 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
920
921 static void
922 show_interrupt_sequence (struct ui_file *file, int from_tty,
923                          struct cmd_list_element *c,
924                          const char *value)
925 {
926   if (interrupt_sequence_mode == interrupt_sequence_control_c)
927     fprintf_filtered (file,
928                       _("Send the ASCII ETX character (Ctrl-c) "
929                         "to the remote target to interrupt the "
930                         "execution of the program.\n"));
931   else if (interrupt_sequence_mode == interrupt_sequence_break)
932     fprintf_filtered (file,
933                       _("send a break signal to the remote target "
934                         "to interrupt the execution of the program.\n"));
935   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
936     fprintf_filtered (file,
937                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
938                         "the remote target to interrupt the execution "
939                         "of Linux kernel.\n"));
940   else
941     internal_error (__FILE__, __LINE__,
942                     _("Invalid value for interrupt_sequence_mode: %s."),
943                     interrupt_sequence_mode);
944 }
945
946 /* This boolean variable specifies whether interrupt_sequence is sent
947    to the remote target when gdb connects to it.
948    This is mostly needed when you debug the Linux kernel: The Linux kernel
949    expects BREAK g which is Magic SysRq g for connecting gdb.  */
950 static int interrupt_on_connect = 0;
951
952 /* This variable is used to implement the "set/show remotebreak" commands.
953    Since these commands are now deprecated in favor of "set/show remote
954    interrupt-sequence", it no longer has any effect on the code.  */
955 static int remote_break;
956
957 static void
958 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
959 {
960   if (remote_break)
961     interrupt_sequence_mode = interrupt_sequence_break;
962   else
963     interrupt_sequence_mode = interrupt_sequence_control_c;
964 }
965
966 static void
967 show_remotebreak (struct ui_file *file, int from_tty,
968                   struct cmd_list_element *c,
969                   const char *value)
970 {
971 }
972
973 /* This variable sets the number of bits in an address that are to be
974    sent in a memory ("M" or "m") packet.  Normally, after stripping
975    leading zeros, the entire address would be sent.  This variable
976    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
977    initial implementation of remote.c restricted the address sent in
978    memory packets to ``host::sizeof long'' bytes - (typically 32
979    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
980    address was never sent.  Since fixing this bug may cause a break in
981    some remote targets this variable is principly provided to
982    facilitate backward compatibility.  */
983
984 static unsigned int remote_address_size;
985
986 /* Temporary to track who currently owns the terminal.  See
987    remote_terminal_* for more details.  */
988
989 static int remote_async_terminal_ours_p;
990
991 \f
992 /* User configurable variables for the number of characters in a
993    memory read/write packet.  MIN (rsa->remote_packet_size,
994    rsa->sizeof_g_packet) is the default.  Some targets need smaller
995    values (fifo overruns, et.al.) and some users need larger values
996    (speed up transfers).  The variables ``preferred_*'' (the user
997    request), ``current_*'' (what was actually set) and ``forced_*''
998    (Positive - a soft limit, negative - a hard limit).  */
999
1000 struct memory_packet_config
1001 {
1002   char *name;
1003   long size;
1004   int fixed_p;
1005 };
1006
1007 /* The default max memory-write-packet-size.  The 16k is historical.
1008    (It came from older GDB's using alloca for buffers and the
1009    knowledge (folklore?) that some hosts don't cope very well with
1010    large alloca calls.)  */
1011 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1012
1013 /* The minimum remote packet size for memory transfers.  Ensures we
1014    can write at least one byte.  */
1015 #define MIN_MEMORY_PACKET_SIZE 20
1016
1017 /* Compute the current size of a read/write packet.  Since this makes
1018    use of ``actual_register_packet_size'' the computation is dynamic.  */
1019
1020 static long
1021 get_memory_packet_size (struct memory_packet_config *config)
1022 {
1023   struct remote_state *rs = get_remote_state ();
1024   struct remote_arch_state *rsa = get_remote_arch_state ();
1025
1026   long what_they_get;
1027   if (config->fixed_p)
1028     {
1029       if (config->size <= 0)
1030         what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1031       else
1032         what_they_get = config->size;
1033     }
1034   else
1035     {
1036       what_they_get = get_remote_packet_size ();
1037       /* Limit the packet to the size specified by the user.  */
1038       if (config->size > 0
1039           && what_they_get > config->size)
1040         what_they_get = config->size;
1041
1042       /* Limit it to the size of the targets ``g'' response unless we have
1043          permission from the stub to use a larger packet size.  */
1044       if (rs->explicit_packet_size == 0
1045           && rsa->actual_register_packet_size > 0
1046           && what_they_get > rsa->actual_register_packet_size)
1047         what_they_get = rsa->actual_register_packet_size;
1048     }
1049   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1050     what_they_get = MIN_MEMORY_PACKET_SIZE;
1051
1052   /* Make sure there is room in the global buffer for this packet
1053      (including its trailing NUL byte).  */
1054   if (rs->buf_size < what_they_get + 1)
1055     {
1056       rs->buf_size = 2 * what_they_get;
1057       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1058     }
1059
1060   return what_they_get;
1061 }
1062
1063 /* Update the size of a read/write packet.  If they user wants
1064    something really big then do a sanity check.  */
1065
1066 static void
1067 set_memory_packet_size (char *args, struct memory_packet_config *config)
1068 {
1069   int fixed_p = config->fixed_p;
1070   long size = config->size;
1071
1072   if (args == NULL)
1073     error (_("Argument required (integer, `fixed' or `limited')."));
1074   else if (strcmp (args, "hard") == 0
1075       || strcmp (args, "fixed") == 0)
1076     fixed_p = 1;
1077   else if (strcmp (args, "soft") == 0
1078            || strcmp (args, "limit") == 0)
1079     fixed_p = 0;
1080   else
1081     {
1082       char *end;
1083
1084       size = strtoul (args, &end, 0);
1085       if (args == end)
1086         error (_("Invalid %s (bad syntax)."), config->name);
1087
1088       /* Instead of explicitly capping the size of a packet to or
1089          disallowing it, the user is allowed to set the size to
1090          something arbitrarily large.  */
1091     }
1092
1093   /* So that the query shows the correct value.  */
1094   if (size <= 0)
1095     size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1096
1097   /* Extra checks?  */
1098   if (fixed_p && !config->fixed_p)
1099     {
1100       if (! query (_("The target may not be able to correctly handle a %s\n"
1101                    "of %ld bytes. Change the packet size? "),
1102                    config->name, size))
1103         error (_("Packet size not changed."));
1104     }
1105   /* Update the config.  */
1106   config->fixed_p = fixed_p;
1107   config->size = size;
1108 }
1109
1110 static void
1111 show_memory_packet_size (struct memory_packet_config *config)
1112 {
1113   printf_filtered (_("The %s is %ld. "), config->name, config->size);
1114   if (config->fixed_p)
1115     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1116                      get_memory_packet_size (config));
1117   else
1118     printf_filtered (_("Packets are limited to %ld bytes.\n"),
1119                      get_memory_packet_size (config));
1120 }
1121
1122 static struct memory_packet_config memory_write_packet_config =
1123 {
1124   "memory-write-packet-size",
1125 };
1126
1127 static void
1128 set_memory_write_packet_size (char *args, int from_tty)
1129 {
1130   set_memory_packet_size (args, &memory_write_packet_config);
1131 }
1132
1133 static void
1134 show_memory_write_packet_size (char *args, int from_tty)
1135 {
1136   show_memory_packet_size (&memory_write_packet_config);
1137 }
1138
1139 static long
1140 get_memory_write_packet_size (void)
1141 {
1142   return get_memory_packet_size (&memory_write_packet_config);
1143 }
1144
1145 static struct memory_packet_config memory_read_packet_config =
1146 {
1147   "memory-read-packet-size",
1148 };
1149
1150 static void
1151 set_memory_read_packet_size (char *args, int from_tty)
1152 {
1153   set_memory_packet_size (args, &memory_read_packet_config);
1154 }
1155
1156 static void
1157 show_memory_read_packet_size (char *args, int from_tty)
1158 {
1159   show_memory_packet_size (&memory_read_packet_config);
1160 }
1161
1162 static long
1163 get_memory_read_packet_size (void)
1164 {
1165   long size = get_memory_packet_size (&memory_read_packet_config);
1166
1167   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1168      extra buffer size argument before the memory read size can be
1169      increased beyond this.  */
1170   if (size > get_remote_packet_size ())
1171     size = get_remote_packet_size ();
1172   return size;
1173 }
1174
1175 \f
1176 /* Generic configuration support for packets the stub optionally
1177    supports.  Allows the user to specify the use of the packet as well
1178    as allowing GDB to auto-detect support in the remote stub.  */
1179
1180 enum packet_support
1181   {
1182     PACKET_SUPPORT_UNKNOWN = 0,
1183     PACKET_ENABLE,
1184     PACKET_DISABLE
1185   };
1186
1187 struct packet_config
1188   {
1189     const char *name;
1190     const char *title;
1191
1192     /* If auto, GDB auto-detects support for this packet or feature,
1193        either through qSupported, or by trying the packet and looking
1194        at the response.  If true, GDB assumes the target supports this
1195        packet.  If false, the packet is disabled.  Configs that don't
1196        have an associated command always have this set to auto.  */
1197     enum auto_boolean detect;
1198
1199     /* Does the target support this packet?  */
1200     enum packet_support support;
1201   };
1202
1203 /* Analyze a packet's return value and update the packet config
1204    accordingly.  */
1205
1206 enum packet_result
1207 {
1208   PACKET_ERROR,
1209   PACKET_OK,
1210   PACKET_UNKNOWN
1211 };
1212
1213 static enum packet_support packet_config_support (struct packet_config *config);
1214 static enum packet_support packet_support (int packet);
1215
1216 static void
1217 show_packet_config_cmd (struct packet_config *config)
1218 {
1219   char *support = "internal-error";
1220
1221   switch (packet_config_support (config))
1222     {
1223     case PACKET_ENABLE:
1224       support = "enabled";
1225       break;
1226     case PACKET_DISABLE:
1227       support = "disabled";
1228       break;
1229     case PACKET_SUPPORT_UNKNOWN:
1230       support = "unknown";
1231       break;
1232     }
1233   switch (config->detect)
1234     {
1235     case AUTO_BOOLEAN_AUTO:
1236       printf_filtered (_("Support for the `%s' packet "
1237                          "is auto-detected, currently %s.\n"),
1238                        config->name, support);
1239       break;
1240     case AUTO_BOOLEAN_TRUE:
1241     case AUTO_BOOLEAN_FALSE:
1242       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1243                        config->name, support);
1244       break;
1245     }
1246 }
1247
1248 static void
1249 add_packet_config_cmd (struct packet_config *config, const char *name,
1250                        const char *title, int legacy)
1251 {
1252   char *set_doc;
1253   char *show_doc;
1254   char *cmd_name;
1255
1256   config->name = name;
1257   config->title = title;
1258   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1259                         name, title);
1260   show_doc = xstrprintf ("Show current use of remote "
1261                          "protocol `%s' (%s) packet",
1262                          name, title);
1263   /* set/show TITLE-packet {auto,on,off} */
1264   cmd_name = xstrprintf ("%s-packet", title);
1265   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1266                                 &config->detect, set_doc,
1267                                 show_doc, NULL, /* help_doc */
1268                                 NULL,
1269                                 show_remote_protocol_packet_cmd,
1270                                 &remote_set_cmdlist, &remote_show_cmdlist);
1271   /* The command code copies the documentation strings.  */
1272   xfree (set_doc);
1273   xfree (show_doc);
1274   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1275   if (legacy)
1276     {
1277       char *legacy_name;
1278
1279       legacy_name = xstrprintf ("%s-packet", name);
1280       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1281                      &remote_set_cmdlist);
1282       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1283                      &remote_show_cmdlist);
1284     }
1285 }
1286
1287 static enum packet_result
1288 packet_check_result (const char *buf)
1289 {
1290   if (buf[0] != '\0')
1291     {
1292       /* The stub recognized the packet request.  Check that the
1293          operation succeeded.  */
1294       if (buf[0] == 'E'
1295           && isxdigit (buf[1]) && isxdigit (buf[2])
1296           && buf[3] == '\0')
1297         /* "Enn"  - definitly an error.  */
1298         return PACKET_ERROR;
1299
1300       /* Always treat "E." as an error.  This will be used for
1301          more verbose error messages, such as E.memtypes.  */
1302       if (buf[0] == 'E' && buf[1] == '.')
1303         return PACKET_ERROR;
1304
1305       /* The packet may or may not be OK.  Just assume it is.  */
1306       return PACKET_OK;
1307     }
1308   else
1309     /* The stub does not support the packet.  */
1310     return PACKET_UNKNOWN;
1311 }
1312
1313 static enum packet_result
1314 packet_ok (const char *buf, struct packet_config *config)
1315 {
1316   enum packet_result result;
1317
1318   if (config->detect != AUTO_BOOLEAN_TRUE
1319       && config->support == PACKET_DISABLE)
1320     internal_error (__FILE__, __LINE__,
1321                     _("packet_ok: attempt to use a disabled packet"));
1322
1323   result = packet_check_result (buf);
1324   switch (result)
1325     {
1326     case PACKET_OK:
1327     case PACKET_ERROR:
1328       /* The stub recognized the packet request.  */
1329       if (config->support == PACKET_SUPPORT_UNKNOWN)
1330         {
1331           if (remote_debug)
1332             fprintf_unfiltered (gdb_stdlog,
1333                                 "Packet %s (%s) is supported\n",
1334                                 config->name, config->title);
1335           config->support = PACKET_ENABLE;
1336         }
1337       break;
1338     case PACKET_UNKNOWN:
1339       /* The stub does not support the packet.  */
1340       if (config->detect == AUTO_BOOLEAN_AUTO
1341           && config->support == PACKET_ENABLE)
1342         {
1343           /* If the stub previously indicated that the packet was
1344              supported then there is a protocol error.  */
1345           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1346                  config->name, config->title);
1347         }
1348       else if (config->detect == AUTO_BOOLEAN_TRUE)
1349         {
1350           /* The user set it wrong.  */
1351           error (_("Enabled packet %s (%s) not recognized by stub"),
1352                  config->name, config->title);
1353         }
1354
1355       if (remote_debug)
1356         fprintf_unfiltered (gdb_stdlog,
1357                             "Packet %s (%s) is NOT supported\n",
1358                             config->name, config->title);
1359       config->support = PACKET_DISABLE;
1360       break;
1361     }
1362
1363   return result;
1364 }
1365
1366 enum {
1367   PACKET_vCont = 0,
1368   PACKET_X,
1369   PACKET_qSymbol,
1370   PACKET_P,
1371   PACKET_p,
1372   PACKET_Z0,
1373   PACKET_Z1,
1374   PACKET_Z2,
1375   PACKET_Z3,
1376   PACKET_Z4,
1377   PACKET_vFile_setfs,
1378   PACKET_vFile_open,
1379   PACKET_vFile_pread,
1380   PACKET_vFile_pwrite,
1381   PACKET_vFile_close,
1382   PACKET_vFile_unlink,
1383   PACKET_vFile_readlink,
1384   PACKET_vFile_fstat,
1385   PACKET_qXfer_auxv,
1386   PACKET_qXfer_features,
1387   PACKET_qXfer_exec_file,
1388   PACKET_qXfer_libraries,
1389   PACKET_qXfer_libraries_svr4,
1390   PACKET_qXfer_memory_map,
1391   PACKET_qXfer_spu_read,
1392   PACKET_qXfer_spu_write,
1393   PACKET_qXfer_osdata,
1394   PACKET_qXfer_threads,
1395   PACKET_qXfer_statictrace_read,
1396   PACKET_qXfer_traceframe_info,
1397   PACKET_qXfer_uib,
1398   PACKET_qGetTIBAddr,
1399   PACKET_qGetTLSAddr,
1400   PACKET_qSupported,
1401   PACKET_qTStatus,
1402   PACKET_QPassSignals,
1403   PACKET_QCatchSyscalls,
1404   PACKET_QProgramSignals,
1405   PACKET_qCRC,
1406   PACKET_qSearch_memory,
1407   PACKET_vAttach,
1408   PACKET_vRun,
1409   PACKET_QStartNoAckMode,
1410   PACKET_vKill,
1411   PACKET_qXfer_siginfo_read,
1412   PACKET_qXfer_siginfo_write,
1413   PACKET_qAttached,
1414
1415   /* Support for conditional tracepoints.  */
1416   PACKET_ConditionalTracepoints,
1417
1418   /* Support for target-side breakpoint conditions.  */
1419   PACKET_ConditionalBreakpoints,
1420
1421   /* Support for target-side breakpoint commands.  */
1422   PACKET_BreakpointCommands,
1423
1424   /* Support for fast tracepoints.  */
1425   PACKET_FastTracepoints,
1426
1427   /* Support for static tracepoints.  */
1428   PACKET_StaticTracepoints,
1429
1430   /* Support for installing tracepoints while a trace experiment is
1431      running.  */
1432   PACKET_InstallInTrace,
1433
1434   PACKET_bc,
1435   PACKET_bs,
1436   PACKET_TracepointSource,
1437   PACKET_QAllow,
1438   PACKET_qXfer_fdpic,
1439   PACKET_QDisableRandomization,
1440   PACKET_QAgent,
1441   PACKET_QTBuffer_size,
1442   PACKET_Qbtrace_off,
1443   PACKET_Qbtrace_bts,
1444   PACKET_Qbtrace_pt,
1445   PACKET_qXfer_btrace,
1446
1447   /* Support for the QNonStop packet.  */
1448   PACKET_QNonStop,
1449
1450   /* Support for the QThreadEvents packet.  */
1451   PACKET_QThreadEvents,
1452
1453   /* Support for multi-process extensions.  */
1454   PACKET_multiprocess_feature,
1455
1456   /* Support for enabling and disabling tracepoints while a trace
1457      experiment is running.  */
1458   PACKET_EnableDisableTracepoints_feature,
1459
1460   /* Support for collecting strings using the tracenz bytecode.  */
1461   PACKET_tracenz_feature,
1462
1463   /* Support for continuing to run a trace experiment while GDB is
1464      disconnected.  */
1465   PACKET_DisconnectedTracing_feature,
1466
1467   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1468   PACKET_augmented_libraries_svr4_read_feature,
1469
1470   /* Support for the qXfer:btrace-conf:read packet.  */
1471   PACKET_qXfer_btrace_conf,
1472
1473   /* Support for the Qbtrace-conf:bts:size packet.  */
1474   PACKET_Qbtrace_conf_bts_size,
1475
1476   /* Support for swbreak+ feature.  */
1477   PACKET_swbreak_feature,
1478
1479   /* Support for hwbreak+ feature.  */
1480   PACKET_hwbreak_feature,
1481
1482   /* Support for fork events.  */
1483   PACKET_fork_event_feature,
1484
1485   /* Support for vfork events.  */
1486   PACKET_vfork_event_feature,
1487
1488   /* Support for the Qbtrace-conf:pt:size packet.  */
1489   PACKET_Qbtrace_conf_pt_size,
1490
1491   /* Support for exec events.  */
1492   PACKET_exec_event_feature,
1493
1494   /* Support for query supported vCont actions.  */
1495   PACKET_vContSupported,
1496
1497   /* Support remote CTRL-C.  */
1498   PACKET_vCtrlC,
1499
1500   /* Support TARGET_WAITKIND_NO_RESUMED.  */
1501   PACKET_no_resumed,
1502
1503   PACKET_MAX
1504 };
1505
1506 static struct packet_config remote_protocol_packets[PACKET_MAX];
1507
1508 /* Returns the packet's corresponding "set remote foo-packet" command
1509    state.  See struct packet_config for more details.  */
1510
1511 static enum auto_boolean
1512 packet_set_cmd_state (int packet)
1513 {
1514   return remote_protocol_packets[packet].detect;
1515 }
1516
1517 /* Returns whether a given packet or feature is supported.  This takes
1518    into account the state of the corresponding "set remote foo-packet"
1519    command, which may be used to bypass auto-detection.  */
1520
1521 static enum packet_support
1522 packet_config_support (struct packet_config *config)
1523 {
1524   switch (config->detect)
1525     {
1526     case AUTO_BOOLEAN_TRUE:
1527       return PACKET_ENABLE;
1528     case AUTO_BOOLEAN_FALSE:
1529       return PACKET_DISABLE;
1530     case AUTO_BOOLEAN_AUTO:
1531       {
1532         struct remote_state *rs = get_remote_state ();
1533
1534         if (rs->unknown_v_replies_ok && config->name != NULL
1535             && config->name[0] == 'v')
1536           return PACKET_DISABLE;
1537       }
1538       return config->support;
1539     default:
1540       gdb_assert_not_reached (_("bad switch"));
1541     }
1542 }
1543
1544 /* Same as packet_config_support, but takes the packet's enum value as
1545    argument.  */
1546
1547 static enum packet_support
1548 packet_support (int packet)
1549 {
1550   struct packet_config *config = &remote_protocol_packets[packet];
1551
1552   return packet_config_support (config);
1553 }
1554
1555 static void
1556 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1557                                  struct cmd_list_element *c,
1558                                  const char *value)
1559 {
1560   struct packet_config *packet;
1561
1562   for (packet = remote_protocol_packets;
1563        packet < &remote_protocol_packets[PACKET_MAX];
1564        packet++)
1565     {
1566       if (&packet->detect == c->var)
1567         {
1568           show_packet_config_cmd (packet);
1569           return;
1570         }
1571     }
1572   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1573                   c->name);
1574 }
1575
1576 /* Should we try one of the 'Z' requests?  */
1577
1578 enum Z_packet_type
1579 {
1580   Z_PACKET_SOFTWARE_BP,
1581   Z_PACKET_HARDWARE_BP,
1582   Z_PACKET_WRITE_WP,
1583   Z_PACKET_READ_WP,
1584   Z_PACKET_ACCESS_WP,
1585   NR_Z_PACKET_TYPES
1586 };
1587
1588 /* For compatibility with older distributions.  Provide a ``set remote
1589    Z-packet ...'' command that updates all the Z packet types.  */
1590
1591 static enum auto_boolean remote_Z_packet_detect;
1592
1593 static void
1594 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1595                                   struct cmd_list_element *c)
1596 {
1597   int i;
1598
1599   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1600     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1601 }
1602
1603 static void
1604 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1605                                    struct cmd_list_element *c,
1606                                    const char *value)
1607 {
1608   int i;
1609
1610   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1611     {
1612       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1613     }
1614 }
1615
1616 /* Returns true if the multi-process extensions are in effect.  */
1617
1618 static int
1619 remote_multi_process_p (struct remote_state *rs)
1620 {
1621   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1622 }
1623
1624 /* Returns true if fork events are supported.  */
1625
1626 static int
1627 remote_fork_event_p (struct remote_state *rs)
1628 {
1629   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1630 }
1631
1632 /* Returns true if vfork events are supported.  */
1633
1634 static int
1635 remote_vfork_event_p (struct remote_state *rs)
1636 {
1637   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1638 }
1639
1640 /* Returns true if exec events are supported.  */
1641
1642 static int
1643 remote_exec_event_p (struct remote_state *rs)
1644 {
1645   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1646 }
1647
1648 /* Insert fork catchpoint target routine.  If fork events are enabled
1649    then return success, nothing more to do.  */
1650
1651 static int
1652 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1653 {
1654   struct remote_state *rs = get_remote_state ();
1655
1656   return !remote_fork_event_p (rs);
1657 }
1658
1659 /* Remove fork catchpoint target routine.  Nothing to do, just
1660    return success.  */
1661
1662 static int
1663 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1664 {
1665   return 0;
1666 }
1667
1668 /* Insert vfork catchpoint target routine.  If vfork events are enabled
1669    then return success, nothing more to do.  */
1670
1671 static int
1672 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1673 {
1674   struct remote_state *rs = get_remote_state ();
1675
1676   return !remote_vfork_event_p (rs);
1677 }
1678
1679 /* Remove vfork catchpoint target routine.  Nothing to do, just
1680    return success.  */
1681
1682 static int
1683 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1684 {
1685   return 0;
1686 }
1687
1688 /* Insert exec catchpoint target routine.  If exec events are
1689    enabled, just return success.  */
1690
1691 static int
1692 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1693 {
1694   struct remote_state *rs = get_remote_state ();
1695
1696   return !remote_exec_event_p (rs);
1697 }
1698
1699 /* Remove exec catchpoint target routine.  Nothing to do, just
1700    return success.  */
1701
1702 static int
1703 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1704 {
1705   return 0;
1706 }
1707
1708 /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
1709 static struct async_signal_handler *async_sigint_remote_twice_token;
1710 static struct async_signal_handler *async_sigint_remote_token;
1711
1712 \f
1713 /* Asynchronous signal handle registered as event loop source for
1714    when we have pending events ready to be passed to the core.  */
1715
1716 static struct async_event_handler *remote_async_inferior_event_token;
1717
1718 \f
1719
1720 static ptid_t magic_null_ptid;
1721 static ptid_t not_sent_ptid;
1722 static ptid_t any_thread_ptid;
1723
1724 /* Find out if the stub attached to PID (and hence GDB should offer to
1725    detach instead of killing it when bailing out).  */
1726
1727 static int
1728 remote_query_attached (int pid)
1729 {
1730   struct remote_state *rs = get_remote_state ();
1731   size_t size = get_remote_packet_size ();
1732
1733   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1734     return 0;
1735
1736   if (remote_multi_process_p (rs))
1737     xsnprintf (rs->buf, size, "qAttached:%x", pid);
1738   else
1739     xsnprintf (rs->buf, size, "qAttached");
1740
1741   putpkt (rs->buf);
1742   getpkt (&rs->buf, &rs->buf_size, 0);
1743
1744   switch (packet_ok (rs->buf,
1745                      &remote_protocol_packets[PACKET_qAttached]))
1746     {
1747     case PACKET_OK:
1748       if (strcmp (rs->buf, "1") == 0)
1749         return 1;
1750       break;
1751     case PACKET_ERROR:
1752       warning (_("Remote failure reply: %s"), rs->buf);
1753       break;
1754     case PACKET_UNKNOWN:
1755       break;
1756     }
1757
1758   return 0;
1759 }
1760
1761 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
1762    has been invented by GDB, instead of reported by the target.  Since
1763    we can be connected to a remote system before before knowing about
1764    any inferior, mark the target with execution when we find the first
1765    inferior.  If ATTACHED is 1, then we had just attached to this
1766    inferior.  If it is 0, then we just created this inferior.  If it
1767    is -1, then try querying the remote stub to find out if it had
1768    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
1769    attempt to open this inferior's executable as the main executable
1770    if no main executable is open already.  */
1771
1772 static struct inferior *
1773 remote_add_inferior (int fake_pid_p, int pid, int attached,
1774                      int try_open_exec)
1775 {
1776   struct inferior *inf;
1777
1778   /* Check whether this process we're learning about is to be
1779      considered attached, or if is to be considered to have been
1780      spawned by the stub.  */
1781   if (attached == -1)
1782     attached = remote_query_attached (pid);
1783
1784   if (gdbarch_has_global_solist (target_gdbarch ()))
1785     {
1786       /* If the target shares code across all inferiors, then every
1787          attach adds a new inferior.  */
1788       inf = add_inferior (pid);
1789
1790       /* ... and every inferior is bound to the same program space.
1791          However, each inferior may still have its own address
1792          space.  */
1793       inf->aspace = maybe_new_address_space ();
1794       inf->pspace = current_program_space;
1795     }
1796   else
1797     {
1798       /* In the traditional debugging scenario, there's a 1-1 match
1799          between program/address spaces.  We simply bind the inferior
1800          to the program space's address space.  */
1801       inf = current_inferior ();
1802       inferior_appeared (inf, pid);
1803     }
1804
1805   inf->attach_flag = attached;
1806   inf->fake_pid_p = fake_pid_p;
1807
1808   /* If no main executable is currently open then attempt to
1809      open the file that was executed to create this inferior.  */
1810   if (try_open_exec && get_exec_file (0) == NULL)
1811     exec_file_locate_attach (pid, 1);
1812
1813   return inf;
1814 }
1815
1816 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1817    according to RUNNING.  */
1818
1819 static void
1820 remote_add_thread (ptid_t ptid, int running, int executing)
1821 {
1822   struct remote_state *rs = get_remote_state ();
1823
1824   /* GDB historically didn't pull threads in the initial connection
1825      setup.  If the remote target doesn't even have a concept of
1826      threads (e.g., a bare-metal target), even if internally we
1827      consider that a single-threaded target, mentioning a new thread
1828      might be confusing to the user.  Be silent then, preserving the
1829      age old behavior.  */
1830   if (rs->starting_up)
1831     add_thread_silent (ptid);
1832   else
1833     add_thread (ptid);
1834
1835   set_executing (ptid, executing);
1836   set_running (ptid, running);
1837 }
1838
1839 /* Come here when we learn about a thread id from the remote target.
1840    It may be the first time we hear about such thread, so take the
1841    opportunity to add it to GDB's thread list.  In case this is the
1842    first time we're noticing its corresponding inferior, add it to
1843    GDB's inferior list as well.  EXECUTING indicates whether the
1844    thread is (internally) executing or stopped.  */
1845
1846 static void
1847 remote_notice_new_inferior (ptid_t currthread, int executing)
1848 {
1849   /* In non-stop mode, we assume new found threads are (externally)
1850      running until proven otherwise with a stop reply.  In all-stop,
1851      we can only get here if all threads are stopped.  */
1852   int running = target_is_non_stop_p () ? 1 : 0;
1853
1854   /* If this is a new thread, add it to GDB's thread list.
1855      If we leave it up to WFI to do this, bad things will happen.  */
1856
1857   if (in_thread_list (currthread) && is_exited (currthread))
1858     {
1859       /* We're seeing an event on a thread id we knew had exited.
1860          This has to be a new thread reusing the old id.  Add it.  */
1861       remote_add_thread (currthread, running, executing);
1862       return;
1863     }
1864
1865   if (!in_thread_list (currthread))
1866     {
1867       struct inferior *inf = NULL;
1868       int pid = ptid_get_pid (currthread);
1869
1870       if (ptid_is_pid (inferior_ptid)
1871           && pid == ptid_get_pid (inferior_ptid))
1872         {
1873           /* inferior_ptid has no thread member yet.  This can happen
1874              with the vAttach -> remote_wait,"TAAthread:" path if the
1875              stub doesn't support qC.  This is the first stop reported
1876              after an attach, so this is the main thread.  Update the
1877              ptid in the thread list.  */
1878           if (in_thread_list (pid_to_ptid (pid)))
1879             thread_change_ptid (inferior_ptid, currthread);
1880           else
1881             {
1882               remote_add_thread (currthread, running, executing);
1883               inferior_ptid = currthread;
1884             }
1885           return;
1886         }
1887
1888       if (ptid_equal (magic_null_ptid, inferior_ptid))
1889         {
1890           /* inferior_ptid is not set yet.  This can happen with the
1891              vRun -> remote_wait,"TAAthread:" path if the stub
1892              doesn't support qC.  This is the first stop reported
1893              after an attach, so this is the main thread.  Update the
1894              ptid in the thread list.  */
1895           thread_change_ptid (inferior_ptid, currthread);
1896           return;
1897         }
1898
1899       /* When connecting to a target remote, or to a target
1900          extended-remote which already was debugging an inferior, we
1901          may not know about it yet.  Add it before adding its child
1902          thread, so notifications are emitted in a sensible order.  */
1903       if (!in_inferior_list (ptid_get_pid (currthread)))
1904         {
1905           struct remote_state *rs = get_remote_state ();
1906           int fake_pid_p = !remote_multi_process_p (rs);
1907
1908           inf = remote_add_inferior (fake_pid_p,
1909                                      ptid_get_pid (currthread), -1, 1);
1910         }
1911
1912       /* This is really a new thread.  Add it.  */
1913       remote_add_thread (currthread, running, executing);
1914
1915       /* If we found a new inferior, let the common code do whatever
1916          it needs to with it (e.g., read shared libraries, insert
1917          breakpoints), unless we're just setting up an all-stop
1918          connection.  */
1919       if (inf != NULL)
1920         {
1921           struct remote_state *rs = get_remote_state ();
1922
1923           if (!rs->starting_up)
1924             notice_new_inferior (currthread, executing, 0);
1925         }
1926     }
1927 }
1928
1929 /* Return the private thread data, creating it if necessary.  */
1930
1931 static struct private_thread_info *
1932 demand_private_info (ptid_t ptid)
1933 {
1934   struct thread_info *info = find_thread_ptid (ptid);
1935
1936   gdb_assert (info);
1937
1938   if (!info->priv)
1939     {
1940       info->priv = XNEW (struct private_thread_info);
1941       info->private_dtor = free_private_thread_info;
1942       info->priv->core = -1;
1943       info->priv->extra = NULL;
1944       info->priv->name = NULL;
1945     }
1946
1947   return info->priv;
1948 }
1949
1950 /* Call this function as a result of
1951    1) A halt indication (T packet) containing a thread id
1952    2) A direct query of currthread
1953    3) Successful execution of set thread */
1954
1955 static void
1956 record_currthread (struct remote_state *rs, ptid_t currthread)
1957 {
1958   rs->general_thread = currthread;
1959 }
1960
1961 /* If 'QPassSignals' is supported, tell the remote stub what signals
1962    it can simply pass through to the inferior without reporting.  */
1963
1964 static void
1965 remote_pass_signals (struct target_ops *self,
1966                      int numsigs, unsigned char *pass_signals)
1967 {
1968   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1969     {
1970       char *pass_packet, *p;
1971       int count = 0, i;
1972       struct remote_state *rs = get_remote_state ();
1973
1974       gdb_assert (numsigs < 256);
1975       for (i = 0; i < numsigs; i++)
1976         {
1977           if (pass_signals[i])
1978             count++;
1979         }
1980       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1981       strcpy (pass_packet, "QPassSignals:");
1982       p = pass_packet + strlen (pass_packet);
1983       for (i = 0; i < numsigs; i++)
1984         {
1985           if (pass_signals[i])
1986             {
1987               if (i >= 16)
1988                 *p++ = tohex (i >> 4);
1989               *p++ = tohex (i & 15);
1990               if (count)
1991                 *p++ = ';';
1992               else
1993                 break;
1994               count--;
1995             }
1996         }
1997       *p = 0;
1998       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1999         {
2000           putpkt (pass_packet);
2001           getpkt (&rs->buf, &rs->buf_size, 0);
2002           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2003           if (rs->last_pass_packet)
2004             xfree (rs->last_pass_packet);
2005           rs->last_pass_packet = pass_packet;
2006         }
2007       else
2008         xfree (pass_packet);
2009     }
2010 }
2011
2012 /* If 'QCatchSyscalls' is supported, tell the remote stub
2013    to report syscalls to GDB.  */
2014
2015 static int
2016 remote_set_syscall_catchpoint (struct target_ops *self,
2017                                int pid, int needed, int any_count,
2018                                int table_size, int *table)
2019 {
2020   char *catch_packet;
2021   enum packet_result result;
2022   int n_sysno = 0;
2023
2024   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2025     {
2026       /* Not supported.  */
2027       return 1;
2028     }
2029
2030   if (needed && !any_count)
2031     {
2032       int i;
2033
2034       /* Count how many syscalls are to be caught (table[sysno] != 0).  */
2035       for (i = 0; i < table_size; i++)
2036         {
2037           if (table[i] != 0)
2038             n_sysno++;
2039         }
2040     }
2041
2042   if (remote_debug)
2043     {
2044       fprintf_unfiltered (gdb_stdlog,
2045                           "remote_set_syscall_catchpoint "
2046                           "pid %d needed %d any_count %d n_sysno %d\n",
2047                           pid, needed, any_count, n_sysno);
2048     }
2049
2050   if (needed)
2051     {
2052       /* Prepare a packet with the sysno list, assuming max 8+1
2053          characters for a sysno.  If the resulting packet size is too
2054          big, fallback on the non-selective packet.  */
2055       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2056
2057       catch_packet = (char *) xmalloc (maxpktsz);
2058       strcpy (catch_packet, "QCatchSyscalls:1");
2059       if (!any_count)
2060         {
2061           int i;
2062           char *p;
2063
2064           p = catch_packet;
2065           p += strlen (p);
2066
2067           /* Add in catch_packet each syscall to be caught (table[i] != 0).  */
2068           for (i = 0; i < table_size; i++)
2069             {
2070               if (table[i] != 0)
2071                 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2072             }
2073         }
2074       if (strlen (catch_packet) > get_remote_packet_size ())
2075         {
2076           /* catch_packet too big.  Fallback to less efficient
2077              non selective mode, with GDB doing the filtering.  */
2078           catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2079         }
2080     }
2081   else
2082     catch_packet = xstrdup ("QCatchSyscalls:0");
2083
2084   {
2085     struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2086     struct remote_state *rs = get_remote_state ();
2087
2088     putpkt (catch_packet);
2089     getpkt (&rs->buf, &rs->buf_size, 0);
2090     result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2091     do_cleanups (old_chain);
2092     if (result == PACKET_OK)
2093       return 0;
2094     else
2095       return -1;
2096   }
2097 }
2098
2099 /* If 'QProgramSignals' is supported, tell the remote stub what
2100    signals it should pass through to the inferior when detaching.  */
2101
2102 static void
2103 remote_program_signals (struct target_ops *self,
2104                         int numsigs, unsigned char *signals)
2105 {
2106   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2107     {
2108       char *packet, *p;
2109       int count = 0, i;
2110       struct remote_state *rs = get_remote_state ();
2111
2112       gdb_assert (numsigs < 256);
2113       for (i = 0; i < numsigs; i++)
2114         {
2115           if (signals[i])
2116             count++;
2117         }
2118       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2119       strcpy (packet, "QProgramSignals:");
2120       p = packet + strlen (packet);
2121       for (i = 0; i < numsigs; i++)
2122         {
2123           if (signal_pass_state (i))
2124             {
2125               if (i >= 16)
2126                 *p++ = tohex (i >> 4);
2127               *p++ = tohex (i & 15);
2128               if (count)
2129                 *p++ = ';';
2130               else
2131                 break;
2132               count--;
2133             }
2134         }
2135       *p = 0;
2136       if (!rs->last_program_signals_packet
2137           || strcmp (rs->last_program_signals_packet, packet) != 0)
2138         {
2139           putpkt (packet);
2140           getpkt (&rs->buf, &rs->buf_size, 0);
2141           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2142           xfree (rs->last_program_signals_packet);
2143           rs->last_program_signals_packet = packet;
2144         }
2145       else
2146         xfree (packet);
2147     }
2148 }
2149
2150 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2151    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2152    thread.  If GEN is set, set the general thread, if not, then set
2153    the step/continue thread.  */
2154 static void
2155 set_thread (struct ptid ptid, int gen)
2156 {
2157   struct remote_state *rs = get_remote_state ();
2158   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2159   char *buf = rs->buf;
2160   char *endbuf = rs->buf + get_remote_packet_size ();
2161
2162   if (ptid_equal (state, ptid))
2163     return;
2164
2165   *buf++ = 'H';
2166   *buf++ = gen ? 'g' : 'c';
2167   if (ptid_equal (ptid, magic_null_ptid))
2168     xsnprintf (buf, endbuf - buf, "0");
2169   else if (ptid_equal (ptid, any_thread_ptid))
2170     xsnprintf (buf, endbuf - buf, "0");
2171   else if (ptid_equal (ptid, minus_one_ptid))
2172     xsnprintf (buf, endbuf - buf, "-1");
2173   else
2174     write_ptid (buf, endbuf, ptid);
2175   putpkt (rs->buf);
2176   getpkt (&rs->buf, &rs->buf_size, 0);
2177   if (gen)
2178     rs->general_thread = ptid;
2179   else
2180     rs->continue_thread = ptid;
2181 }
2182
2183 static void
2184 set_general_thread (struct ptid ptid)
2185 {
2186   set_thread (ptid, 1);
2187 }
2188
2189 static void
2190 set_continue_thread (struct ptid ptid)
2191 {
2192   set_thread (ptid, 0);
2193 }
2194
2195 /* Change the remote current process.  Which thread within the process
2196    ends up selected isn't important, as long as it is the same process
2197    as what INFERIOR_PTID points to.
2198
2199    This comes from that fact that there is no explicit notion of
2200    "selected process" in the protocol.  The selected process for
2201    general operations is the process the selected general thread
2202    belongs to.  */
2203
2204 static void
2205 set_general_process (void)
2206 {
2207   struct remote_state *rs = get_remote_state ();
2208
2209   /* If the remote can't handle multiple processes, don't bother.  */
2210   if (!remote_multi_process_p (rs))
2211     return;
2212
2213   /* We only need to change the remote current thread if it's pointing
2214      at some other process.  */
2215   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2216     set_general_thread (inferior_ptid);
2217 }
2218
2219 \f
2220 /* Return nonzero if this is the main thread that we made up ourselves
2221    to model non-threaded targets as single-threaded.  */
2222
2223 static int
2224 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2225 {
2226   if (ptid_equal (ptid, magic_null_ptid))
2227     /* The main thread is always alive.  */
2228     return 1;
2229
2230   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2231     /* The main thread is always alive.  This can happen after a
2232        vAttach, if the remote side doesn't support
2233        multi-threading.  */
2234     return 1;
2235
2236   return 0;
2237 }
2238
2239 /* Return nonzero if the thread PTID is still alive on the remote
2240    system.  */
2241
2242 static int
2243 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2244 {
2245   struct remote_state *rs = get_remote_state ();
2246   char *p, *endp;
2247
2248   /* Check if this is a thread that we made up ourselves to model
2249      non-threaded targets as single-threaded.  */
2250   if (remote_thread_always_alive (ops, ptid))
2251     return 1;
2252
2253   p = rs->buf;
2254   endp = rs->buf + get_remote_packet_size ();
2255
2256   *p++ = 'T';
2257   write_ptid (p, endp, ptid);
2258
2259   putpkt (rs->buf);
2260   getpkt (&rs->buf, &rs->buf_size, 0);
2261   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2262 }
2263
2264 /* Return a pointer to a thread name if we know it and NULL otherwise.
2265    The thread_info object owns the memory for the name.  */
2266
2267 static const char *
2268 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2269 {
2270   if (info->priv != NULL)
2271     return info->priv->name;
2272
2273   return NULL;
2274 }
2275
2276 /* About these extended threadlist and threadinfo packets.  They are
2277    variable length packets but, the fields within them are often fixed
2278    length.  They are redundent enough to send over UDP as is the
2279    remote protocol in general.  There is a matching unit test module
2280    in libstub.  */
2281
2282 /* WARNING: This threadref data structure comes from the remote O.S.,
2283    libstub protocol encoding, and remote.c.  It is not particularly
2284    changable.  */
2285
2286 /* Right now, the internal structure is int. We want it to be bigger.
2287    Plan to fix this.  */
2288
2289 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2290
2291 /* gdb_ext_thread_info is an internal GDB data structure which is
2292    equivalent to the reply of the remote threadinfo packet.  */
2293
2294 struct gdb_ext_thread_info
2295   {
2296     threadref threadid;         /* External form of thread reference.  */
2297     int active;                 /* Has state interesting to GDB?
2298                                    regs, stack.  */
2299     char display[256];          /* Brief state display, name,
2300                                    blocked/suspended.  */
2301     char shortname[32];         /* To be used to name threads.  */
2302     char more_display[256];     /* Long info, statistics, queue depth,
2303                                    whatever.  */
2304   };
2305
2306 /* The volume of remote transfers can be limited by submitting
2307    a mask containing bits specifying the desired information.
2308    Use a union of these values as the 'selection' parameter to
2309    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2310
2311 #define TAG_THREADID 1
2312 #define TAG_EXISTS 2
2313 #define TAG_DISPLAY 4
2314 #define TAG_THREADNAME 8
2315 #define TAG_MOREDISPLAY 16
2316
2317 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2318
2319 static char *unpack_nibble (char *buf, int *val);
2320
2321 static char *unpack_byte (char *buf, int *value);
2322
2323 static char *pack_int (char *buf, int value);
2324
2325 static char *unpack_int (char *buf, int *value);
2326
2327 static char *unpack_string (char *src, char *dest, int length);
2328
2329 static char *pack_threadid (char *pkt, threadref *id);
2330
2331 static char *unpack_threadid (char *inbuf, threadref *id);
2332
2333 void int_to_threadref (threadref *id, int value);
2334
2335 static int threadref_to_int (threadref *ref);
2336
2337 static void copy_threadref (threadref *dest, threadref *src);
2338
2339 static int threadmatch (threadref *dest, threadref *src);
2340
2341 static char *pack_threadinfo_request (char *pkt, int mode,
2342                                       threadref *id);
2343
2344 static int remote_unpack_thread_info_response (char *pkt,
2345                                                threadref *expectedref,
2346                                                struct gdb_ext_thread_info
2347                                                *info);
2348
2349
2350 static int remote_get_threadinfo (threadref *threadid,
2351                                   int fieldset, /*TAG mask */
2352                                   struct gdb_ext_thread_info *info);
2353
2354 static char *pack_threadlist_request (char *pkt, int startflag,
2355                                       int threadcount,
2356                                       threadref *nextthread);
2357
2358 static int parse_threadlist_response (char *pkt,
2359                                       int result_limit,
2360                                       threadref *original_echo,
2361                                       threadref *resultlist,
2362                                       int *doneflag);
2363
2364 static int remote_get_threadlist (int startflag,
2365                                   threadref *nextthread,
2366                                   int result_limit,
2367                                   int *done,
2368                                   int *result_count,
2369                                   threadref *threadlist);
2370
2371 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2372
2373 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2374                                        void *context, int looplimit);
2375
2376 static int remote_newthread_step (threadref *ref, void *context);
2377
2378
2379 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2380    buffer we're allowed to write to.  Returns
2381    BUF+CHARACTERS_WRITTEN.  */
2382
2383 static char *
2384 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2385 {
2386   int pid, tid;
2387   struct remote_state *rs = get_remote_state ();
2388
2389   if (remote_multi_process_p (rs))
2390     {
2391       pid = ptid_get_pid (ptid);
2392       if (pid < 0)
2393         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2394       else
2395         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2396     }
2397   tid = ptid_get_lwp (ptid);
2398   if (tid < 0)
2399     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2400   else
2401     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2402
2403   return buf;
2404 }
2405
2406 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
2407    passed the last parsed char.  Returns null_ptid on error.  */
2408
2409 static ptid_t
2410 read_ptid (char *buf, char **obuf)
2411 {
2412   char *p = buf;
2413   char *pp;
2414   ULONGEST pid = 0, tid = 0;
2415
2416   if (*p == 'p')
2417     {
2418       /* Multi-process ptid.  */
2419       pp = unpack_varlen_hex (p + 1, &pid);
2420       if (*pp != '.')
2421         error (_("invalid remote ptid: %s"), p);
2422
2423       p = pp;
2424       pp = unpack_varlen_hex (p + 1, &tid);
2425       if (obuf)
2426         *obuf = pp;
2427       return ptid_build (pid, tid, 0);
2428     }
2429
2430   /* No multi-process.  Just a tid.  */
2431   pp = unpack_varlen_hex (p, &tid);
2432
2433   /* Return null_ptid when no thread id is found.  */
2434   if (p == pp)
2435     {
2436       if (obuf)
2437         *obuf = pp;
2438       return null_ptid;
2439     }
2440
2441   /* Since the stub is not sending a process id, then default to
2442      what's in inferior_ptid, unless it's null at this point.  If so,
2443      then since there's no way to know the pid of the reported
2444      threads, use the magic number.  */
2445   if (ptid_equal (inferior_ptid, null_ptid))
2446     pid = ptid_get_pid (magic_null_ptid);
2447   else
2448     pid = ptid_get_pid (inferior_ptid);
2449
2450   if (obuf)
2451     *obuf = pp;
2452   return ptid_build (pid, tid, 0);
2453 }
2454
2455 static int
2456 stubhex (int ch)
2457 {
2458   if (ch >= 'a' && ch <= 'f')
2459     return ch - 'a' + 10;
2460   if (ch >= '0' && ch <= '9')
2461     return ch - '0';
2462   if (ch >= 'A' && ch <= 'F')
2463     return ch - 'A' + 10;
2464   return -1;
2465 }
2466
2467 static int
2468 stub_unpack_int (char *buff, int fieldlength)
2469 {
2470   int nibble;
2471   int retval = 0;
2472
2473   while (fieldlength)
2474     {
2475       nibble = stubhex (*buff++);
2476       retval |= nibble;
2477       fieldlength--;
2478       if (fieldlength)
2479         retval = retval << 4;
2480     }
2481   return retval;
2482 }
2483
2484 static char *
2485 unpack_nibble (char *buf, int *val)
2486 {
2487   *val = fromhex (*buf++);
2488   return buf;
2489 }
2490
2491 static char *
2492 unpack_byte (char *buf, int *value)
2493 {
2494   *value = stub_unpack_int (buf, 2);
2495   return buf + 2;
2496 }
2497
2498 static char *
2499 pack_int (char *buf, int value)
2500 {
2501   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2502   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2503   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2504   buf = pack_hex_byte (buf, (value & 0xff));
2505   return buf;
2506 }
2507
2508 static char *
2509 unpack_int (char *buf, int *value)
2510 {
2511   *value = stub_unpack_int (buf, 8);
2512   return buf + 8;
2513 }
2514
2515 #if 0                   /* Currently unused, uncomment when needed.  */
2516 static char *pack_string (char *pkt, char *string);
2517
2518 static char *
2519 pack_string (char *pkt, char *string)
2520 {
2521   char ch;
2522   int len;
2523
2524   len = strlen (string);
2525   if (len > 200)
2526     len = 200;          /* Bigger than most GDB packets, junk???  */
2527   pkt = pack_hex_byte (pkt, len);
2528   while (len-- > 0)
2529     {
2530       ch = *string++;
2531       if ((ch == '\0') || (ch == '#'))
2532         ch = '*';               /* Protect encapsulation.  */
2533       *pkt++ = ch;
2534     }
2535   return pkt;
2536 }
2537 #endif /* 0 (unused) */
2538
2539 static char *
2540 unpack_string (char *src, char *dest, int length)
2541 {
2542   while (length--)
2543     *dest++ = *src++;
2544   *dest = '\0';
2545   return src;
2546 }
2547
2548 static char *
2549 pack_threadid (char *pkt, threadref *id)
2550 {
2551   char *limit;
2552   unsigned char *altid;
2553
2554   altid = (unsigned char *) id;
2555   limit = pkt + BUF_THREAD_ID_SIZE;
2556   while (pkt < limit)
2557     pkt = pack_hex_byte (pkt, *altid++);
2558   return pkt;
2559 }
2560
2561
2562 static char *
2563 unpack_threadid (char *inbuf, threadref *id)
2564 {
2565   char *altref;
2566   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2567   int x, y;
2568
2569   altref = (char *) id;
2570
2571   while (inbuf < limit)
2572     {
2573       x = stubhex (*inbuf++);
2574       y = stubhex (*inbuf++);
2575       *altref++ = (x << 4) | y;
2576     }
2577   return inbuf;
2578 }
2579
2580 /* Externally, threadrefs are 64 bits but internally, they are still
2581    ints.  This is due to a mismatch of specifications.  We would like
2582    to use 64bit thread references internally.  This is an adapter
2583    function.  */
2584
2585 void
2586 int_to_threadref (threadref *id, int value)
2587 {
2588   unsigned char *scan;
2589
2590   scan = (unsigned char *) id;
2591   {
2592     int i = 4;
2593     while (i--)
2594       *scan++ = 0;
2595   }
2596   *scan++ = (value >> 24) & 0xff;
2597   *scan++ = (value >> 16) & 0xff;
2598   *scan++ = (value >> 8) & 0xff;
2599   *scan++ = (value & 0xff);
2600 }
2601
2602 static int
2603 threadref_to_int (threadref *ref)
2604 {
2605   int i, value = 0;
2606   unsigned char *scan;
2607
2608   scan = *ref;
2609   scan += 4;
2610   i = 4;
2611   while (i-- > 0)
2612     value = (value << 8) | ((*scan++) & 0xff);
2613   return value;
2614 }
2615
2616 static void
2617 copy_threadref (threadref *dest, threadref *src)
2618 {
2619   int i;
2620   unsigned char *csrc, *cdest;
2621
2622   csrc = (unsigned char *) src;
2623   cdest = (unsigned char *) dest;
2624   i = 8;
2625   while (i--)
2626     *cdest++ = *csrc++;
2627 }
2628
2629 static int
2630 threadmatch (threadref *dest, threadref *src)
2631 {
2632   /* Things are broken right now, so just assume we got a match.  */
2633 #if 0
2634   unsigned char *srcp, *destp;
2635   int i, result;
2636   srcp = (char *) src;
2637   destp = (char *) dest;
2638
2639   result = 1;
2640   while (i-- > 0)
2641     result &= (*srcp++ == *destp++) ? 1 : 0;
2642   return result;
2643 #endif
2644   return 1;
2645 }
2646
2647 /*
2648    threadid:1,        # always request threadid
2649    context_exists:2,
2650    display:4,
2651    unique_name:8,
2652    more_display:16
2653  */
2654
2655 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2656
2657 static char *
2658 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2659 {
2660   *pkt++ = 'q';                         /* Info Query */
2661   *pkt++ = 'P';                         /* process or thread info */
2662   pkt = pack_int (pkt, mode);           /* mode */
2663   pkt = pack_threadid (pkt, id);        /* threadid */
2664   *pkt = '\0';                          /* terminate */
2665   return pkt;
2666 }
2667
2668 /* These values tag the fields in a thread info response packet.  */
2669 /* Tagging the fields allows us to request specific fields and to
2670    add more fields as time goes by.  */
2671
2672 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2673 #define TAG_EXISTS 2            /* Is this process defined enough to
2674                                    fetch registers and its stack?  */
2675 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2676 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2677 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2678                                    the process.  */
2679
2680 static int
2681 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2682                                     struct gdb_ext_thread_info *info)
2683 {
2684   struct remote_state *rs = get_remote_state ();
2685   int mask, length;
2686   int tag;
2687   threadref ref;
2688   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2689   int retval = 1;
2690
2691   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2692   info->active = 0;
2693   info->display[0] = '\0';
2694   info->shortname[0] = '\0';
2695   info->more_display[0] = '\0';
2696
2697   /* Assume the characters indicating the packet type have been
2698      stripped.  */
2699   pkt = unpack_int (pkt, &mask);        /* arg mask */
2700   pkt = unpack_threadid (pkt, &ref);
2701
2702   if (mask == 0)
2703     warning (_("Incomplete response to threadinfo request."));
2704   if (!threadmatch (&ref, expectedref))
2705     {                   /* This is an answer to a different request.  */
2706       warning (_("ERROR RMT Thread info mismatch."));
2707       return 0;
2708     }
2709   copy_threadref (&info->threadid, &ref);
2710
2711   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
2712
2713   /* Packets are terminated with nulls.  */
2714   while ((pkt < limit) && mask && *pkt)
2715     {
2716       pkt = unpack_int (pkt, &tag);     /* tag */
2717       pkt = unpack_byte (pkt, &length); /* length */
2718       if (!(tag & mask))                /* Tags out of synch with mask.  */
2719         {
2720           warning (_("ERROR RMT: threadinfo tag mismatch."));
2721           retval = 0;
2722           break;
2723         }
2724       if (tag == TAG_THREADID)
2725         {
2726           if (length != 16)
2727             {
2728               warning (_("ERROR RMT: length of threadid is not 16."));
2729               retval = 0;
2730               break;
2731             }
2732           pkt = unpack_threadid (pkt, &ref);
2733           mask = mask & ~TAG_THREADID;
2734           continue;
2735         }
2736       if (tag == TAG_EXISTS)
2737         {
2738           info->active = stub_unpack_int (pkt, length);
2739           pkt += length;
2740           mask = mask & ~(TAG_EXISTS);
2741           if (length > 8)
2742             {
2743               warning (_("ERROR RMT: 'exists' length too long."));
2744               retval = 0;
2745               break;
2746             }
2747           continue;
2748         }
2749       if (tag == TAG_THREADNAME)
2750         {
2751           pkt = unpack_string (pkt, &info->shortname[0], length);
2752           mask = mask & ~TAG_THREADNAME;
2753           continue;
2754         }
2755       if (tag == TAG_DISPLAY)
2756         {
2757           pkt = unpack_string (pkt, &info->display[0], length);
2758           mask = mask & ~TAG_DISPLAY;
2759           continue;
2760         }
2761       if (tag == TAG_MOREDISPLAY)
2762         {
2763           pkt = unpack_string (pkt, &info->more_display[0], length);
2764           mask = mask & ~TAG_MOREDISPLAY;
2765           continue;
2766         }
2767       warning (_("ERROR RMT: unknown thread info tag."));
2768       break;                    /* Not a tag we know about.  */
2769     }
2770   return retval;
2771 }
2772
2773 static int
2774 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2775                        struct gdb_ext_thread_info *info)
2776 {
2777   struct remote_state *rs = get_remote_state ();
2778   int result;
2779
2780   pack_threadinfo_request (rs->buf, fieldset, threadid);
2781   putpkt (rs->buf);
2782   getpkt (&rs->buf, &rs->buf_size, 0);
2783
2784   if (rs->buf[0] == '\0')
2785     return 0;
2786
2787   result = remote_unpack_thread_info_response (rs->buf + 2,
2788                                                threadid, info);
2789   return result;
2790 }
2791
2792 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2793
2794 static char *
2795 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2796                          threadref *nextthread)
2797 {
2798   *pkt++ = 'q';                 /* info query packet */
2799   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2800   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2801   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2802   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2803   *pkt = '\0';
2804   return pkt;
2805 }
2806
2807 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2808
2809 static int
2810 parse_threadlist_response (char *pkt, int result_limit,
2811                            threadref *original_echo, threadref *resultlist,
2812                            int *doneflag)
2813 {
2814   struct remote_state *rs = get_remote_state ();
2815   char *limit;
2816   int count, resultcount, done;
2817
2818   resultcount = 0;
2819   /* Assume the 'q' and 'M chars have been stripped.  */
2820   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2821   /* done parse past here */
2822   pkt = unpack_byte (pkt, &count);      /* count field */
2823   pkt = unpack_nibble (pkt, &done);
2824   /* The first threadid is the argument threadid.  */
2825   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2826   while ((count-- > 0) && (pkt < limit))
2827     {
2828       pkt = unpack_threadid (pkt, resultlist++);
2829       if (resultcount++ >= result_limit)
2830         break;
2831     }
2832   if (doneflag)
2833     *doneflag = done;
2834   return resultcount;
2835 }
2836
2837 /* Fetch the next batch of threads from the remote.  Returns -1 if the
2838    qL packet is not supported, 0 on error and 1 on success.  */
2839
2840 static int
2841 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2842                        int *done, int *result_count, threadref *threadlist)
2843 {
2844   struct remote_state *rs = get_remote_state ();
2845   int result = 1;
2846
2847   /* Trancate result limit to be smaller than the packet size.  */
2848   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2849       >= get_remote_packet_size ())
2850     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2851
2852   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2853   putpkt (rs->buf);
2854   getpkt (&rs->buf, &rs->buf_size, 0);
2855   if (*rs->buf == '\0')
2856     {
2857       /* Packet not supported.  */
2858       return -1;
2859     }
2860
2861   *result_count =
2862     parse_threadlist_response (rs->buf + 2, result_limit,
2863                                &rs->echo_nextthread, threadlist, done);
2864
2865   if (!threadmatch (&rs->echo_nextthread, nextthread))
2866     {
2867       /* FIXME: This is a good reason to drop the packet.  */
2868       /* Possably, there is a duplicate response.  */
2869       /* Possabilities :
2870          retransmit immediatly - race conditions
2871          retransmit after timeout - yes
2872          exit
2873          wait for packet, then exit
2874        */
2875       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2876       return 0;                 /* I choose simply exiting.  */
2877     }
2878   if (*result_count <= 0)
2879     {
2880       if (*done != 1)
2881         {
2882           warning (_("RMT ERROR : failed to get remote thread list."));
2883           result = 0;
2884         }
2885       return result;            /* break; */
2886     }
2887   if (*result_count > result_limit)
2888     {
2889       *result_count = 0;
2890       warning (_("RMT ERROR: threadlist response longer than requested."));
2891       return 0;
2892     }
2893   return result;
2894 }
2895
2896 /* Fetch the list of remote threads, with the qL packet, and call
2897    STEPFUNCTION for each thread found.  Stops iterating and returns 1
2898    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
2899    STEPFUNCTION returns false.  If the packet is not supported,
2900    returns -1.  */
2901
2902 static int
2903 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2904                             int looplimit)
2905 {
2906   struct remote_state *rs = get_remote_state ();
2907   int done, i, result_count;
2908   int startflag = 1;
2909   int result = 1;
2910   int loopcount = 0;
2911
2912   done = 0;
2913   while (!done)
2914     {
2915       if (loopcount++ > looplimit)
2916         {
2917           result = 0;
2918           warning (_("Remote fetch threadlist -infinite loop-."));
2919           break;
2920         }
2921       result = remote_get_threadlist (startflag, &rs->nextthread,
2922                                       MAXTHREADLISTRESULTS,
2923                                       &done, &result_count,
2924                                       rs->resultthreadlist);
2925       if (result <= 0)
2926         break;
2927       /* Clear for later iterations.  */
2928       startflag = 0;
2929       /* Setup to resume next batch of thread references, set nextthread.  */
2930       if (result_count >= 1)
2931         copy_threadref (&rs->nextthread,
2932                         &rs->resultthreadlist[result_count - 1]);
2933       i = 0;
2934       while (result_count--)
2935         {
2936           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2937             {
2938               result = 0;
2939               break;
2940             }
2941         }
2942     }
2943   return result;
2944 }
2945
2946 /* A thread found on the remote target.  */
2947
2948 typedef struct thread_item
2949 {
2950   /* The thread's PTID.  */
2951   ptid_t ptid;
2952
2953   /* The thread's extra info.  May be NULL.  */
2954   char *extra;
2955
2956   /* The thread's name.  May be NULL.  */
2957   char *name;
2958
2959   /* The core the thread was running on.  -1 if not known.  */
2960   int core;
2961 } thread_item_t;
2962 DEF_VEC_O(thread_item_t);
2963
2964 /* Context passed around to the various methods listing remote
2965    threads.  As new threads are found, they're added to the ITEMS
2966    vector.  */
2967
2968 struct threads_listing_context
2969 {
2970   /* The threads found on the remote target.  */
2971   VEC (thread_item_t) *items;
2972 };
2973
2974 /* Discard the contents of the constructed thread listing context.  */
2975
2976 static void
2977 clear_threads_listing_context (void *p)
2978 {
2979   struct threads_listing_context *context
2980     = (struct threads_listing_context *) p;
2981   int i;
2982   struct thread_item *item;
2983
2984   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2985     {
2986       xfree (item->extra);
2987       xfree (item->name);
2988     }
2989
2990   VEC_free (thread_item_t, context->items);
2991 }
2992
2993 /* Remove the thread specified as the related_pid field of WS
2994    from the CONTEXT list.  */
2995
2996 static void
2997 threads_listing_context_remove (struct target_waitstatus *ws,
2998                                 struct threads_listing_context *context)
2999 {
3000   struct thread_item *item;
3001   int i;
3002   ptid_t child_ptid = ws->value.related_pid;
3003
3004   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3005     {
3006       if (ptid_equal (item->ptid, child_ptid))
3007         {
3008           VEC_ordered_remove (thread_item_t, context->items, i);
3009           break;
3010         }
3011     }
3012 }
3013
3014 static int
3015 remote_newthread_step (threadref *ref, void *data)
3016 {
3017   struct threads_listing_context *context
3018     = (struct threads_listing_context *) data;
3019   struct thread_item item;
3020   int pid = ptid_get_pid (inferior_ptid);
3021
3022   item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3023   item.core = -1;
3024   item.name = NULL;
3025   item.extra = NULL;
3026
3027   VEC_safe_push (thread_item_t, context->items, &item);
3028
3029   return 1;                     /* continue iterator */
3030 }
3031
3032 #define CRAZY_MAX_THREADS 1000
3033
3034 static ptid_t
3035 remote_current_thread (ptid_t oldpid)
3036 {
3037   struct remote_state *rs = get_remote_state ();
3038
3039   putpkt ("qC");
3040   getpkt (&rs->buf, &rs->buf_size, 0);
3041   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3042     {
3043       char *obuf;
3044       ptid_t result;
3045
3046       result = read_ptid (&rs->buf[2], &obuf);
3047       if (*obuf != '\0' && remote_debug)
3048         fprintf_unfiltered (gdb_stdlog,
3049                             "warning: garbage in qC reply\n");
3050
3051       return result;
3052     }
3053   else
3054     return oldpid;
3055 }
3056
3057 /* List remote threads using the deprecated qL packet.  */
3058
3059 static int
3060 remote_get_threads_with_ql (struct target_ops *ops,
3061                             struct threads_listing_context *context)
3062 {
3063   if (remote_threadlist_iterator (remote_newthread_step, context,
3064                                   CRAZY_MAX_THREADS) >= 0)
3065     return 1;
3066
3067   return 0;
3068 }
3069
3070 #if defined(HAVE_LIBEXPAT)
3071
3072 static void
3073 start_thread (struct gdb_xml_parser *parser,
3074               const struct gdb_xml_element *element,
3075               void *user_data, VEC(gdb_xml_value_s) *attributes)
3076 {
3077   struct threads_listing_context *data
3078     = (struct threads_listing_context *) user_data;
3079
3080   struct thread_item item;
3081   char *id;
3082   struct gdb_xml_value *attr;
3083
3084   id = (char *) xml_find_attribute (attributes, "id")->value;
3085   item.ptid = read_ptid (id, NULL);
3086
3087   attr = xml_find_attribute (attributes, "core");
3088   if (attr != NULL)
3089     item.core = *(ULONGEST *) attr->value;
3090   else
3091     item.core = -1;
3092
3093   attr = xml_find_attribute (attributes, "name");
3094   item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3095
3096   item.extra = 0;
3097
3098   VEC_safe_push (thread_item_t, data->items, &item);
3099 }
3100
3101 static void
3102 end_thread (struct gdb_xml_parser *parser,
3103             const struct gdb_xml_element *element,
3104             void *user_data, const char *body_text)
3105 {
3106   struct threads_listing_context *data
3107     = (struct threads_listing_context *) user_data;
3108
3109   if (body_text && *body_text)
3110     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3111 }
3112
3113 const struct gdb_xml_attribute thread_attributes[] = {
3114   { "id", GDB_XML_AF_NONE, NULL, NULL },
3115   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3116   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3117   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3118 };
3119
3120 const struct gdb_xml_element thread_children[] = {
3121   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3122 };
3123
3124 const struct gdb_xml_element threads_children[] = {
3125   { "thread", thread_attributes, thread_children,
3126     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3127     start_thread, end_thread },
3128   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3129 };
3130
3131 const struct gdb_xml_element threads_elements[] = {
3132   { "threads", NULL, threads_children,
3133     GDB_XML_EF_NONE, NULL, NULL },
3134   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3135 };
3136
3137 #endif
3138
3139 /* List remote threads using qXfer:threads:read.  */
3140
3141 static int
3142 remote_get_threads_with_qxfer (struct target_ops *ops,
3143                                struct threads_listing_context *context)
3144 {
3145 #if defined(HAVE_LIBEXPAT)
3146   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3147     {
3148       char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3149       struct cleanup *back_to = make_cleanup (xfree, xml);
3150
3151       if (xml != NULL && *xml != '\0')
3152         {
3153           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3154                                threads_elements, xml, context);
3155         }
3156
3157       do_cleanups (back_to);
3158       return 1;
3159     }
3160 #endif
3161
3162   return 0;
3163 }
3164
3165 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3166
3167 static int
3168 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3169                                      struct threads_listing_context *context)
3170 {
3171   struct remote_state *rs = get_remote_state ();
3172
3173   if (rs->use_threadinfo_query)
3174     {
3175       char *bufp;
3176
3177       putpkt ("qfThreadInfo");
3178       getpkt (&rs->buf, &rs->buf_size, 0);
3179       bufp = rs->buf;
3180       if (bufp[0] != '\0')              /* q packet recognized */
3181         {
3182           while (*bufp++ == 'm')        /* reply contains one or more TID */
3183             {
3184               do
3185                 {
3186                   struct thread_item item;
3187
3188                   item.ptid = read_ptid (bufp, &bufp);
3189                   item.core = -1;
3190                   item.name = NULL;
3191                   item.extra = NULL;
3192
3193                   VEC_safe_push (thread_item_t, context->items, &item);
3194                 }
3195               while (*bufp++ == ',');   /* comma-separated list */
3196               putpkt ("qsThreadInfo");
3197               getpkt (&rs->buf, &rs->buf_size, 0);
3198               bufp = rs->buf;
3199             }
3200           return 1;
3201         }
3202       else
3203         {
3204           /* Packet not recognized.  */
3205           rs->use_threadinfo_query = 0;
3206         }
3207     }
3208
3209   return 0;
3210 }
3211
3212 /* Implement the to_update_thread_list function for the remote
3213    targets.  */
3214
3215 static void
3216 remote_update_thread_list (struct target_ops *ops)
3217 {
3218   struct threads_listing_context context;
3219   struct cleanup *old_chain;
3220   int got_list = 0;
3221
3222   context.items = NULL;
3223   old_chain = make_cleanup (clear_threads_listing_context, &context);
3224
3225   /* We have a few different mechanisms to fetch the thread list.  Try
3226      them all, starting with the most preferred one first, falling
3227      back to older methods.  */
3228   if (remote_get_threads_with_qxfer (ops, &context)
3229       || remote_get_threads_with_qthreadinfo (ops, &context)
3230       || remote_get_threads_with_ql (ops, &context))
3231     {
3232       int i;
3233       struct thread_item *item;
3234       struct thread_info *tp, *tmp;
3235
3236       got_list = 1;
3237
3238       if (VEC_empty (thread_item_t, context.items)
3239           && remote_thread_always_alive (ops, inferior_ptid))
3240         {
3241           /* Some targets don't really support threads, but still
3242              reply an (empty) thread list in response to the thread
3243              listing packets, instead of replying "packet not
3244              supported".  Exit early so we don't delete the main
3245              thread.  */
3246           do_cleanups (old_chain);
3247           return;
3248         }
3249
3250       /* CONTEXT now holds the current thread list on the remote
3251          target end.  Delete GDB-side threads no longer found on the
3252          target.  */
3253       ALL_THREADS_SAFE (tp, tmp)
3254         {
3255           for (i = 0;
3256                VEC_iterate (thread_item_t, context.items, i, item);
3257                ++i)
3258             {
3259               if (ptid_equal (item->ptid, tp->ptid))
3260                 break;
3261             }
3262
3263           if (i == VEC_length (thread_item_t, context.items))
3264             {
3265               /* Not found.  */
3266               delete_thread (tp->ptid);
3267             }
3268         }
3269
3270       /* Remove any unreported fork child threads from CONTEXT so
3271          that we don't interfere with follow fork, which is where
3272          creation of such threads is handled.  */
3273       remove_new_fork_children (&context);
3274
3275       /* And now add threads we don't know about yet to our list.  */
3276       for (i = 0;
3277            VEC_iterate (thread_item_t, context.items, i, item);
3278            ++i)
3279         {
3280           if (!ptid_equal (item->ptid, null_ptid))
3281             {
3282               struct private_thread_info *info;
3283               /* In non-stop mode, we assume new found threads are
3284                  executing until proven otherwise with a stop reply.
3285                  In all-stop, we can only get here if all threads are
3286                  stopped.  */
3287               int executing = target_is_non_stop_p () ? 1 : 0;
3288
3289               remote_notice_new_inferior (item->ptid, executing);
3290
3291               info = demand_private_info (item->ptid);
3292               info->core = item->core;
3293               info->extra = item->extra;
3294               item->extra = NULL;
3295               info->name = item->name;
3296               item->name = NULL;
3297             }
3298         }
3299     }
3300
3301   if (!got_list)
3302     {
3303       /* If no thread listing method is supported, then query whether
3304          each known thread is alive, one by one, with the T packet.
3305          If the target doesn't support threads at all, then this is a
3306          no-op.  See remote_thread_alive.  */
3307       prune_threads ();
3308     }
3309
3310   do_cleanups (old_chain);
3311 }
3312
3313 /*
3314  * Collect a descriptive string about the given thread.
3315  * The target may say anything it wants to about the thread
3316  * (typically info about its blocked / runnable state, name, etc.).
3317  * This string will appear in the info threads display.
3318  *
3319  * Optional: targets are not required to implement this function.
3320  */
3321
3322 static char *
3323 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3324 {
3325   struct remote_state *rs = get_remote_state ();
3326   int result;
3327   int set;
3328   threadref id;
3329   struct gdb_ext_thread_info threadinfo;
3330   static char display_buf[100]; /* arbitrary...  */
3331   int n = 0;                    /* position in display_buf */
3332
3333   if (rs->remote_desc == 0)             /* paranoia */
3334     internal_error (__FILE__, __LINE__,
3335                     _("remote_threads_extra_info"));
3336
3337   if (ptid_equal (tp->ptid, magic_null_ptid)
3338       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3339     /* This is the main thread which was added by GDB.  The remote
3340        server doesn't know about it.  */
3341     return NULL;
3342
3343   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3344     {
3345       struct thread_info *info = find_thread_ptid (tp->ptid);
3346
3347       if (info && info->priv)
3348         return info->priv->extra;
3349       else
3350         return NULL;
3351     }
3352
3353   if (rs->use_threadextra_query)
3354     {
3355       char *b = rs->buf;
3356       char *endb = rs->buf + get_remote_packet_size ();
3357
3358       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3359       b += strlen (b);
3360       write_ptid (b, endb, tp->ptid);
3361
3362       putpkt (rs->buf);
3363       getpkt (&rs->buf, &rs->buf_size, 0);
3364       if (rs->buf[0] != 0)
3365         {
3366           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3367           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3368           display_buf [result] = '\0';
3369           return display_buf;
3370         }
3371     }
3372
3373   /* If the above query fails, fall back to the old method.  */
3374   rs->use_threadextra_query = 0;
3375   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3376     | TAG_MOREDISPLAY | TAG_DISPLAY;
3377   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3378   if (remote_get_threadinfo (&id, set, &threadinfo))
3379     if (threadinfo.active)
3380       {
3381         if (*threadinfo.shortname)
3382           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3383                           " Name: %s,", threadinfo.shortname);
3384         if (*threadinfo.display)
3385           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3386                           " State: %s,", threadinfo.display);
3387         if (*threadinfo.more_display)
3388           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3389                           " Priority: %s", threadinfo.more_display);
3390
3391         if (n > 0)
3392           {
3393             /* For purely cosmetic reasons, clear up trailing commas.  */
3394             if (',' == display_buf[n-1])
3395               display_buf[n-1] = ' ';
3396             return display_buf;
3397           }
3398       }
3399   return NULL;
3400 }
3401 \f
3402
3403 static int
3404 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3405                                     struct static_tracepoint_marker *marker)
3406 {
3407   struct remote_state *rs = get_remote_state ();
3408   char *p = rs->buf;
3409
3410   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3411   p += strlen (p);
3412   p += hexnumstr (p, addr);
3413   putpkt (rs->buf);
3414   getpkt (&rs->buf, &rs->buf_size, 0);
3415   p = rs->buf;
3416
3417   if (*p == 'E')
3418     error (_("Remote failure reply: %s"), p);
3419
3420   if (*p++ == 'm')
3421     {
3422       parse_static_tracepoint_marker_definition (p, &p, marker);
3423       return 1;
3424     }
3425
3426   return 0;
3427 }
3428
3429 static VEC(static_tracepoint_marker_p) *
3430 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3431                                            const char *strid)
3432 {
3433   struct remote_state *rs = get_remote_state ();
3434   VEC(static_tracepoint_marker_p) *markers = NULL;
3435   struct static_tracepoint_marker *marker = NULL;
3436   struct cleanup *old_chain;
3437   char *p;
3438
3439   /* Ask for a first packet of static tracepoint marker
3440      definition.  */
3441   putpkt ("qTfSTM");
3442   getpkt (&rs->buf, &rs->buf_size, 0);
3443   p = rs->buf;
3444   if (*p == 'E')
3445     error (_("Remote failure reply: %s"), p);
3446
3447   old_chain = make_cleanup (free_current_marker, &marker);
3448
3449   while (*p++ == 'm')
3450     {
3451       if (marker == NULL)
3452         marker = XCNEW (struct static_tracepoint_marker);
3453
3454       do
3455         {
3456           parse_static_tracepoint_marker_definition (p, &p, marker);
3457
3458           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3459             {
3460               VEC_safe_push (static_tracepoint_marker_p,
3461                              markers, marker);
3462               marker = NULL;
3463             }
3464           else
3465             {
3466               release_static_tracepoint_marker (marker);
3467               memset (marker, 0, sizeof (*marker));
3468             }
3469         }
3470       while (*p++ == ',');      /* comma-separated list */
3471       /* Ask for another packet of static tracepoint definition.  */
3472       putpkt ("qTsSTM");
3473       getpkt (&rs->buf, &rs->buf_size, 0);
3474       p = rs->buf;
3475     }
3476
3477   do_cleanups (old_chain);
3478   return markers;
3479 }
3480
3481 \f
3482 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3483
3484 static ptid_t
3485 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3486 {
3487   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3488 }
3489 \f
3490
3491 /* Restart the remote side; this is an extended protocol operation.  */
3492
3493 static void
3494 extended_remote_restart (void)
3495 {
3496   struct remote_state *rs = get_remote_state ();
3497
3498   /* Send the restart command; for reasons I don't understand the
3499      remote side really expects a number after the "R".  */
3500   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3501   putpkt (rs->buf);
3502
3503   remote_fileio_reset ();
3504 }
3505 \f
3506 /* Clean up connection to a remote debugger.  */
3507
3508 static void
3509 remote_close (struct target_ops *self)
3510 {
3511   struct remote_state *rs = get_remote_state ();
3512
3513   if (rs->remote_desc == NULL)
3514     return; /* already closed */
3515
3516   /* Make sure we leave stdin registered in the event loop, and we
3517      don't leave the async SIGINT signal handler installed.  */
3518   remote_terminal_ours (self);
3519
3520   serial_close (rs->remote_desc);
3521   rs->remote_desc = NULL;
3522
3523   /* We don't have a connection to the remote stub anymore.  Get rid
3524      of all the inferiors and their threads we were controlling.
3525      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3526      will be unable to find the thread corresponding to (pid, 0, 0).  */
3527   inferior_ptid = null_ptid;
3528   discard_all_inferiors ();
3529
3530   /* We are closing the remote target, so we should discard
3531      everything of this target.  */
3532   discard_pending_stop_replies_in_queue (rs);
3533
3534   if (remote_async_inferior_event_token)
3535     delete_async_event_handler (&remote_async_inferior_event_token);
3536
3537   remote_notif_state_xfree (rs->notif_state);
3538
3539   trace_reset_local_state ();
3540 }
3541
3542 /* Query the remote side for the text, data and bss offsets.  */
3543
3544 static void
3545 get_offsets (void)
3546 {
3547   struct remote_state *rs = get_remote_state ();
3548   char *buf;
3549   char *ptr;
3550   int lose, num_segments = 0, do_sections, do_segments;
3551   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3552   struct section_offsets *offs;
3553   struct symfile_segment_data *data;
3554
3555   if (symfile_objfile == NULL)
3556     return;
3557
3558   putpkt ("qOffsets");
3559   getpkt (&rs->buf, &rs->buf_size, 0);
3560   buf = rs->buf;
3561
3562   if (buf[0] == '\000')
3563     return;                     /* Return silently.  Stub doesn't support
3564                                    this command.  */
3565   if (buf[0] == 'E')
3566     {
3567       warning (_("Remote failure reply: %s"), buf);
3568       return;
3569     }
3570
3571   /* Pick up each field in turn.  This used to be done with scanf, but
3572      scanf will make trouble if CORE_ADDR size doesn't match
3573      conversion directives correctly.  The following code will work
3574      with any size of CORE_ADDR.  */
3575   text_addr = data_addr = bss_addr = 0;
3576   ptr = buf;
3577   lose = 0;
3578
3579   if (startswith (ptr, "Text="))
3580     {
3581       ptr += 5;
3582       /* Don't use strtol, could lose on big values.  */
3583       while (*ptr && *ptr != ';')
3584         text_addr = (text_addr << 4) + fromhex (*ptr++);
3585
3586       if (startswith (ptr, ";Data="))
3587         {
3588           ptr += 6;
3589           while (*ptr && *ptr != ';')
3590             data_addr = (data_addr << 4) + fromhex (*ptr++);
3591         }
3592       else
3593         lose = 1;
3594
3595       if (!lose && startswith (ptr, ";Bss="))
3596         {
3597           ptr += 5;
3598           while (*ptr && *ptr != ';')
3599             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3600
3601           if (bss_addr != data_addr)
3602             warning (_("Target reported unsupported offsets: %s"), buf);
3603         }
3604       else
3605         lose = 1;
3606     }
3607   else if (startswith (ptr, "TextSeg="))
3608     {
3609       ptr += 8;
3610       /* Don't use strtol, could lose on big values.  */
3611       while (*ptr && *ptr != ';')
3612         text_addr = (text_addr << 4) + fromhex (*ptr++);
3613       num_segments = 1;
3614
3615       if (startswith (ptr, ";DataSeg="))
3616         {
3617           ptr += 9;
3618           while (*ptr && *ptr != ';')
3619             data_addr = (data_addr << 4) + fromhex (*ptr++);
3620           num_segments++;
3621         }
3622     }
3623   else
3624     lose = 1;
3625
3626   if (lose)
3627     error (_("Malformed response to offset query, %s"), buf);
3628   else if (*ptr != '\0')
3629     warning (_("Target reported unsupported offsets: %s"), buf);
3630
3631   offs = ((struct section_offsets *)
3632           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3633   memcpy (offs, symfile_objfile->section_offsets,
3634           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3635
3636   data = get_symfile_segment_data (symfile_objfile->obfd);
3637   do_segments = (data != NULL);
3638   do_sections = num_segments == 0;
3639
3640   if (num_segments > 0)
3641     {
3642       segments[0] = text_addr;
3643       segments[1] = data_addr;
3644     }
3645   /* If we have two segments, we can still try to relocate everything
3646      by assuming that the .text and .data offsets apply to the whole
3647      text and data segments.  Convert the offsets given in the packet
3648      to base addresses for symfile_map_offsets_to_segments.  */
3649   else if (data && data->num_segments == 2)
3650     {
3651       segments[0] = data->segment_bases[0] + text_addr;
3652       segments[1] = data->segment_bases[1] + data_addr;
3653       num_segments = 2;
3654     }
3655   /* If the object file has only one segment, assume that it is text
3656      rather than data; main programs with no writable data are rare,
3657      but programs with no code are useless.  Of course the code might
3658      have ended up in the data segment... to detect that we would need
3659      the permissions here.  */
3660   else if (data && data->num_segments == 1)
3661     {
3662       segments[0] = data->segment_bases[0] + text_addr;
3663       num_segments = 1;
3664     }
3665   /* There's no way to relocate by segment.  */
3666   else
3667     do_segments = 0;
3668
3669   if (do_segments)
3670     {
3671       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3672                                                  offs, num_segments, segments);
3673
3674       if (ret == 0 && !do_sections)
3675         error (_("Can not handle qOffsets TextSeg "
3676                  "response with this symbol file"));
3677
3678       if (ret > 0)
3679         do_sections = 0;
3680     }
3681
3682   if (data)
3683     free_symfile_segment_data (data);
3684
3685   if (do_sections)
3686     {
3687       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3688
3689       /* This is a temporary kludge to force data and bss to use the
3690          same offsets because that's what nlmconv does now.  The real
3691          solution requires changes to the stub and remote.c that I
3692          don't have time to do right now.  */
3693
3694       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3695       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3696     }
3697
3698   objfile_relocate (symfile_objfile, offs);
3699 }
3700
3701 /* Send interrupt_sequence to remote target.  */
3702 static void
3703 send_interrupt_sequence (void)
3704 {
3705   struct remote_state *rs = get_remote_state ();
3706
3707   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3708     remote_serial_write ("\x03", 1);
3709   else if (interrupt_sequence_mode == interrupt_sequence_break)
3710     serial_send_break (rs->remote_desc);
3711   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3712     {
3713       serial_send_break (rs->remote_desc);
3714       remote_serial_write ("g", 1);
3715     }
3716   else
3717     internal_error (__FILE__, __LINE__,
3718                     _("Invalid value for interrupt_sequence_mode: %s."),
3719                     interrupt_sequence_mode);
3720 }
3721
3722
3723 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3724    and extract the PTID.  Returns NULL_PTID if not found.  */
3725
3726 static ptid_t
3727 stop_reply_extract_thread (char *stop_reply)
3728 {
3729   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3730     {
3731       char *p;
3732
3733       /* Txx r:val ; r:val (...)  */
3734       p = &stop_reply[3];
3735
3736       /* Look for "register" named "thread".  */
3737       while (*p != '\0')
3738         {
3739           char *p1;
3740
3741           p1 = strchr (p, ':');
3742           if (p1 == NULL)
3743             return null_ptid;
3744
3745           if (strncmp (p, "thread", p1 - p) == 0)
3746             return read_ptid (++p1, &p);
3747
3748           p1 = strchr (p, ';');
3749           if (p1 == NULL)
3750             return null_ptid;
3751           p1++;
3752
3753           p = p1;
3754         }
3755     }
3756
3757   return null_ptid;
3758 }
3759
3760 /* Determine the remote side's current thread.  If we have a stop
3761    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3762    "thread" register we can extract the current thread from.  If not,
3763    ask the remote which is the current thread with qC.  The former
3764    method avoids a roundtrip.  */
3765
3766 static ptid_t
3767 get_current_thread (char *wait_status)
3768 {
3769   ptid_t ptid = null_ptid;
3770
3771   /* Note we don't use remote_parse_stop_reply as that makes use of
3772      the target architecture, which we haven't yet fully determined at
3773      this point.  */
3774   if (wait_status != NULL)
3775     ptid = stop_reply_extract_thread (wait_status);
3776   if (ptid_equal (ptid, null_ptid))
3777     ptid = remote_current_thread (inferior_ptid);
3778
3779   return ptid;
3780 }
3781
3782 /* Query the remote target for which is the current thread/process,
3783    add it to our tables, and update INFERIOR_PTID.  The caller is
3784    responsible for setting the state such that the remote end is ready
3785    to return the current thread.
3786
3787    This function is called after handling the '?' or 'vRun' packets,
3788    whose response is a stop reply from which we can also try
3789    extracting the thread.  If the target doesn't support the explicit
3790    qC query, we infer the current thread from that stop reply, passed
3791    in in WAIT_STATUS, which may be NULL.  */
3792
3793 static void
3794 add_current_inferior_and_thread (char *wait_status)
3795 {
3796   struct remote_state *rs = get_remote_state ();
3797   int fake_pid_p = 0;
3798   ptid_t ptid;
3799
3800   inferior_ptid = null_ptid;
3801
3802   /* Now, if we have thread information, update inferior_ptid.  */
3803   ptid = get_current_thread (wait_status);
3804
3805   if (!ptid_equal (ptid, null_ptid))
3806     {
3807       if (!remote_multi_process_p (rs))
3808         fake_pid_p = 1;
3809
3810       inferior_ptid = ptid;
3811     }
3812   else
3813     {
3814       /* Without this, some commands which require an active target
3815          (such as kill) won't work.  This variable serves (at least)
3816          double duty as both the pid of the target process (if it has
3817          such), and as a flag indicating that a target is active.  */
3818       inferior_ptid = magic_null_ptid;
3819       fake_pid_p = 1;
3820     }
3821
3822   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3823
3824   /* Add the main thread.  */
3825   add_thread_silent (inferior_ptid);
3826 }
3827
3828 /* Print info about a thread that was found already stopped on
3829    connection.  */
3830
3831 static void
3832 print_one_stopped_thread (struct thread_info *thread)
3833 {
3834   struct target_waitstatus *ws = &thread->suspend.waitstatus;
3835
3836   switch_to_thread (thread->ptid);
3837   stop_pc = get_frame_pc (get_current_frame ());
3838   set_current_sal_from_frame (get_current_frame ());
3839
3840   thread->suspend.waitstatus_pending_p = 0;
3841
3842   if (ws->kind == TARGET_WAITKIND_STOPPED)
3843     {
3844       enum gdb_signal sig = ws->value.sig;
3845
3846       if (signal_print_state (sig))
3847         observer_notify_signal_received (sig);
3848     }
3849   observer_notify_normal_stop (NULL, 1);
3850 }
3851
3852 /* Process all initial stop replies the remote side sent in response
3853    to the ? packet.  These indicate threads that were already stopped
3854    on initial connection.  We mark these threads as stopped and print
3855    their current frame before giving the user the prompt.  */
3856
3857 static void
3858 process_initial_stop_replies (int from_tty)
3859 {
3860   int pending_stop_replies = stop_reply_queue_length ();
3861   struct inferior *inf;
3862   struct thread_info *thread;
3863   struct thread_info *selected = NULL;
3864   struct thread_info *lowest_stopped = NULL;
3865   struct thread_info *first = NULL;
3866
3867   /* Consume the initial pending events.  */
3868   while (pending_stop_replies-- > 0)
3869     {
3870       ptid_t waiton_ptid = minus_one_ptid;
3871       ptid_t event_ptid;
3872       struct target_waitstatus ws;
3873       int ignore_event = 0;
3874       struct thread_info *thread;
3875
3876       memset (&ws, 0, sizeof (ws));
3877       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3878       if (remote_debug)
3879         print_target_wait_results (waiton_ptid, event_ptid, &ws);
3880
3881       switch (ws.kind)
3882         {
3883         case TARGET_WAITKIND_IGNORE:
3884         case TARGET_WAITKIND_NO_RESUMED:
3885         case TARGET_WAITKIND_SIGNALLED:
3886         case TARGET_WAITKIND_EXITED:
3887           /* We shouldn't see these, but if we do, just ignore.  */
3888           if (remote_debug)
3889             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3890           ignore_event = 1;
3891           break;
3892
3893         case TARGET_WAITKIND_EXECD:
3894           xfree (ws.value.execd_pathname);
3895           break;
3896         default:
3897           break;
3898         }
3899
3900       if (ignore_event)
3901         continue;
3902
3903       thread = find_thread_ptid (event_ptid);
3904
3905       if (ws.kind == TARGET_WAITKIND_STOPPED)
3906         {
3907           enum gdb_signal sig = ws.value.sig;
3908
3909           /* Stubs traditionally report SIGTRAP as initial signal,
3910              instead of signal 0.  Suppress it.  */
3911           if (sig == GDB_SIGNAL_TRAP)
3912             sig = GDB_SIGNAL_0;
3913           thread->suspend.stop_signal = sig;
3914           ws.value.sig = sig;
3915         }
3916
3917       thread->suspend.waitstatus = ws;
3918
3919       if (ws.kind != TARGET_WAITKIND_STOPPED
3920           || ws.value.sig != GDB_SIGNAL_0)
3921         thread->suspend.waitstatus_pending_p = 1;
3922
3923       set_executing (event_ptid, 0);
3924       set_running (event_ptid, 0);
3925     }
3926
3927   /* "Notice" the new inferiors before anything related to
3928      registers/memory.  */
3929   ALL_INFERIORS (inf)
3930     {
3931       if (inf->pid == 0)
3932         continue;
3933
3934       inf->needs_setup = 1;
3935
3936       if (non_stop)
3937         {
3938           thread = any_live_thread_of_process (inf->pid);
3939           notice_new_inferior (thread->ptid,
3940                                thread->state == THREAD_RUNNING,
3941                                from_tty);
3942         }
3943     }
3944
3945   /* If all-stop on top of non-stop, pause all threads.  Note this
3946      records the threads' stop pc, so must be done after "noticing"
3947      the inferiors.  */
3948   if (!non_stop)
3949     {
3950       stop_all_threads ();
3951
3952       /* If all threads of an inferior were already stopped, we
3953          haven't setup the inferior yet.  */
3954       ALL_INFERIORS (inf)
3955         {
3956           if (inf->pid == 0)
3957             continue;
3958
3959           if (inf->needs_setup)
3960             {
3961               thread = any_live_thread_of_process (inf->pid);
3962               switch_to_thread_no_regs (thread);
3963               setup_inferior (0);
3964             }
3965         }
3966     }
3967
3968   /* Now go over all threads that are stopped, and print their current
3969      frame.  If all-stop, then if there's a signalled thread, pick
3970      that as current.  */
3971   ALL_NON_EXITED_THREADS (thread)
3972     {
3973       if (first == NULL)
3974         first = thread;
3975
3976       if (!non_stop)
3977         set_running (thread->ptid, 0);
3978       else if (thread->state != THREAD_STOPPED)
3979         continue;
3980
3981       if (selected == NULL
3982           && thread->suspend.waitstatus_pending_p)
3983         selected = thread;
3984
3985       if (lowest_stopped == NULL
3986           || thread->inf->num < lowest_stopped->inf->num
3987           || thread->per_inf_num < lowest_stopped->per_inf_num)
3988         lowest_stopped = thread;
3989
3990       if (non_stop)
3991         print_one_stopped_thread (thread);
3992     }
3993
3994   /* In all-stop, we only print the status of one thread, and leave
3995      others with their status pending.  */
3996   if (!non_stop)
3997     {
3998       thread = selected;
3999       if (thread == NULL)
4000         thread = lowest_stopped;
4001       if (thread == NULL)
4002         thread = first;
4003
4004       print_one_stopped_thread (thread);
4005     }
4006
4007   /* For "info program".  */
4008   thread = inferior_thread ();
4009   if (thread->state == THREAD_STOPPED)
4010     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4011 }
4012
4013 static void
4014 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4015 {
4016   struct remote_state *rs = get_remote_state ();
4017   struct packet_config *noack_config;
4018   char *wait_status = NULL;
4019
4020   immediate_quit++;             /* Allow user to interrupt it.  */
4021   QUIT;
4022
4023   if (interrupt_on_connect)
4024     send_interrupt_sequence ();
4025
4026   /* Ack any packet which the remote side has already sent.  */
4027   serial_write (rs->remote_desc, "+", 1);
4028
4029   /* Signal other parts that we're going through the initial setup,
4030      and so things may not be stable yet.  */
4031   rs->starting_up = 1;
4032
4033   /* The first packet we send to the target is the optional "supported
4034      packets" request.  If the target can answer this, it will tell us
4035      which later probes to skip.  */
4036   remote_query_supported ();
4037
4038   /* If the stub wants to get a QAllow, compose one and send it.  */
4039   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4040     remote_set_permissions (target);
4041
4042   /* See unknown_v_replies_ok description.  */
4043   {
4044     const char v_mustreplyempty[] = "vMustReplyEmpty";
4045
4046     putpkt (v_mustreplyempty);
4047     getpkt (&rs->buf, &rs->buf_size, 0);
4048     if (strcmp (rs->buf, "OK") == 0)
4049       rs->unknown_v_replies_ok = 1;
4050     else if (strcmp (rs->buf, "") == 0)
4051       rs->unknown_v_replies_ok = 0;
4052     else
4053       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4054              rs->buf);
4055   }
4056
4057   /* Next, we possibly activate noack mode.
4058
4059      If the QStartNoAckMode packet configuration is set to AUTO,
4060      enable noack mode if the stub reported a wish for it with
4061      qSupported.
4062
4063      If set to TRUE, then enable noack mode even if the stub didn't
4064      report it in qSupported.  If the stub doesn't reply OK, the
4065      session ends with an error.
4066
4067      If FALSE, then don't activate noack mode, regardless of what the
4068      stub claimed should be the default with qSupported.  */
4069
4070   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4071   if (packet_config_support (noack_config) != PACKET_DISABLE)
4072     {
4073       putpkt ("QStartNoAckMode");
4074       getpkt (&rs->buf, &rs->buf_size, 0);
4075       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4076         rs->noack_mode = 1;
4077     }
4078
4079   if (extended_p)
4080     {
4081       /* Tell the remote that we are using the extended protocol.  */
4082       putpkt ("!");
4083       getpkt (&rs->buf, &rs->buf_size, 0);
4084     }
4085
4086   /* Let the target know which signals it is allowed to pass down to
4087      the program.  */
4088   update_signals_program_target ();
4089
4090   /* Next, if the target can specify a description, read it.  We do
4091      this before anything involving memory or registers.  */
4092   target_find_description ();
4093
4094   /* Next, now that we know something about the target, update the
4095      address spaces in the program spaces.  */
4096   update_address_spaces ();
4097
4098   /* On OSs where the list of libraries is global to all
4099      processes, we fetch them early.  */
4100   if (gdbarch_has_global_solist (target_gdbarch ()))
4101     solib_add (NULL, from_tty, target, auto_solib_add);
4102
4103   if (target_is_non_stop_p ())
4104     {
4105       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4106         error (_("Non-stop mode requested, but remote "
4107                  "does not support non-stop"));
4108
4109       putpkt ("QNonStop:1");
4110       getpkt (&rs->buf, &rs->buf_size, 0);
4111
4112       if (strcmp (rs->buf, "OK") != 0)
4113         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4114
4115       /* Find about threads and processes the stub is already
4116          controlling.  We default to adding them in the running state.
4117          The '?' query below will then tell us about which threads are
4118          stopped.  */
4119       remote_update_thread_list (target);
4120     }
4121   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4122     {
4123       /* Don't assume that the stub can operate in all-stop mode.
4124          Request it explicitly.  */
4125       putpkt ("QNonStop:0");
4126       getpkt (&rs->buf, &rs->buf_size, 0);
4127
4128       if (strcmp (rs->buf, "OK") != 0)
4129         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4130     }
4131
4132   /* Upload TSVs regardless of whether the target is running or not.  The
4133      remote stub, such as GDBserver, may have some predefined or builtin
4134      TSVs, even if the target is not running.  */
4135   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4136     {
4137       struct uploaded_tsv *uploaded_tsvs = NULL;
4138
4139       remote_upload_trace_state_variables (target, &uploaded_tsvs);
4140       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4141     }
4142
4143   /* Check whether the target is running now.  */
4144   putpkt ("?");
4145   getpkt (&rs->buf, &rs->buf_size, 0);
4146
4147   if (!target_is_non_stop_p ())
4148     {
4149       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4150         {
4151           if (!extended_p)
4152             error (_("The target is not running (try extended-remote?)"));
4153
4154           /* We're connected, but not running.  Drop out before we
4155              call start_remote.  */
4156           rs->starting_up = 0;
4157           return;
4158         }
4159       else
4160         {
4161           /* Save the reply for later.  */
4162           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4163           strcpy (wait_status, rs->buf);
4164         }
4165
4166       /* Fetch thread list.  */
4167       target_update_thread_list ();
4168
4169       /* Let the stub know that we want it to return the thread.  */
4170       set_continue_thread (minus_one_ptid);
4171
4172       if (thread_count () == 0)
4173         {
4174           /* Target has no concept of threads at all.  GDB treats
4175              non-threaded target as single-threaded; add a main
4176              thread.  */
4177           add_current_inferior_and_thread (wait_status);
4178         }
4179       else
4180         {
4181           /* We have thread information; select the thread the target
4182              says should be current.  If we're reconnecting to a
4183              multi-threaded program, this will ideally be the thread
4184              that last reported an event before GDB disconnected.  */
4185           inferior_ptid = get_current_thread (wait_status);
4186           if (ptid_equal (inferior_ptid, null_ptid))
4187             {
4188               /* Odd... The target was able to list threads, but not
4189                  tell us which thread was current (no "thread"
4190                  register in T stop reply?).  Just pick the first
4191                  thread in the thread list then.  */
4192               
4193               if (remote_debug)
4194                 fprintf_unfiltered (gdb_stdlog,
4195                                     "warning: couldn't determine remote "
4196                                     "current thread; picking first in list.\n");
4197
4198               inferior_ptid = thread_list->ptid;
4199             }
4200         }
4201
4202       /* init_wait_for_inferior should be called before get_offsets in order
4203          to manage `inserted' flag in bp loc in a correct state.
4204          breakpoint_init_inferior, called from init_wait_for_inferior, set
4205          `inserted' flag to 0, while before breakpoint_re_set, called from
4206          start_remote, set `inserted' flag to 1.  In the initialization of
4207          inferior, breakpoint_init_inferior should be called first, and then
4208          breakpoint_re_set can be called.  If this order is broken, state of
4209          `inserted' flag is wrong, and cause some problems on breakpoint
4210          manipulation.  */
4211       init_wait_for_inferior ();
4212
4213       get_offsets ();           /* Get text, data & bss offsets.  */
4214
4215       /* If we could not find a description using qXfer, and we know
4216          how to do it some other way, try again.  This is not
4217          supported for non-stop; it could be, but it is tricky if
4218          there are no stopped threads when we connect.  */
4219       if (remote_read_description_p (target)
4220           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4221         {
4222           target_clear_description ();
4223           target_find_description ();
4224         }
4225
4226       /* Use the previously fetched status.  */
4227       gdb_assert (wait_status != NULL);
4228       strcpy (rs->buf, wait_status);
4229       rs->cached_wait_status = 1;
4230
4231       immediate_quit--;
4232       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4233     }
4234   else
4235     {
4236       /* Clear WFI global state.  Do this before finding about new
4237          threads and inferiors, and setting the current inferior.
4238          Otherwise we would clear the proceed status of the current
4239          inferior when we want its stop_soon state to be preserved
4240          (see notice_new_inferior).  */
4241       init_wait_for_inferior ();
4242
4243       /* In non-stop, we will either get an "OK", meaning that there
4244          are no stopped threads at this time; or, a regular stop
4245          reply.  In the latter case, there may be more than one thread
4246          stopped --- we pull them all out using the vStopped
4247          mechanism.  */
4248       if (strcmp (rs->buf, "OK") != 0)
4249         {
4250           struct notif_client *notif = &notif_client_stop;
4251
4252           /* remote_notif_get_pending_replies acks this one, and gets
4253              the rest out.  */
4254           rs->notif_state->pending_event[notif_client_stop.id]
4255             = remote_notif_parse (notif, rs->buf);
4256           remote_notif_get_pending_events (notif);
4257         }
4258
4259       if (thread_count () == 0)
4260         {
4261           if (!extended_p)
4262             error (_("The target is not running (try extended-remote?)"));
4263
4264           /* We're connected, but not running.  Drop out before we
4265              call start_remote.  */
4266           rs->starting_up = 0;
4267           return;
4268         }
4269
4270       /* In non-stop mode, any cached wait status will be stored in
4271          the stop reply queue.  */
4272       gdb_assert (wait_status == NULL);
4273
4274       /* Report all signals during attach/startup.  */
4275       remote_pass_signals (target, 0, NULL);
4276
4277       /* If there are already stopped threads, mark them stopped and
4278          report their stops before giving the prompt to the user.  */
4279       process_initial_stop_replies (from_tty);
4280
4281       if (target_can_async_p ())
4282         target_async (1);
4283     }
4284
4285   /* If we connected to a live target, do some additional setup.  */
4286   if (target_has_execution)
4287     {
4288       if (symfile_objfile)      /* No use without a symbol-file.  */
4289         remote_check_symbols ();
4290     }
4291
4292   /* Possibly the target has been engaged in a trace run started
4293      previously; find out where things are at.  */
4294   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4295     {
4296       struct uploaded_tp *uploaded_tps = NULL;
4297
4298       if (current_trace_status ()->running)
4299         printf_filtered (_("Trace is already running on the target.\n"));
4300
4301       remote_upload_tracepoints (target, &uploaded_tps);
4302
4303       merge_uploaded_tracepoints (&uploaded_tps);
4304     }
4305
4306   /* The thread and inferior lists are now synchronized with the
4307      target, our symbols have been relocated, and we're merged the
4308      target's tracepoints with ours.  We're done with basic start
4309      up.  */
4310   rs->starting_up = 0;
4311
4312   /* Maybe breakpoints are global and need to be inserted now.  */
4313   if (breakpoints_should_be_inserted_now ())
4314     insert_breakpoints ();
4315 }
4316
4317 /* Open a connection to a remote debugger.
4318    NAME is the filename used for communication.  */
4319
4320 static void
4321 remote_open (const char *name, int from_tty)
4322 {
4323   remote_open_1 (name, from_tty, &remote_ops, 0);
4324 }
4325
4326 /* Open a connection to a remote debugger using the extended
4327    remote gdb protocol.  NAME is the filename used for communication.  */
4328
4329 static void
4330 extended_remote_open (const char *name, int from_tty)
4331 {
4332   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4333 }
4334
4335 /* Reset all packets back to "unknown support".  Called when opening a
4336    new connection to a remote target.  */
4337
4338 static void
4339 reset_all_packet_configs_support (void)
4340 {
4341   int i;
4342
4343   for (i = 0; i < PACKET_MAX; i++)
4344     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4345 }
4346
4347 /* Initialize all packet configs.  */
4348
4349 static void
4350 init_all_packet_configs (void)
4351 {
4352   int i;
4353
4354   for (i = 0; i < PACKET_MAX; i++)
4355     {
4356       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4357       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4358     }
4359 }
4360
4361 /* Symbol look-up.  */
4362
4363 static void
4364 remote_check_symbols (void)
4365 {
4366   struct remote_state *rs = get_remote_state ();
4367   char *msg, *reply, *tmp;
4368   int end;
4369   long reply_size;
4370   struct cleanup *old_chain;
4371
4372   /* The remote side has no concept of inferiors that aren't running
4373      yet, it only knows about running processes.  If we're connected
4374      but our current inferior is not running, we should not invite the
4375      remote target to request symbol lookups related to its
4376      (unrelated) current process.  */
4377   if (!target_has_execution)
4378     return;
4379
4380   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4381     return;
4382
4383   /* Make sure the remote is pointing at the right process.  Note
4384      there's no way to select "no process".  */
4385   set_general_process ();
4386
4387   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4388      because we need both at the same time.  */
4389   msg = (char *) xmalloc (get_remote_packet_size ());
4390   old_chain = make_cleanup (xfree, msg);
4391   reply = (char *) xmalloc (get_remote_packet_size ());
4392   make_cleanup (free_current_contents, &reply);
4393   reply_size = get_remote_packet_size ();
4394
4395   /* Invite target to request symbol lookups.  */
4396
4397   putpkt ("qSymbol::");
4398   getpkt (&reply, &reply_size, 0);
4399   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4400
4401   while (startswith (reply, "qSymbol:"))
4402     {
4403       struct bound_minimal_symbol sym;
4404
4405       tmp = &reply[8];
4406       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4407       msg[end] = '\0';
4408       sym = lookup_minimal_symbol (msg, NULL, NULL);
4409       if (sym.minsym == NULL)
4410         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4411       else
4412         {
4413           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4414           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4415
4416           /* If this is a function address, return the start of code
4417              instead of any data function descriptor.  */
4418           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4419                                                          sym_addr,
4420                                                          &current_target);
4421
4422           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4423                      phex_nz (sym_addr, addr_size), &reply[8]);
4424         }
4425   
4426       putpkt (msg);
4427       getpkt (&reply, &reply_size, 0);
4428     }
4429
4430   do_cleanups (old_chain);
4431 }
4432
4433 static struct serial *
4434 remote_serial_open (const char *name)
4435 {
4436   static int udp_warning = 0;
4437
4438   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4439      of in ser-tcp.c, because it is the remote protocol assuming that the
4440      serial connection is reliable and not the serial connection promising
4441      to be.  */
4442   if (!udp_warning && startswith (name, "udp:"))
4443     {
4444       warning (_("The remote protocol may be unreliable over UDP.\n"
4445                  "Some events may be lost, rendering further debugging "
4446                  "impossible."));
4447       udp_warning = 1;
4448     }
4449
4450   return serial_open (name);
4451 }
4452
4453 /* Inform the target of our permission settings.  The permission flags
4454    work without this, but if the target knows the settings, it can do
4455    a couple things.  First, it can add its own check, to catch cases
4456    that somehow manage to get by the permissions checks in target
4457    methods.  Second, if the target is wired to disallow particular
4458    settings (for instance, a system in the field that is not set up to
4459    be able to stop at a breakpoint), it can object to any unavailable
4460    permissions.  */
4461
4462 void
4463 remote_set_permissions (struct target_ops *self)
4464 {
4465   struct remote_state *rs = get_remote_state ();
4466
4467   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4468              "WriteReg:%x;WriteMem:%x;"
4469              "InsertBreak:%x;InsertTrace:%x;"
4470              "InsertFastTrace:%x;Stop:%x",
4471              may_write_registers, may_write_memory,
4472              may_insert_breakpoints, may_insert_tracepoints,
4473              may_insert_fast_tracepoints, may_stop);
4474   putpkt (rs->buf);
4475   getpkt (&rs->buf, &rs->buf_size, 0);
4476
4477   /* If the target didn't like the packet, warn the user.  Do not try
4478      to undo the user's settings, that would just be maddening.  */
4479   if (strcmp (rs->buf, "OK") != 0)
4480     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4481 }
4482
4483 /* This type describes each known response to the qSupported
4484    packet.  */
4485 struct protocol_feature
4486 {
4487   /* The name of this protocol feature.  */
4488   const char *name;
4489
4490   /* The default for this protocol feature.  */
4491   enum packet_support default_support;
4492
4493   /* The function to call when this feature is reported, or after
4494      qSupported processing if the feature is not supported.
4495      The first argument points to this structure.  The second
4496      argument indicates whether the packet requested support be
4497      enabled, disabled, or probed (or the default, if this function
4498      is being called at the end of processing and this feature was
4499      not reported).  The third argument may be NULL; if not NULL, it
4500      is a NUL-terminated string taken from the packet following
4501      this feature's name and an equals sign.  */
4502   void (*func) (const struct protocol_feature *, enum packet_support,
4503                 const char *);
4504
4505   /* The corresponding packet for this feature.  Only used if
4506      FUNC is remote_supported_packet.  */
4507   int packet;
4508 };
4509
4510 static void
4511 remote_supported_packet (const struct protocol_feature *feature,
4512                          enum packet_support support,
4513                          const char *argument)
4514 {
4515   if (argument)
4516     {
4517       warning (_("Remote qSupported response supplied an unexpected value for"
4518                  " \"%s\"."), feature->name);
4519       return;
4520     }
4521
4522   remote_protocol_packets[feature->packet].support = support;
4523 }
4524
4525 static void
4526 remote_packet_size (const struct protocol_feature *feature,
4527                     enum packet_support support, const char *value)
4528 {
4529   struct remote_state *rs = get_remote_state ();
4530
4531   int packet_size;
4532   char *value_end;
4533
4534   if (support != PACKET_ENABLE)
4535     return;
4536
4537   if (value == NULL || *value == '\0')
4538     {
4539       warning (_("Remote target reported \"%s\" without a size."),
4540                feature->name);
4541       return;
4542     }
4543
4544   errno = 0;
4545   packet_size = strtol (value, &value_end, 16);
4546   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4547     {
4548       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4549                feature->name, value);
4550       return;
4551     }
4552
4553   /* Record the new maximum packet size.  */
4554   rs->explicit_packet_size = packet_size;
4555 }
4556
4557 static const struct protocol_feature remote_protocol_features[] = {
4558   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4559   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4560     PACKET_qXfer_auxv },
4561   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4562     PACKET_qXfer_exec_file },
4563   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4564     PACKET_qXfer_features },
4565   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4566     PACKET_qXfer_libraries },
4567   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4568     PACKET_qXfer_libraries_svr4 },
4569   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4570     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4571   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4572     PACKET_qXfer_memory_map },
4573   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4574     PACKET_qXfer_spu_read },
4575   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4576     PACKET_qXfer_spu_write },
4577   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4578     PACKET_qXfer_osdata },
4579   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4580     PACKET_qXfer_threads },
4581   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4582     PACKET_qXfer_traceframe_info },
4583   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4584     PACKET_QPassSignals },
4585   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4586     PACKET_QCatchSyscalls },
4587   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4588     PACKET_QProgramSignals },
4589   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4590     PACKET_QStartNoAckMode },
4591   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4592     PACKET_multiprocess_feature },
4593   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4594   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4595     PACKET_qXfer_siginfo_read },
4596   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4597     PACKET_qXfer_siginfo_write },
4598   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4599     PACKET_ConditionalTracepoints },
4600   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4601     PACKET_ConditionalBreakpoints },
4602   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4603     PACKET_BreakpointCommands },
4604   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4605     PACKET_FastTracepoints },
4606   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4607     PACKET_StaticTracepoints },
4608   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4609    PACKET_InstallInTrace},
4610   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4611     PACKET_DisconnectedTracing_feature },
4612   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4613     PACKET_bc },
4614   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4615     PACKET_bs },
4616   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4617     PACKET_TracepointSource },
4618   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4619     PACKET_QAllow },
4620   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4621     PACKET_EnableDisableTracepoints_feature },
4622   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4623     PACKET_qXfer_fdpic },
4624   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4625     PACKET_qXfer_uib },
4626   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4627     PACKET_QDisableRandomization },
4628   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4629   { "QTBuffer:size", PACKET_DISABLE,
4630     remote_supported_packet, PACKET_QTBuffer_size},
4631   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4632   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4633   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4634   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4635   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4636     PACKET_qXfer_btrace },
4637   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4638     PACKET_qXfer_btrace_conf },
4639   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4640     PACKET_Qbtrace_conf_bts_size },
4641   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4642   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4643   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4644     PACKET_fork_event_feature },
4645   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4646     PACKET_vfork_event_feature },
4647   { "exec-events", PACKET_DISABLE, remote_supported_packet,
4648     PACKET_exec_event_feature },
4649   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4650     PACKET_Qbtrace_conf_pt_size },
4651   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4652   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4653   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4654 };
4655
4656 static char *remote_support_xml;
4657
4658 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4659
4660 void
4661 register_remote_support_xml (const char *xml)
4662 {
4663 #if defined(HAVE_LIBEXPAT)
4664   if (remote_support_xml == NULL)
4665     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4666   else
4667     {
4668       char *copy = xstrdup (remote_support_xml + 13);
4669       char *p = strtok (copy, ",");
4670
4671       do
4672         {
4673           if (strcmp (p, xml) == 0)
4674             {
4675               /* already there */
4676               xfree (copy);
4677               return;
4678             }
4679         }
4680       while ((p = strtok (NULL, ",")) != NULL);
4681       xfree (copy);
4682
4683       remote_support_xml = reconcat (remote_support_xml,
4684                                      remote_support_xml, ",", xml,
4685                                      (char *) NULL);
4686     }
4687 #endif
4688 }
4689
4690 static char *
4691 remote_query_supported_append (char *msg, const char *append)
4692 {
4693   if (msg)
4694     return reconcat (msg, msg, ";", append, (char *) NULL);
4695   else
4696     return xstrdup (append);
4697 }
4698
4699 static void
4700 remote_query_supported (void)
4701 {
4702   struct remote_state *rs = get_remote_state ();
4703   char *next;
4704   int i;
4705   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4706
4707   /* The packet support flags are handled differently for this packet
4708      than for most others.  We treat an error, a disabled packet, and
4709      an empty response identically: any features which must be reported
4710      to be used will be automatically disabled.  An empty buffer
4711      accomplishes this, since that is also the representation for a list
4712      containing no features.  */
4713
4714   rs->buf[0] = 0;
4715   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4716     {
4717       char *q = NULL;
4718       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4719
4720       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4721         q = remote_query_supported_append (q, "multiprocess+");
4722
4723       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4724         q = remote_query_supported_append (q, "swbreak+");
4725       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4726         q = remote_query_supported_append (q, "hwbreak+");
4727
4728       q = remote_query_supported_append (q, "qRelocInsn+");
4729
4730       if (packet_set_cmd_state (PACKET_fork_event_feature)
4731           != AUTO_BOOLEAN_FALSE)
4732         q = remote_query_supported_append (q, "fork-events+");
4733       if (packet_set_cmd_state (PACKET_vfork_event_feature)
4734           != AUTO_BOOLEAN_FALSE)
4735         q = remote_query_supported_append (q, "vfork-events+");
4736       if (packet_set_cmd_state (PACKET_exec_event_feature)
4737           != AUTO_BOOLEAN_FALSE)
4738         q = remote_query_supported_append (q, "exec-events+");
4739
4740       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4741         q = remote_query_supported_append (q, "vContSupported+");
4742
4743       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4744         q = remote_query_supported_append (q, "QThreadEvents+");
4745
4746       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4747         q = remote_query_supported_append (q, "no-resumed+");
4748
4749       /* Keep this one last to work around a gdbserver <= 7.10 bug in
4750          the qSupported:xmlRegisters=i386 handling.  */
4751       if (remote_support_xml != NULL)
4752         q = remote_query_supported_append (q, remote_support_xml);
4753
4754       q = reconcat (q, "qSupported:", q, (char *) NULL);
4755       putpkt (q);
4756
4757       do_cleanups (old_chain);
4758
4759       getpkt (&rs->buf, &rs->buf_size, 0);
4760
4761       /* If an error occured, warn, but do not return - just reset the
4762          buffer to empty and go on to disable features.  */
4763       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4764           == PACKET_ERROR)
4765         {
4766           warning (_("Remote failure reply: %s"), rs->buf);
4767           rs->buf[0] = 0;
4768         }
4769     }
4770
4771   memset (seen, 0, sizeof (seen));
4772
4773   next = rs->buf;
4774   while (*next)
4775     {
4776       enum packet_support is_supported;
4777       char *p, *end, *name_end, *value;
4778
4779       /* First separate out this item from the rest of the packet.  If
4780          there's another item after this, we overwrite the separator
4781          (terminated strings are much easier to work with).  */
4782       p = next;
4783       end = strchr (p, ';');
4784       if (end == NULL)
4785         {
4786           end = p + strlen (p);
4787           next = end;
4788         }
4789       else
4790         {
4791           *end = '\0';
4792           next = end + 1;
4793
4794           if (end == p)
4795             {
4796               warning (_("empty item in \"qSupported\" response"));
4797               continue;
4798             }
4799         }
4800
4801       name_end = strchr (p, '=');
4802       if (name_end)
4803         {
4804           /* This is a name=value entry.  */
4805           is_supported = PACKET_ENABLE;
4806           value = name_end + 1;
4807           *name_end = '\0';
4808         }
4809       else
4810         {
4811           value = NULL;
4812           switch (end[-1])
4813             {
4814             case '+':
4815               is_supported = PACKET_ENABLE;
4816               break;
4817
4818             case '-':
4819               is_supported = PACKET_DISABLE;
4820               break;
4821
4822             case '?':
4823               is_supported = PACKET_SUPPORT_UNKNOWN;
4824               break;
4825
4826             default:
4827               warning (_("unrecognized item \"%s\" "
4828                          "in \"qSupported\" response"), p);
4829               continue;
4830             }
4831           end[-1] = '\0';
4832         }
4833
4834       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4835         if (strcmp (remote_protocol_features[i].name, p) == 0)
4836           {
4837             const struct protocol_feature *feature;
4838
4839             seen[i] = 1;
4840             feature = &remote_protocol_features[i];
4841             feature->func (feature, is_supported, value);
4842             break;
4843           }
4844     }
4845
4846   /* If we increased the packet size, make sure to increase the global
4847      buffer size also.  We delay this until after parsing the entire
4848      qSupported packet, because this is the same buffer we were
4849      parsing.  */
4850   if (rs->buf_size < rs->explicit_packet_size)
4851     {
4852       rs->buf_size = rs->explicit_packet_size;
4853       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4854     }
4855
4856   /* Handle the defaults for unmentioned features.  */
4857   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4858     if (!seen[i])
4859       {
4860         const struct protocol_feature *feature;
4861
4862         feature = &remote_protocol_features[i];
4863         feature->func (feature, feature->default_support, NULL);
4864       }
4865 }
4866
4867 /* Remove any of the remote.c targets from target stack.  Upper targets depend
4868    on it so remove them first.  */
4869
4870 static void
4871 remote_unpush_target (void)
4872 {
4873   pop_all_targets_at_and_above (process_stratum);
4874 }
4875
4876 static void
4877 remote_open_1 (const char *name, int from_tty,
4878                struct target_ops *target, int extended_p)
4879 {
4880   struct remote_state *rs = get_remote_state ();
4881
4882   if (name == 0)
4883     error (_("To open a remote debug connection, you need to specify what\n"
4884            "serial device is attached to the remote system\n"
4885            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4886
4887   /* See FIXME above.  */
4888   if (!target_async_permitted)
4889     wait_forever_enabled_p = 1;
4890
4891   /* If we're connected to a running target, target_preopen will kill it.
4892      Ask this question first, before target_preopen has a chance to kill
4893      anything.  */
4894   if (rs->remote_desc != NULL && !have_inferiors ())
4895     {
4896       if (from_tty
4897           && !query (_("Already connected to a remote target.  Disconnect? ")))
4898         error (_("Still connected."));
4899     }
4900
4901   /* Here the possibly existing remote target gets unpushed.  */
4902   target_preopen (from_tty);
4903
4904   /* Make sure we send the passed signals list the next time we resume.  */
4905   xfree (rs->last_pass_packet);
4906   rs->last_pass_packet = NULL;
4907
4908   /* Make sure we send the program signals list the next time we
4909      resume.  */
4910   xfree (rs->last_program_signals_packet);
4911   rs->last_program_signals_packet = NULL;
4912
4913   remote_fileio_reset ();
4914   reopen_exec_file ();
4915   reread_symbols ();
4916
4917   rs->remote_desc = remote_serial_open (name);
4918   if (!rs->remote_desc)
4919     perror_with_name (name);
4920
4921   if (baud_rate != -1)
4922     {
4923       if (serial_setbaudrate (rs->remote_desc, baud_rate))
4924         {
4925           /* The requested speed could not be set.  Error out to
4926              top level after closing remote_desc.  Take care to
4927              set remote_desc to NULL to avoid closing remote_desc
4928              more than once.  */
4929           serial_close (rs->remote_desc);
4930           rs->remote_desc = NULL;
4931           perror_with_name (name);
4932         }
4933     }
4934
4935   serial_setparity (rs->remote_desc, serial_parity);
4936   serial_raw (rs->remote_desc);
4937
4938   /* If there is something sitting in the buffer we might take it as a
4939      response to a command, which would be bad.  */
4940   serial_flush_input (rs->remote_desc);
4941
4942   if (from_tty)
4943     {
4944       puts_filtered ("Remote debugging using ");
4945       puts_filtered (name);
4946       puts_filtered ("\n");
4947     }
4948   push_target (target);         /* Switch to using remote target now.  */
4949
4950   /* Register extra event sources in the event loop.  */
4951   remote_async_inferior_event_token
4952     = create_async_event_handler (remote_async_inferior_event_handler,
4953                                   NULL);
4954   rs->notif_state = remote_notif_state_allocate ();
4955
4956   /* Reset the target state; these things will be queried either by
4957      remote_query_supported or as they are needed.  */
4958   reset_all_packet_configs_support ();
4959   rs->cached_wait_status = 0;
4960   rs->explicit_packet_size = 0;
4961   rs->noack_mode = 0;
4962   rs->extended = extended_p;
4963   rs->waiting_for_stop_reply = 0;
4964   rs->ctrlc_pending_p = 0;
4965
4966   rs->general_thread = not_sent_ptid;
4967   rs->continue_thread = not_sent_ptid;
4968   rs->remote_traceframe_number = -1;
4969
4970   /* Probe for ability to use "ThreadInfo" query, as required.  */
4971   rs->use_threadinfo_query = 1;
4972   rs->use_threadextra_query = 1;
4973
4974   readahead_cache_invalidate ();
4975
4976   if (target_async_permitted)
4977     {
4978       /* With this target we start out by owning the terminal.  */
4979       remote_async_terminal_ours_p = 1;
4980
4981       /* FIXME: cagney/1999-09-23: During the initial connection it is
4982          assumed that the target is already ready and able to respond to
4983          requests.  Unfortunately remote_start_remote() eventually calls
4984          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
4985          around this.  Eventually a mechanism that allows
4986          wait_for_inferior() to expect/get timeouts will be
4987          implemented.  */
4988       wait_forever_enabled_p = 0;
4989     }
4990
4991   /* First delete any symbols previously loaded from shared libraries.  */
4992   no_shared_libraries (NULL, 0);
4993
4994   /* Start afresh.  */
4995   init_thread_list ();
4996
4997   /* Start the remote connection.  If error() or QUIT, discard this
4998      target (we'd otherwise be in an inconsistent state) and then
4999      propogate the error on up the exception chain.  This ensures that
5000      the caller doesn't stumble along blindly assuming that the
5001      function succeeded.  The CLI doesn't have this problem but other
5002      UI's, such as MI do.
5003
5004      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5005      this function should return an error indication letting the
5006      caller restore the previous state.  Unfortunately the command
5007      ``target remote'' is directly wired to this function making that
5008      impossible.  On a positive note, the CLI side of this problem has
5009      been fixed - the function set_cmd_context() makes it possible for
5010      all the ``target ....'' commands to share a common callback
5011      function.  See cli-dump.c.  */
5012   {
5013
5014     TRY
5015       {
5016         remote_start_remote (from_tty, target, extended_p);
5017       }
5018     CATCH (ex, RETURN_MASK_ALL)
5019       {
5020         /* Pop the partially set up target - unless something else did
5021            already before throwing the exception.  */
5022         if (rs->remote_desc != NULL)
5023           remote_unpush_target ();
5024         if (target_async_permitted)
5025           wait_forever_enabled_p = 1;
5026         throw_exception (ex);
5027       }
5028     END_CATCH
5029   }
5030
5031   remote_btrace_reset ();
5032
5033   if (target_async_permitted)
5034     wait_forever_enabled_p = 1;
5035 }
5036
5037 /* Detach the specified process.  */
5038
5039 static void
5040 remote_detach_pid (int pid)
5041 {
5042   struct remote_state *rs = get_remote_state ();
5043
5044   if (remote_multi_process_p (rs))
5045     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5046   else
5047     strcpy (rs->buf, "D");
5048
5049   putpkt (rs->buf);
5050   getpkt (&rs->buf, &rs->buf_size, 0);
5051
5052   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5053     ;
5054   else if (rs->buf[0] == '\0')
5055     error (_("Remote doesn't know how to detach"));
5056   else
5057     error (_("Can't detach process."));
5058 }
5059
5060 /* This detaches a program to which we previously attached, using
5061    inferior_ptid to identify the process.  After this is done, GDB
5062    can be used to debug some other program.  We better not have left
5063    any breakpoints in the target program or it'll die when it hits
5064    one.  */
5065
5066 static void
5067 remote_detach_1 (const char *args, int from_tty)
5068 {
5069   int pid = ptid_get_pid (inferior_ptid);
5070   struct remote_state *rs = get_remote_state ();
5071   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5072   int is_fork_parent;
5073
5074   if (args)
5075     error (_("Argument given to \"detach\" when remotely debugging."));
5076
5077   if (!target_has_execution)
5078     error (_("No process to detach from."));
5079
5080   if (from_tty)
5081     {
5082       char *exec_file = get_exec_file (0);
5083       if (exec_file == NULL)
5084         exec_file = "";
5085       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
5086                          target_pid_to_str (pid_to_ptid (pid)));
5087       gdb_flush (gdb_stdout);
5088     }
5089
5090   /* Tell the remote target to detach.  */
5091   remote_detach_pid (pid);
5092
5093   /* Exit only if this is the only active inferior.  */
5094   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5095     puts_filtered (_("Ending remote debugging.\n"));
5096
5097   /* Check to see if we are detaching a fork parent.  Note that if we
5098      are detaching a fork child, tp == NULL.  */
5099   is_fork_parent = (tp != NULL
5100                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5101
5102   /* If doing detach-on-fork, we don't mourn, because that will delete
5103      breakpoints that should be available for the followed inferior.  */
5104   if (!is_fork_parent)
5105     target_mourn_inferior ();
5106   else
5107     {
5108       inferior_ptid = null_ptid;
5109       detach_inferior (pid);
5110     }
5111 }
5112
5113 static void
5114 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5115 {
5116   remote_detach_1 (args, from_tty);
5117 }
5118
5119 static void
5120 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5121 {
5122   remote_detach_1 (args, from_tty);
5123 }
5124
5125 /* Target follow-fork function for remote targets.  On entry, and
5126    at return, the current inferior is the fork parent.
5127
5128    Note that although this is currently only used for extended-remote,
5129    it is named remote_follow_fork in anticipation of using it for the
5130    remote target as well.  */
5131
5132 static int
5133 remote_follow_fork (struct target_ops *ops, int follow_child,
5134                     int detach_fork)
5135 {
5136   struct remote_state *rs = get_remote_state ();
5137   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5138
5139   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5140       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5141     {
5142       /* When following the parent and detaching the child, we detach
5143          the child here.  For the case of following the child and
5144          detaching the parent, the detach is done in the target-
5145          independent follow fork code in infrun.c.  We can't use
5146          target_detach when detaching an unfollowed child because
5147          the client side doesn't know anything about the child.  */
5148       if (detach_fork && !follow_child)
5149         {
5150           /* Detach the fork child.  */
5151           ptid_t child_ptid;
5152           pid_t child_pid;
5153
5154           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5155           child_pid = ptid_get_pid (child_ptid);
5156
5157           remote_detach_pid (child_pid);
5158           detach_inferior (child_pid);
5159         }
5160     }
5161   return 0;
5162 }
5163
5164 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5165    in the program space of the new inferior.  On entry and at return the
5166    current inferior is the exec'ing inferior.  INF is the new exec'd
5167    inferior, which may be the same as the exec'ing inferior unless
5168    follow-exec-mode is "new".  */
5169
5170 static void
5171 remote_follow_exec (struct target_ops *ops,
5172                     struct inferior *inf, char *execd_pathname)
5173 {
5174   /* We know that this is a target file name, so if it has the "target:"
5175      prefix we strip it off before saving it in the program space.  */
5176   if (is_target_filename (execd_pathname))
5177     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5178
5179   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5180 }
5181
5182 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5183
5184 static void
5185 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5186 {
5187   if (args)
5188     error (_("Argument given to \"disconnect\" when remotely debugging."));
5189
5190   /* Make sure we unpush even the extended remote targets.  Calling
5191      target_mourn_inferior won't unpush, and remote_mourn won't
5192      unpush if there is more than one inferior left.  */
5193   unpush_target (target);
5194   generic_mourn_inferior ();
5195
5196   if (from_tty)
5197     puts_filtered ("Ending remote debugging.\n");
5198 }
5199
5200 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5201    be chatty about it.  */
5202
5203 static void
5204 extended_remote_attach (struct target_ops *target, const char *args,
5205                         int from_tty)
5206 {
5207   struct remote_state *rs = get_remote_state ();
5208   int pid;
5209   char *wait_status = NULL;
5210
5211   pid = parse_pid_to_attach (args);
5212
5213   /* Remote PID can be freely equal to getpid, do not check it here the same
5214      way as in other targets.  */
5215
5216   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5217     error (_("This target does not support attaching to a process"));
5218
5219   if (from_tty)
5220     {
5221       char *exec_file = get_exec_file (0);
5222
5223       if (exec_file)
5224         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5225                            target_pid_to_str (pid_to_ptid (pid)));
5226       else
5227         printf_unfiltered (_("Attaching to %s\n"),
5228                            target_pid_to_str (pid_to_ptid (pid)));
5229
5230       gdb_flush (gdb_stdout);
5231     }
5232
5233   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5234   putpkt (rs->buf);
5235   getpkt (&rs->buf, &rs->buf_size, 0);
5236
5237   switch (packet_ok (rs->buf,
5238                      &remote_protocol_packets[PACKET_vAttach]))
5239     {
5240     case PACKET_OK:
5241       if (!target_is_non_stop_p ())
5242         {
5243           /* Save the reply for later.  */
5244           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5245           strcpy (wait_status, rs->buf);
5246         }
5247       else if (strcmp (rs->buf, "OK") != 0)
5248         error (_("Attaching to %s failed with: %s"),
5249                target_pid_to_str (pid_to_ptid (pid)),
5250                rs->buf);
5251       break;
5252     case PACKET_UNKNOWN:
5253       error (_("This target does not support attaching to a process"));
5254     default:
5255       error (_("Attaching to %s failed"),
5256              target_pid_to_str (pid_to_ptid (pid)));
5257     }
5258
5259   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5260
5261   inferior_ptid = pid_to_ptid (pid);
5262
5263   if (target_is_non_stop_p ())
5264     {
5265       struct thread_info *thread;
5266
5267       /* Get list of threads.  */
5268       remote_update_thread_list (target);
5269
5270       thread = first_thread_of_process (pid);
5271       if (thread)
5272         inferior_ptid = thread->ptid;
5273       else
5274         inferior_ptid = pid_to_ptid (pid);
5275
5276       /* Invalidate our notion of the remote current thread.  */
5277       record_currthread (rs, minus_one_ptid);
5278     }
5279   else
5280     {
5281       /* Now, if we have thread information, update inferior_ptid.  */
5282       inferior_ptid = remote_current_thread (inferior_ptid);
5283
5284       /* Add the main thread to the thread list.  */
5285       add_thread_silent (inferior_ptid);
5286     }
5287
5288   /* Next, if the target can specify a description, read it.  We do
5289      this before anything involving memory or registers.  */
5290   target_find_description ();
5291
5292   if (!target_is_non_stop_p ())
5293     {
5294       /* Use the previously fetched status.  */
5295       gdb_assert (wait_status != NULL);
5296
5297       if (target_can_async_p ())
5298         {
5299           struct notif_event *reply
5300             =  remote_notif_parse (&notif_client_stop, wait_status);
5301
5302           push_stop_reply ((struct stop_reply *) reply);
5303
5304           target_async (1);
5305         }
5306       else
5307         {
5308           gdb_assert (wait_status != NULL);
5309           strcpy (rs->buf, wait_status);
5310           rs->cached_wait_status = 1;
5311         }
5312     }
5313   else
5314     gdb_assert (wait_status == NULL);
5315 }
5316
5317 /* Implementation of the to_post_attach method.  */
5318
5319 static void
5320 extended_remote_post_attach (struct target_ops *ops, int pid)
5321 {
5322   /* Get text, data & bss offsets.  */
5323   get_offsets ();
5324
5325   /* In certain cases GDB might not have had the chance to start
5326      symbol lookup up until now.  This could happen if the debugged
5327      binary is not using shared libraries, the vsyscall page is not
5328      present (on Linux) and the binary itself hadn't changed since the
5329      debugging process was started.  */
5330   if (symfile_objfile != NULL)
5331     remote_check_symbols();
5332 }
5333
5334 \f
5335 /* Check for the availability of vCont.  This function should also check
5336    the response.  */
5337
5338 static void
5339 remote_vcont_probe (struct remote_state *rs)
5340 {
5341   char *buf;
5342
5343   strcpy (rs->buf, "vCont?");
5344   putpkt (rs->buf);
5345   getpkt (&rs->buf, &rs->buf_size, 0);
5346   buf = rs->buf;
5347
5348   /* Make sure that the features we assume are supported.  */
5349   if (startswith (buf, "vCont"))
5350     {
5351       char *p = &buf[5];
5352       int support_c, support_C;
5353
5354       rs->supports_vCont.s = 0;
5355       rs->supports_vCont.S = 0;
5356       support_c = 0;
5357       support_C = 0;
5358       rs->supports_vCont.t = 0;
5359       rs->supports_vCont.r = 0;
5360       while (p && *p == ';')
5361         {
5362           p++;
5363           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5364             rs->supports_vCont.s = 1;
5365           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5366             rs->supports_vCont.S = 1;
5367           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5368             support_c = 1;
5369           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5370             support_C = 1;
5371           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5372             rs->supports_vCont.t = 1;
5373           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5374             rs->supports_vCont.r = 1;
5375
5376           p = strchr (p, ';');
5377         }
5378
5379       /* If c, and C are not all supported, we can't use vCont.  Clearing
5380          BUF will make packet_ok disable the packet.  */
5381       if (!support_c || !support_C)
5382         buf[0] = 0;
5383     }
5384
5385   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5386 }
5387
5388 /* Helper function for building "vCont" resumptions.  Write a
5389    resumption to P.  ENDP points to one-passed-the-end of the buffer
5390    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5391    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5392    resumed thread should be single-stepped and/or signalled.  If PTID
5393    equals minus_one_ptid, then all threads are resumed; if PTID
5394    represents a process, then all threads of the process are resumed;
5395    the thread to be stepped and/or signalled is given in the global
5396    INFERIOR_PTID.  */
5397
5398 static char *
5399 append_resumption (char *p, char *endp,
5400                    ptid_t ptid, int step, enum gdb_signal siggnal)
5401 {
5402   struct remote_state *rs = get_remote_state ();
5403
5404   if (step && siggnal != GDB_SIGNAL_0)
5405     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5406   else if (step
5407            /* GDB is willing to range step.  */
5408            && use_range_stepping
5409            /* Target supports range stepping.  */
5410            && rs->supports_vCont.r
5411            /* We don't currently support range stepping multiple
5412               threads with a wildcard (though the protocol allows it,
5413               so stubs shouldn't make an active effort to forbid
5414               it).  */
5415            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5416     {
5417       struct thread_info *tp;
5418
5419       if (ptid_equal (ptid, minus_one_ptid))
5420         {
5421           /* If we don't know about the target thread's tid, then
5422              we're resuming magic_null_ptid (see caller).  */
5423           tp = find_thread_ptid (magic_null_ptid);
5424         }
5425       else
5426         tp = find_thread_ptid (ptid);
5427       gdb_assert (tp != NULL);
5428
5429       if (tp->control.may_range_step)
5430         {
5431           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5432
5433           p += xsnprintf (p, endp - p, ";r%s,%s",
5434                           phex_nz (tp->control.step_range_start,
5435                                    addr_size),
5436                           phex_nz (tp->control.step_range_end,
5437                                    addr_size));
5438         }
5439       else
5440         p += xsnprintf (p, endp - p, ";s");
5441     }
5442   else if (step)
5443     p += xsnprintf (p, endp - p, ";s");
5444   else if (siggnal != GDB_SIGNAL_0)
5445     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5446   else
5447     p += xsnprintf (p, endp - p, ";c");
5448
5449   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5450     {
5451       ptid_t nptid;
5452
5453       /* All (-1) threads of process.  */
5454       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5455
5456       p += xsnprintf (p, endp - p, ":");
5457       p = write_ptid (p, endp, nptid);
5458     }
5459   else if (!ptid_equal (ptid, minus_one_ptid))
5460     {
5461       p += xsnprintf (p, endp - p, ":");
5462       p = write_ptid (p, endp, ptid);
5463     }
5464
5465   return p;
5466 }
5467
5468 /* Clear the thread's private info on resume.  */
5469
5470 static void
5471 resume_clear_thread_private_info (struct thread_info *thread)
5472 {
5473   if (thread->priv != NULL)
5474     {
5475       thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5476       thread->priv->watch_data_address = 0;
5477     }
5478 }
5479
5480 /* Append a vCont continue-with-signal action for threads that have a
5481    non-zero stop signal.  */
5482
5483 static char *
5484 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5485 {
5486   struct thread_info *thread;
5487
5488   ALL_NON_EXITED_THREADS (thread)
5489     if (ptid_match (thread->ptid, ptid)
5490         && !ptid_equal (inferior_ptid, thread->ptid)
5491         && thread->suspend.stop_signal != GDB_SIGNAL_0)
5492       {
5493         p = append_resumption (p, endp, thread->ptid,
5494                                0, thread->suspend.stop_signal);
5495         thread->suspend.stop_signal = GDB_SIGNAL_0;
5496         resume_clear_thread_private_info (thread);
5497       }
5498
5499   return p;
5500 }
5501
5502 /* Resume the remote inferior by using a "vCont" packet.  The thread
5503    to be resumed is PTID; STEP and SIGGNAL indicate whether the
5504    resumed thread should be single-stepped and/or signalled.  If PTID
5505    equals minus_one_ptid, then all threads are resumed; the thread to
5506    be stepped and/or signalled is given in the global INFERIOR_PTID.
5507    This function returns non-zero iff it resumes the inferior.
5508
5509    This function issues a strict subset of all possible vCont commands at the
5510    moment.  */
5511
5512 static int
5513 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5514 {
5515   struct remote_state *rs = get_remote_state ();
5516   char *p;
5517   char *endp;
5518
5519   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5520     remote_vcont_probe (rs);
5521
5522   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5523     return 0;
5524
5525   p = rs->buf;
5526   endp = rs->buf + get_remote_packet_size ();
5527
5528   /* If we could generate a wider range of packets, we'd have to worry
5529      about overflowing BUF.  Should there be a generic
5530      "multi-part-packet" packet?  */
5531
5532   p += xsnprintf (p, endp - p, "vCont");
5533
5534   if (ptid_equal (ptid, magic_null_ptid))
5535     {
5536       /* MAGIC_NULL_PTID means that we don't have any active threads,
5537          so we don't have any TID numbers the inferior will
5538          understand.  Make sure to only send forms that do not specify
5539          a TID.  */
5540       append_resumption (p, endp, minus_one_ptid, step, siggnal);
5541     }
5542   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5543     {
5544       /* Resume all threads (of all processes, or of a single
5545          process), with preference for INFERIOR_PTID.  This assumes
5546          inferior_ptid belongs to the set of all threads we are about
5547          to resume.  */
5548       if (step || siggnal != GDB_SIGNAL_0)
5549         {
5550           /* Step inferior_ptid, with or without signal.  */
5551           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5552         }
5553
5554       /* Also pass down any pending signaled resumption for other
5555          threads not the current.  */
5556       p = append_pending_thread_resumptions (p, endp, ptid);
5557
5558       /* And continue others without a signal.  */
5559       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5560     }
5561   else
5562     {
5563       /* Scheduler locking; resume only PTID.  */
5564       append_resumption (p, endp, ptid, step, siggnal);
5565     }
5566
5567   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5568   putpkt (rs->buf);
5569
5570   if (target_is_non_stop_p ())
5571     {
5572       /* In non-stop, the stub replies to vCont with "OK".  The stop
5573          reply will be reported asynchronously by means of a `%Stop'
5574          notification.  */
5575       getpkt (&rs->buf, &rs->buf_size, 0);
5576       if (strcmp (rs->buf, "OK") != 0)
5577         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5578     }
5579
5580   return 1;
5581 }
5582
5583 /* Tell the remote machine to resume.  */
5584
5585 static void
5586 remote_resume (struct target_ops *ops,
5587                ptid_t ptid, int step, enum gdb_signal siggnal)
5588 {
5589   struct remote_state *rs = get_remote_state ();
5590   char *buf;
5591   struct thread_info *thread;
5592
5593   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5594      (explained in remote-notif.c:handle_notification) so
5595      remote_notif_process is not called.  We need find a place where
5596      it is safe to start a 'vNotif' sequence.  It is good to do it
5597      before resuming inferior, because inferior was stopped and no RSP
5598      traffic at that moment.  */
5599   if (!target_is_non_stop_p ())
5600     remote_notif_process (rs->notif_state, &notif_client_stop);
5601
5602   rs->last_sent_signal = siggnal;
5603   rs->last_sent_step = step;
5604
5605   /* The vCont packet doesn't need to specify threads via Hc.  */
5606   /* No reverse support (yet) for vCont.  */
5607   if (execution_direction != EXEC_REVERSE)
5608     if (remote_vcont_resume (ptid, step, siggnal))
5609       goto done;
5610
5611   /* All other supported resume packets do use Hc, so set the continue
5612      thread.  */
5613   if (ptid_equal (ptid, minus_one_ptid))
5614     set_continue_thread (any_thread_ptid);
5615   else
5616     set_continue_thread (ptid);
5617
5618   ALL_NON_EXITED_THREADS (thread)
5619     resume_clear_thread_private_info (thread);
5620
5621   buf = rs->buf;
5622   if (execution_direction == EXEC_REVERSE)
5623     {
5624       /* We don't pass signals to the target in reverse exec mode.  */
5625       if (info_verbose && siggnal != GDB_SIGNAL_0)
5626         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5627                  siggnal);
5628
5629       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5630         error (_("Remote reverse-step not supported."));
5631       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5632         error (_("Remote reverse-continue not supported."));
5633
5634       strcpy (buf, step ? "bs" : "bc");
5635     }
5636   else if (siggnal != GDB_SIGNAL_0)
5637     {
5638       buf[0] = step ? 'S' : 'C';
5639       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5640       buf[2] = tohex (((int) siggnal) & 0xf);
5641       buf[3] = '\0';
5642     }
5643   else
5644     strcpy (buf, step ? "s" : "c");
5645
5646   putpkt (buf);
5647
5648  done:
5649   /* We are about to start executing the inferior, let's register it
5650      with the event loop.  NOTE: this is the one place where all the
5651      execution commands end up.  We could alternatively do this in each
5652      of the execution commands in infcmd.c.  */
5653   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5654      into infcmd.c in order to allow inferior function calls to work
5655      NOT asynchronously.  */
5656   if (target_can_async_p ())
5657     target_async (1);
5658
5659   /* We've just told the target to resume.  The remote server will
5660      wait for the inferior to stop, and then send a stop reply.  In
5661      the mean time, we can't start another command/query ourselves
5662      because the stub wouldn't be ready to process it.  This applies
5663      only to the base all-stop protocol, however.  In non-stop (which
5664      only supports vCont), the stub replies with an "OK", and is
5665      immediate able to process further serial input.  */
5666   if (!target_is_non_stop_p ())
5667     rs->waiting_for_stop_reply = 1;
5668 }
5669 \f
5670
5671 /* Set up the signal handler for SIGINT, while the target is
5672    executing, ovewriting the 'regular' SIGINT signal handler.  */
5673 static void
5674 async_initialize_sigint_signal_handler (void)
5675 {
5676   signal (SIGINT, async_handle_remote_sigint);
5677 }
5678
5679 /* Signal handler for SIGINT, while the target is executing.  */
5680 static void
5681 async_handle_remote_sigint (int sig)
5682 {
5683   signal (sig, async_handle_remote_sigint_twice);
5684   /* Note we need to go through gdb_call_async_signal_handler in order
5685      to wake up the event loop on Windows.  */
5686   gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5687 }
5688
5689 /* Signal handler for SIGINT, installed after SIGINT has already been
5690    sent once.  It will take effect the second time that the user sends
5691    a ^C.  */
5692 static void
5693 async_handle_remote_sigint_twice (int sig)
5694 {
5695   signal (sig, async_handle_remote_sigint);
5696   /* See note in async_handle_remote_sigint.  */
5697   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5698 }
5699
5700 /* Implementation of to_check_pending_interrupt.  */
5701
5702 static void
5703 remote_check_pending_interrupt (struct target_ops *self)
5704 {
5705   struct async_signal_handler *token = async_sigint_remote_twice_token;
5706
5707   if (async_signal_handler_is_marked (token))
5708     {
5709       clear_async_signal_handler (token);
5710       call_async_signal_handler (token);
5711     }
5712 }
5713
5714 /* Perform the real interruption of the target execution, in response
5715    to a ^C.  */
5716 static void
5717 async_remote_interrupt (gdb_client_data arg)
5718 {
5719   if (remote_debug)
5720     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5721
5722   target_interrupt (inferior_ptid);
5723 }
5724
5725 /* Perform interrupt, if the first attempt did not succeed.  Just give
5726    up on the target alltogether.  */
5727 static void
5728 async_remote_interrupt_twice (gdb_client_data arg)
5729 {
5730   if (remote_debug)
5731     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5732
5733   interrupt_query ();
5734 }
5735
5736 /* Reinstall the usual SIGINT handlers, after the target has
5737    stopped.  */
5738 static void
5739 async_cleanup_sigint_signal_handler (void *dummy)
5740 {
5741   signal (SIGINT, handle_sigint);
5742 }
5743
5744 /* Send ^C to target to halt it.  Target will respond, and send us a
5745    packet.  */
5746 static void (*ofunc) (int);
5747
5748 /* The command line interface's interrupt routine.  This function is installed
5749    as a signal handler for SIGINT.  The first time a user requests an
5750    interrupt, we call remote_interrupt to send a break or ^C.  If there is no
5751    response from the target (it didn't stop when the user requested it),
5752    we ask the user if he'd like to detach from the target.  */
5753
5754 static void
5755 sync_remote_interrupt (int signo)
5756 {
5757   /* If this doesn't work, try more severe steps.  */
5758   signal (signo, sync_remote_interrupt_twice);
5759
5760   gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5761 }
5762
5763 /* The user typed ^C twice.  */
5764
5765 static void
5766 sync_remote_interrupt_twice (int signo)
5767 {
5768   signal (signo, ofunc);
5769   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5770   signal (signo, sync_remote_interrupt);
5771 }
5772
5773 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
5774    thread, all threads of a remote process, or all threads of all
5775    processes.  */
5776
5777 static void
5778 remote_stop_ns (ptid_t ptid)
5779 {
5780   struct remote_state *rs = get_remote_state ();
5781   char *p = rs->buf;
5782   char *endp = rs->buf + get_remote_packet_size ();
5783
5784   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5785     remote_vcont_probe (rs);
5786
5787   if (!rs->supports_vCont.t)
5788     error (_("Remote server does not support stopping threads"));
5789
5790   if (ptid_equal (ptid, minus_one_ptid)
5791       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5792     p += xsnprintf (p, endp - p, "vCont;t");
5793   else
5794     {
5795       ptid_t nptid;
5796
5797       p += xsnprintf (p, endp - p, "vCont;t:");
5798
5799       if (ptid_is_pid (ptid))
5800           /* All (-1) threads of process.  */
5801         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5802       else
5803         {
5804           /* Small optimization: if we already have a stop reply for
5805              this thread, no use in telling the stub we want this
5806              stopped.  */
5807           if (peek_stop_reply (ptid))
5808             return;
5809
5810           nptid = ptid;
5811         }
5812
5813       write_ptid (p, endp, nptid);
5814     }
5815
5816   /* In non-stop, we get an immediate OK reply.  The stop reply will
5817      come in asynchronously by notification.  */
5818   putpkt (rs->buf);
5819   getpkt (&rs->buf, &rs->buf_size, 0);
5820   if (strcmp (rs->buf, "OK") != 0)
5821     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5822 }
5823
5824 /* All-stop version of target_interrupt.  Sends a break or a ^C to
5825    interrupt the remote target.  It is undefined which thread of which
5826    process reports the interrupt.  */
5827
5828 static void
5829 remote_interrupt_as (void)
5830 {
5831   struct remote_state *rs = get_remote_state ();
5832
5833   rs->ctrlc_pending_p = 1;
5834
5835   /* If the inferior is stopped already, but the core didn't know
5836      about it yet, just ignore the request.  The cached wait status
5837      will be collected in remote_wait.  */
5838   if (rs->cached_wait_status)
5839     return;
5840
5841   /* Send interrupt_sequence to remote target.  */
5842   send_interrupt_sequence ();
5843 }
5844
5845 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
5846    the remote target.  It is undefined which thread of which process
5847    reports the interrupt.  Returns true if the packet is supported by
5848    the server, false otherwise.  */
5849
5850 static int
5851 remote_interrupt_ns (void)
5852 {
5853   struct remote_state *rs = get_remote_state ();
5854   char *p = rs->buf;
5855   char *endp = rs->buf + get_remote_packet_size ();
5856
5857   xsnprintf (p, endp - p, "vCtrlC");
5858
5859   /* In non-stop, we get an immediate OK reply.  The stop reply will
5860      come in asynchronously by notification.  */
5861   putpkt (rs->buf);
5862   getpkt (&rs->buf, &rs->buf_size, 0);
5863
5864   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5865     {
5866     case PACKET_OK:
5867       break;
5868     case PACKET_UNKNOWN:
5869       return 0;
5870     case PACKET_ERROR:
5871       error (_("Interrupting target failed: %s"), rs->buf);
5872     }
5873
5874   return 1;
5875 }
5876
5877 /* Implement the to_stop function for the remote targets.  */
5878
5879 static void
5880 remote_stop (struct target_ops *self, ptid_t ptid)
5881 {
5882   if (remote_debug)
5883     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5884
5885   if (target_is_non_stop_p ())
5886     remote_stop_ns (ptid);
5887   else
5888     {
5889       /* We don't currently have a way to transparently pause the
5890          remote target in all-stop mode.  Interrupt it instead.  */
5891       remote_interrupt_as ();
5892     }
5893 }
5894
5895 /* Implement the to_interrupt function for the remote targets.  */
5896
5897 static void
5898 remote_interrupt (struct target_ops *self, ptid_t ptid)
5899 {
5900   if (remote_debug)
5901     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5902
5903   if (non_stop)
5904     {
5905       /* In non-stop mode, we always stop with no signal instead.  */
5906       remote_stop_ns (ptid);
5907     }
5908   else
5909     {
5910       /* In all-stop, we emulate ^C-ing the remote target's
5911          terminal.  */
5912       if (target_is_non_stop_p ())
5913         {
5914           if (!remote_interrupt_ns ())
5915             {
5916               /* No support for ^C-ing the remote target.  Stop it
5917                  (with no signal) instead.  */
5918               remote_stop_ns (ptid);
5919             }
5920         }
5921       else
5922         remote_interrupt_as ();
5923     }
5924 }
5925
5926 /* Ask the user what to do when an interrupt is received.  */
5927
5928 static void
5929 interrupt_query (void)
5930 {
5931   struct remote_state *rs = get_remote_state ();
5932   struct cleanup *old_chain;
5933
5934   old_chain = make_cleanup_restore_target_terminal ();
5935   target_terminal_ours ();
5936
5937   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5938     {
5939       if (query (_("The target is not responding to interrupt requests.\n"
5940                    "Stop debugging it? ")))
5941         {
5942           remote_unpush_target ();
5943           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5944         }
5945     }
5946   else
5947     {
5948       if (query (_("Interrupted while waiting for the program.\n"
5949                    "Give up waiting? ")))
5950         quit ();
5951     }
5952
5953   do_cleanups (old_chain);
5954 }
5955
5956 /* Enable/disable target terminal ownership.  Most targets can use
5957    terminal groups to control terminal ownership.  Remote targets are
5958    different in that explicit transfer of ownership to/from GDB/target
5959    is required.  */
5960
5961 static void
5962 remote_terminal_inferior (struct target_ops *self)
5963 {
5964   if (!target_async_permitted)
5965     /* Nothing to do.  */
5966     return;
5967
5968   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5969      idempotent.  The event-loop GDB talking to an asynchronous target
5970      with a synchronous command calls this function from both
5971      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
5972      transfer the terminal to the target when it shouldn't this guard
5973      can go away.  */
5974   if (!remote_async_terminal_ours_p)
5975     return;
5976   delete_file_handler (input_fd);
5977   remote_async_terminal_ours_p = 0;
5978   async_initialize_sigint_signal_handler ();
5979   /* NOTE: At this point we could also register our selves as the
5980      recipient of all input.  Any characters typed could then be
5981      passed on down to the target.  */
5982 }
5983
5984 static void
5985 remote_terminal_ours (struct target_ops *self)
5986 {
5987   if (!target_async_permitted)
5988     /* Nothing to do.  */
5989     return;
5990
5991   /* See FIXME in remote_terminal_inferior.  */
5992   if (remote_async_terminal_ours_p)
5993     return;
5994   async_cleanup_sigint_signal_handler (NULL);
5995   add_file_handler (input_fd, stdin_event_handler, 0);
5996   remote_async_terminal_ours_p = 1;
5997 }
5998
5999 static void
6000 remote_console_output (char *msg)
6001 {
6002   char *p;
6003
6004   for (p = msg; p[0] && p[1]; p += 2)
6005     {
6006       char tb[2];
6007       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6008
6009       tb[0] = c;
6010       tb[1] = 0;
6011       fputs_unfiltered (tb, gdb_stdtarg);
6012     }
6013   gdb_flush (gdb_stdtarg);
6014 }
6015
6016 typedef struct cached_reg
6017 {
6018   int num;
6019   gdb_byte data[MAX_REGISTER_SIZE];
6020 } cached_reg_t;
6021
6022 DEF_VEC_O(cached_reg_t);
6023
6024 typedef struct stop_reply
6025 {
6026   struct notif_event base;
6027
6028   /* The identifier of the thread about this event  */
6029   ptid_t ptid;
6030
6031   /* The remote state this event is associated with.  When the remote
6032      connection, represented by a remote_state object, is closed,
6033      all the associated stop_reply events should be released.  */
6034   struct remote_state *rs;
6035
6036   struct target_waitstatus ws;
6037
6038   /* Expedited registers.  This makes remote debugging a bit more
6039      efficient for those targets that provide critical registers as
6040      part of their normal status mechanism (as another roundtrip to
6041      fetch them is avoided).  */
6042   VEC(cached_reg_t) *regcache;
6043
6044   enum target_stop_reason stop_reason;
6045
6046   CORE_ADDR watch_data_address;
6047
6048   int core;
6049 } *stop_reply_p;
6050
6051 DECLARE_QUEUE_P (stop_reply_p);
6052 DEFINE_QUEUE_P (stop_reply_p);
6053 /* The list of already fetched and acknowledged stop events.  This
6054    queue is used for notification Stop, and other notifications
6055    don't need queue for their events, because the notification events
6056    of Stop can't be consumed immediately, so that events should be
6057    queued first, and be consumed by remote_wait_{ns,as} one per
6058    time.  Other notifications can consume their events immediately,
6059    so queue is not needed for them.  */
6060 static QUEUE (stop_reply_p) *stop_reply_queue;
6061
6062 static void
6063 stop_reply_xfree (struct stop_reply *r)
6064 {
6065   notif_event_xfree ((struct notif_event *) r);
6066 }
6067
6068 /* Return the length of the stop reply queue.  */
6069
6070 static int
6071 stop_reply_queue_length (void)
6072 {
6073   return QUEUE_length (stop_reply_p, stop_reply_queue);
6074 }
6075
6076 static void
6077 remote_notif_stop_parse (struct notif_client *self, char *buf,
6078                          struct notif_event *event)
6079 {
6080   remote_parse_stop_reply (buf, (struct stop_reply *) event);
6081 }
6082
6083 static void
6084 remote_notif_stop_ack (struct notif_client *self, char *buf,
6085                        struct notif_event *event)
6086 {
6087   struct stop_reply *stop_reply = (struct stop_reply *) event;
6088
6089   /* acknowledge */
6090   putpkt ((char *) self->ack_command);
6091
6092   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6093       /* We got an unknown stop reply.  */
6094       error (_("Unknown stop reply"));
6095
6096   push_stop_reply (stop_reply);
6097 }
6098
6099 static int
6100 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6101 {
6102   /* We can't get pending events in remote_notif_process for
6103      notification stop, and we have to do this in remote_wait_ns
6104      instead.  If we fetch all queued events from stub, remote stub
6105      may exit and we have no chance to process them back in
6106      remote_wait_ns.  */
6107   mark_async_event_handler (remote_async_inferior_event_token);
6108   return 0;
6109 }
6110
6111 static void
6112 stop_reply_dtr (struct notif_event *event)
6113 {
6114   struct stop_reply *r = (struct stop_reply *) event;
6115
6116   VEC_free (cached_reg_t, r->regcache);
6117 }
6118
6119 static struct notif_event *
6120 remote_notif_stop_alloc_reply (void)
6121 {
6122   /* We cast to a pointer to the "base class".  */
6123   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6124
6125   r->dtr = stop_reply_dtr;
6126
6127   return r;
6128 }
6129
6130 /* A client of notification Stop.  */
6131
6132 struct notif_client notif_client_stop =
6133 {
6134   "Stop",
6135   "vStopped",
6136   remote_notif_stop_parse,
6137   remote_notif_stop_ack,
6138   remote_notif_stop_can_get_pending_events,
6139   remote_notif_stop_alloc_reply,
6140   REMOTE_NOTIF_STOP,
6141 };
6142
6143 /* A parameter to pass data in and out.  */
6144
6145 struct queue_iter_param
6146 {
6147   void *input;
6148   struct stop_reply *output;
6149 };
6150
6151 /* Determine if THREAD is a pending fork parent thread.  ARG contains
6152    the pid of the process that owns the threads we want to check, or
6153    -1 if we want to check all threads.  */
6154
6155 static int
6156 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6157                         ptid_t thread_ptid)
6158 {
6159   if (ws->kind == TARGET_WAITKIND_FORKED
6160       || ws->kind == TARGET_WAITKIND_VFORKED)
6161     {
6162       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6163         return 1;
6164     }
6165
6166   return 0;
6167 }
6168
6169 /* Check whether EVENT is a fork event, and if it is, remove the
6170    fork child from the context list passed in DATA.  */
6171
6172 static int
6173 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6174                               QUEUE_ITER (stop_reply_p) *iter,
6175                               stop_reply_p event,
6176                               void *data)
6177 {
6178   struct queue_iter_param *param = (struct queue_iter_param *) data;
6179   struct threads_listing_context *context
6180     = (struct threads_listing_context *) param->input;
6181
6182   if (event->ws.kind == TARGET_WAITKIND_FORKED
6183       || event->ws.kind == TARGET_WAITKIND_VFORKED
6184       || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6185     threads_listing_context_remove (&event->ws, context);
6186
6187   return 1;
6188 }
6189
6190 /* If CONTEXT contains any fork child threads that have not been
6191    reported yet, remove them from the CONTEXT list.  If such a
6192    thread exists it is because we are stopped at a fork catchpoint
6193    and have not yet called follow_fork, which will set up the
6194    host-side data structures for the new process.  */
6195
6196 static void
6197 remove_new_fork_children (struct threads_listing_context *context)
6198 {
6199   struct thread_info * thread;
6200   int pid = -1;
6201   struct notif_client *notif = &notif_client_stop;
6202   struct queue_iter_param param;
6203
6204   /* For any threads stopped at a fork event, remove the corresponding
6205      fork child threads from the CONTEXT list.  */
6206   ALL_NON_EXITED_THREADS (thread)
6207     {
6208       struct target_waitstatus *ws;
6209
6210       if (thread->suspend.waitstatus_pending_p)
6211         ws = &thread->suspend.waitstatus;
6212       else
6213         ws = &thread->pending_follow;
6214
6215       if (is_pending_fork_parent (ws, pid, thread->ptid))
6216         {
6217           threads_listing_context_remove (ws, context);
6218         }
6219     }
6220
6221   /* Check for any pending fork events (not reported or processed yet)
6222      in process PID and remove those fork child threads from the
6223      CONTEXT list as well.  */
6224   remote_notif_get_pending_events (notif);
6225   param.input = context;
6226   param.output = NULL;
6227   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6228                  remove_child_of_pending_fork, &param);
6229 }
6230
6231 /* Remove stop replies in the queue if its pid is equal to the given
6232    inferior's pid.  */
6233
6234 static int
6235 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6236                                 QUEUE_ITER (stop_reply_p) *iter,
6237                                 stop_reply_p event,
6238                                 void *data)
6239 {
6240   struct queue_iter_param *param = (struct queue_iter_param *) data;
6241   struct inferior *inf = (struct inferior *) param->input;
6242
6243   if (ptid_get_pid (event->ptid) == inf->pid)
6244     {
6245       stop_reply_xfree (event);
6246       QUEUE_remove_elem (stop_reply_p, q, iter);
6247     }
6248
6249   return 1;
6250 }
6251
6252 /* Discard all pending stop replies of inferior INF.  */
6253
6254 static void
6255 discard_pending_stop_replies (struct inferior *inf)
6256 {
6257   struct queue_iter_param param;
6258   struct stop_reply *reply;
6259   struct remote_state *rs = get_remote_state ();
6260   struct remote_notif_state *rns = rs->notif_state;
6261
6262   /* This function can be notified when an inferior exists.  When the
6263      target is not remote, the notification state is NULL.  */
6264   if (rs->remote_desc == NULL)
6265     return;
6266
6267   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6268
6269   /* Discard the in-flight notification.  */
6270   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6271     {
6272       stop_reply_xfree (reply);
6273       rns->pending_event[notif_client_stop.id] = NULL;
6274     }
6275
6276   param.input = inf;
6277   param.output = NULL;
6278   /* Discard the stop replies we have already pulled with
6279      vStopped.  */
6280   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6281                  remove_stop_reply_for_inferior, &param);
6282 }
6283
6284 /* If its remote state is equal to the given remote state,
6285    remove EVENT from the stop reply queue.  */
6286
6287 static int
6288 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6289                                    QUEUE_ITER (stop_reply_p) *iter,
6290                                    stop_reply_p event,
6291                                    void *data)
6292 {
6293   struct queue_iter_param *param = (struct queue_iter_param *) data;
6294   struct remote_state *rs = (struct remote_state *) param->input;
6295
6296   if (event->rs == rs)
6297     {
6298       stop_reply_xfree (event);
6299       QUEUE_remove_elem (stop_reply_p, q, iter);
6300     }
6301
6302   return 1;
6303 }
6304
6305 /* Discard the stop replies for RS in stop_reply_queue.  */
6306
6307 static void
6308 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6309 {
6310   struct queue_iter_param param;
6311
6312   param.input = rs;
6313   param.output = NULL;
6314   /* Discard the stop replies we have already pulled with
6315      vStopped.  */
6316   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6317                  remove_stop_reply_of_remote_state, &param);
6318 }
6319
6320 /* A parameter to pass data in and out.  */
6321
6322 static int
6323 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6324                                    QUEUE_ITER (stop_reply_p) *iter,
6325                                    stop_reply_p event,
6326                                    void *data)
6327 {
6328   struct queue_iter_param *param = (struct queue_iter_param *) data;
6329   ptid_t *ptid = (ptid_t *) param->input;
6330
6331   if (ptid_match (event->ptid, *ptid))
6332     {
6333       param->output = event;
6334       QUEUE_remove_elem (stop_reply_p, q, iter);
6335       return 0;
6336     }
6337
6338   return 1;
6339 }
6340
6341 /* Remove the first reply in 'stop_reply_queue' which matches
6342    PTID.  */
6343
6344 static struct stop_reply *
6345 remote_notif_remove_queued_reply (ptid_t ptid)
6346 {
6347   struct queue_iter_param param;
6348
6349   param.input = &ptid;
6350   param.output = NULL;
6351
6352   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6353                  remote_notif_remove_once_on_match, &param);
6354   if (notif_debug)
6355     fprintf_unfiltered (gdb_stdlog,
6356                         "notif: discard queued event: 'Stop' in %s\n",
6357                         target_pid_to_str (ptid));
6358
6359   return param.output;
6360 }
6361
6362 /* Look for a queued stop reply belonging to PTID.  If one is found,
6363    remove it from the queue, and return it.  Returns NULL if none is
6364    found.  If there are still queued events left to process, tell the
6365    event loop to get back to target_wait soon.  */
6366
6367 static struct stop_reply *
6368 queued_stop_reply (ptid_t ptid)
6369 {
6370   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6371
6372   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6373     /* There's still at least an event left.  */
6374     mark_async_event_handler (remote_async_inferior_event_token);
6375
6376   return r;
6377 }
6378
6379 /* Push a fully parsed stop reply in the stop reply queue.  Since we
6380    know that we now have at least one queued event left to pass to the
6381    core side, tell the event loop to get back to target_wait soon.  */
6382
6383 static void
6384 push_stop_reply (struct stop_reply *new_event)
6385 {
6386   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6387
6388   if (notif_debug)
6389     fprintf_unfiltered (gdb_stdlog,
6390                         "notif: push 'Stop' %s to queue %d\n",
6391                         target_pid_to_str (new_event->ptid),
6392                         QUEUE_length (stop_reply_p,
6393                                       stop_reply_queue));
6394
6395   mark_async_event_handler (remote_async_inferior_event_token);
6396 }
6397
6398 static int
6399 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6400                               QUEUE_ITER (stop_reply_p) *iter,
6401                               struct stop_reply *event,
6402                               void *data)
6403 {
6404   ptid_t *ptid = (ptid_t *) data;
6405
6406   return !(ptid_equal (*ptid, event->ptid)
6407            && event->ws.kind == TARGET_WAITKIND_STOPPED);
6408 }
6409
6410 /* Returns true if we have a stop reply for PTID.  */
6411
6412 static int
6413 peek_stop_reply (ptid_t ptid)
6414 {
6415   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6416                          stop_reply_match_ptid_and_ws, &ptid);
6417 }
6418
6419 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
6420    starting with P and ending with PEND matches PREFIX.  */
6421
6422 static int
6423 strprefix (const char *p, const char *pend, const char *prefix)
6424 {
6425   for ( ; p < pend; p++, prefix++)
6426     if (*p != *prefix)
6427       return 0;
6428   return *prefix == '\0';
6429 }
6430
6431 /* Parse the stop reply in BUF.  Either the function succeeds, and the
6432    result is stored in EVENT, or throws an error.  */
6433
6434 static void
6435 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6436 {
6437   struct remote_arch_state *rsa = get_remote_arch_state ();
6438   ULONGEST addr;
6439   char *p;
6440   int skipregs = 0;
6441
6442   event->ptid = null_ptid;
6443   event->rs = get_remote_state ();
6444   event->ws.kind = TARGET_WAITKIND_IGNORE;
6445   event->ws.value.integer = 0;
6446   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6447   event->regcache = NULL;
6448   event->core = -1;
6449
6450   switch (buf[0])
6451     {
6452     case 'T':           /* Status with PC, SP, FP, ...  */
6453       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
6454       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
6455             ss = signal number
6456             n... = register number
6457             r... = register contents
6458       */
6459
6460       p = &buf[3];      /* after Txx */
6461       while (*p)
6462         {
6463           char *p1;
6464           int fieldsize;
6465
6466           p1 = strchr (p, ':');
6467           if (p1 == NULL)
6468             error (_("Malformed packet(a) (missing colon): %s\n\
6469 Packet: '%s'\n"),
6470                    p, buf);
6471           if (p == p1)
6472             error (_("Malformed packet(a) (missing register number): %s\n\
6473 Packet: '%s'\n"),
6474                    p, buf);
6475
6476           /* Some "registers" are actually extended stop information.
6477              Note if you're adding a new entry here: GDB 7.9 and
6478              earlier assume that all register "numbers" that start
6479              with an hex digit are real register numbers.  Make sure
6480              the server only sends such a packet if it knows the
6481              client understands it.  */
6482
6483           if (strprefix (p, p1, "thread"))
6484             event->ptid = read_ptid (++p1, &p);
6485           else if (strprefix (p, p1, "syscall_entry"))
6486             {
6487               ULONGEST sysno;
6488
6489               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6490               p = unpack_varlen_hex (++p1, &sysno);
6491               event->ws.value.syscall_number = (int) sysno;
6492             }
6493           else if (strprefix (p, p1, "syscall_return"))
6494             {
6495               ULONGEST sysno;
6496
6497               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6498               p = unpack_varlen_hex (++p1, &sysno);
6499               event->ws.value.syscall_number = (int) sysno;
6500             }
6501           else if (strprefix (p, p1, "watch")
6502                    || strprefix (p, p1, "rwatch")
6503                    || strprefix (p, p1, "awatch"))
6504             {
6505               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6506               p = unpack_varlen_hex (++p1, &addr);
6507               event->watch_data_address = (CORE_ADDR) addr;
6508             }
6509           else if (strprefix (p, p1, "swbreak"))
6510             {
6511               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6512
6513               /* Make sure the stub doesn't forget to indicate support
6514                  with qSupported.  */
6515               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6516                 error (_("Unexpected swbreak stop reason"));
6517
6518               /* The value part is documented as "must be empty",
6519                  though we ignore it, in case we ever decide to make
6520                  use of it in a backward compatible way.  */
6521               p = strchrnul (p1 + 1, ';');
6522             }
6523           else if (strprefix (p, p1, "hwbreak"))
6524             {
6525               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6526
6527               /* Make sure the stub doesn't forget to indicate support
6528                  with qSupported.  */
6529               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6530                 error (_("Unexpected hwbreak stop reason"));
6531
6532               /* See above.  */
6533               p = strchrnul (p1 + 1, ';');
6534             }
6535           else if (strprefix (p, p1, "library"))
6536             {
6537               event->ws.kind = TARGET_WAITKIND_LOADED;
6538               p = strchrnul (p1 + 1, ';');
6539             }
6540           else if (strprefix (p, p1, "replaylog"))
6541             {
6542               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6543               /* p1 will indicate "begin" or "end", but it makes
6544                  no difference for now, so ignore it.  */
6545               p = strchrnul (p1 + 1, ';');
6546             }
6547           else if (strprefix (p, p1, "core"))
6548             {
6549               ULONGEST c;
6550
6551               p = unpack_varlen_hex (++p1, &c);
6552               event->core = c;
6553             }
6554           else if (strprefix (p, p1, "fork"))
6555             {
6556               event->ws.value.related_pid = read_ptid (++p1, &p);
6557               event->ws.kind = TARGET_WAITKIND_FORKED;
6558             }
6559           else if (strprefix (p, p1, "vfork"))
6560             {
6561               event->ws.value.related_pid = read_ptid (++p1, &p);
6562               event->ws.kind = TARGET_WAITKIND_VFORKED;
6563             }
6564           else if (strprefix (p, p1, "vforkdone"))
6565             {
6566               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6567               p = strchrnul (p1 + 1, ';');
6568             }
6569           else if (strprefix (p, p1, "exec"))
6570             {
6571               ULONGEST ignored;
6572               char pathname[PATH_MAX];
6573               int pathlen;
6574
6575               /* Determine the length of the execd pathname.  */
6576               p = unpack_varlen_hex (++p1, &ignored);
6577               pathlen = (p - p1) / 2;
6578
6579               /* Save the pathname for event reporting and for
6580                  the next run command.  */
6581               hex2bin (p1, (gdb_byte *) pathname, pathlen);
6582               pathname[pathlen] = '\0';
6583
6584               /* This is freed during event handling.  */
6585               event->ws.value.execd_pathname = xstrdup (pathname);
6586               event->ws.kind = TARGET_WAITKIND_EXECD;
6587
6588               /* Skip the registers included in this packet, since
6589                  they may be for an architecture different from the
6590                  one used by the original program.  */
6591               skipregs = 1;
6592             }
6593           else if (strprefix (p, p1, "create"))
6594             {
6595               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6596               p = strchrnul (p1 + 1, ';');
6597             }
6598           else
6599             {
6600               ULONGEST pnum;
6601               char *p_temp;
6602
6603               if (skipregs)
6604                 {
6605                   p = strchrnul (p1 + 1, ';');
6606                   p++;
6607                   continue;
6608                 }
6609
6610               /* Maybe a real ``P'' register number.  */
6611               p_temp = unpack_varlen_hex (p, &pnum);
6612               /* If the first invalid character is the colon, we got a
6613                  register number.  Otherwise, it's an unknown stop
6614                  reason.  */
6615               if (p_temp == p1)
6616                 {
6617                   struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6618                   cached_reg_t cached_reg;
6619
6620                   if (reg == NULL)
6621                     error (_("Remote sent bad register number %s: %s\n\
6622 Packet: '%s'\n"),
6623                            hex_string (pnum), p, buf);
6624
6625                   cached_reg.num = reg->regnum;
6626
6627                   p = p1 + 1;
6628                   fieldsize = hex2bin (p, cached_reg.data,
6629                                        register_size (target_gdbarch (),
6630                                                       reg->regnum));
6631                   p += 2 * fieldsize;
6632                   if (fieldsize < register_size (target_gdbarch (),
6633                                                  reg->regnum))
6634                     warning (_("Remote reply is too short: %s"), buf);
6635
6636                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6637                 }
6638               else
6639                 {
6640                   /* Not a number.  Silently skip unknown optional
6641                      info.  */
6642                   p = strchrnul (p1 + 1, ';');
6643                 }
6644             }
6645
6646           if (*p != ';')
6647             error (_("Remote register badly formatted: %s\nhere: %s"),
6648                    buf, p);
6649           ++p;
6650         }
6651
6652       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6653         break;
6654
6655       /* fall through */
6656     case 'S':           /* Old style status, just signal only.  */
6657       {
6658         int sig;
6659
6660         event->ws.kind = TARGET_WAITKIND_STOPPED;
6661         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6662         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6663           event->ws.value.sig = (enum gdb_signal) sig;
6664         else
6665           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6666       }
6667       break;
6668     case 'w':           /* Thread exited.  */
6669       {
6670         char *p;
6671         ULONGEST value;
6672
6673         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6674         p = unpack_varlen_hex (&buf[1], &value);
6675         event->ws.value.integer = value;
6676         if (*p != ';')
6677           error (_("stop reply packet badly formatted: %s"), buf);
6678         event->ptid = read_ptid (++p, NULL);
6679         break;
6680       }
6681     case 'W':           /* Target exited.  */
6682     case 'X':
6683       {
6684         char *p;
6685         int pid;
6686         ULONGEST value;
6687
6688         /* GDB used to accept only 2 hex chars here.  Stubs should
6689            only send more if they detect GDB supports multi-process
6690            support.  */
6691         p = unpack_varlen_hex (&buf[1], &value);
6692
6693         if (buf[0] == 'W')
6694           {
6695             /* The remote process exited.  */
6696             event->ws.kind = TARGET_WAITKIND_EXITED;
6697             event->ws.value.integer = value;
6698           }
6699         else
6700           {
6701             /* The remote process exited with a signal.  */
6702             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6703             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6704               event->ws.value.sig = (enum gdb_signal) value;
6705             else
6706               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6707           }
6708
6709         /* If no process is specified, assume inferior_ptid.  */
6710         pid = ptid_get_pid (inferior_ptid);
6711         if (*p == '\0')
6712           ;
6713         else if (*p == ';')
6714           {
6715             p++;
6716
6717             if (*p == '\0')
6718               ;
6719             else if (startswith (p, "process:"))
6720               {
6721                 ULONGEST upid;
6722
6723                 p += sizeof ("process:") - 1;
6724                 unpack_varlen_hex (p, &upid);
6725                 pid = upid;
6726               }
6727             else
6728               error (_("unknown stop reply packet: %s"), buf);
6729           }
6730         else
6731           error (_("unknown stop reply packet: %s"), buf);
6732         event->ptid = pid_to_ptid (pid);
6733       }
6734       break;
6735     case 'N':
6736       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6737       event->ptid = minus_one_ptid;
6738       break;
6739     }
6740
6741   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6742     error (_("No process or thread specified in stop reply: %s"), buf);
6743 }
6744
6745 /* When the stub wants to tell GDB about a new notification reply, it
6746    sends a notification (%Stop, for example).  Those can come it at
6747    any time, hence, we have to make sure that any pending
6748    putpkt/getpkt sequence we're making is finished, before querying
6749    the stub for more events with the corresponding ack command
6750    (vStopped, for example).  E.g., if we started a vStopped sequence
6751    immediately upon receiving the notification, something like this
6752    could happen:
6753
6754     1.1) --> Hg 1
6755     1.2) <-- OK
6756     1.3) --> g
6757     1.4) <-- %Stop
6758     1.5) --> vStopped
6759     1.6) <-- (registers reply to step #1.3)
6760
6761    Obviously, the reply in step #1.6 would be unexpected to a vStopped
6762    query.
6763
6764    To solve this, whenever we parse a %Stop notification successfully,
6765    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6766    doing whatever we were doing:
6767
6768     2.1) --> Hg 1
6769     2.2) <-- OK
6770     2.3) --> g
6771     2.4) <-- %Stop
6772       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6773     2.5) <-- (registers reply to step #2.3)
6774
6775    Eventualy after step #2.5, we return to the event loop, which
6776    notices there's an event on the
6777    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6778    associated callback --- the function below.  At this point, we're
6779    always safe to start a vStopped sequence. :
6780
6781     2.6) --> vStopped
6782     2.7) <-- T05 thread:2
6783     2.8) --> vStopped
6784     2.9) --> OK
6785 */
6786
6787 void
6788 remote_notif_get_pending_events (struct notif_client *nc)
6789 {
6790   struct remote_state *rs = get_remote_state ();
6791
6792   if (rs->notif_state->pending_event[nc->id] != NULL)
6793     {
6794       if (notif_debug)
6795         fprintf_unfiltered (gdb_stdlog,
6796                             "notif: process: '%s' ack pending event\n",
6797                             nc->name);
6798
6799       /* acknowledge */
6800       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6801       rs->notif_state->pending_event[nc->id] = NULL;
6802
6803       while (1)
6804         {
6805           getpkt (&rs->buf, &rs->buf_size, 0);
6806           if (strcmp (rs->buf, "OK") == 0)
6807             break;
6808           else
6809             remote_notif_ack (nc, rs->buf);
6810         }
6811     }
6812   else
6813     {
6814       if (notif_debug)
6815         fprintf_unfiltered (gdb_stdlog,
6816                             "notif: process: '%s' no pending reply\n",
6817                             nc->name);
6818     }
6819 }
6820
6821 /* Called when it is decided that STOP_REPLY holds the info of the
6822    event that is to be returned to the core.  This function always
6823    destroys STOP_REPLY.  */
6824
6825 static ptid_t
6826 process_stop_reply (struct stop_reply *stop_reply,
6827                     struct target_waitstatus *status)
6828 {
6829   ptid_t ptid;
6830
6831   *status = stop_reply->ws;
6832   ptid = stop_reply->ptid;
6833
6834   /* If no thread/process was reported by the stub, assume the current
6835      inferior.  */
6836   if (ptid_equal (ptid, null_ptid))
6837     ptid = inferior_ptid;
6838
6839   if (status->kind != TARGET_WAITKIND_EXITED
6840       && status->kind != TARGET_WAITKIND_SIGNALLED
6841       && status->kind != TARGET_WAITKIND_NO_RESUMED)
6842     {
6843       struct private_thread_info *remote_thr;
6844
6845       /* Expedited registers.  */
6846       if (stop_reply->regcache)
6847         {
6848           struct regcache *regcache
6849             = get_thread_arch_regcache (ptid, target_gdbarch ());
6850           cached_reg_t *reg;
6851           int ix;
6852
6853           for (ix = 0;
6854                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6855                ix++)
6856             regcache_raw_supply (regcache, reg->num, reg->data);
6857           VEC_free (cached_reg_t, stop_reply->regcache);
6858         }
6859
6860       remote_notice_new_inferior (ptid, 0);
6861       remote_thr = demand_private_info (ptid);
6862       remote_thr->core = stop_reply->core;
6863       remote_thr->stop_reason = stop_reply->stop_reason;
6864       remote_thr->watch_data_address = stop_reply->watch_data_address;
6865     }
6866
6867   stop_reply_xfree (stop_reply);
6868   return ptid;
6869 }
6870
6871 /* The non-stop mode version of target_wait.  */
6872
6873 static ptid_t
6874 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6875 {
6876   struct remote_state *rs = get_remote_state ();
6877   struct stop_reply *stop_reply;
6878   int ret;
6879   int is_notif = 0;
6880
6881   /* If in non-stop mode, get out of getpkt even if a
6882      notification is received.  */
6883
6884   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6885                               0 /* forever */, &is_notif);
6886   while (1)
6887     {
6888       if (ret != -1 && !is_notif)
6889         switch (rs->buf[0])
6890           {
6891           case 'E':             /* Error of some sort.  */
6892             /* We're out of sync with the target now.  Did it continue
6893                or not?  We can't tell which thread it was in non-stop,
6894                so just ignore this.  */
6895             warning (_("Remote failure reply: %s"), rs->buf);
6896             break;
6897           case 'O':             /* Console output.  */
6898             remote_console_output (rs->buf + 1);
6899             break;
6900           default:
6901             warning (_("Invalid remote reply: %s"), rs->buf);
6902             break;
6903           }
6904
6905       /* Acknowledge a pending stop reply that may have arrived in the
6906          mean time.  */
6907       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6908         remote_notif_get_pending_events (&notif_client_stop);
6909
6910       /* If indeed we noticed a stop reply, we're done.  */
6911       stop_reply = queued_stop_reply (ptid);
6912       if (stop_reply != NULL)
6913         return process_stop_reply (stop_reply, status);
6914
6915       /* Still no event.  If we're just polling for an event, then
6916          return to the event loop.  */
6917       if (options & TARGET_WNOHANG)
6918         {
6919           status->kind = TARGET_WAITKIND_IGNORE;
6920           return minus_one_ptid;
6921         }
6922
6923       /* Otherwise do a blocking wait.  */
6924       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6925                                   1 /* forever */, &is_notif);
6926     }
6927 }
6928
6929 /* Wait until the remote machine stops, then return, storing status in
6930    STATUS just as `wait' would.  */
6931
6932 static ptid_t
6933 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6934 {
6935   struct remote_state *rs = get_remote_state ();
6936   ptid_t event_ptid = null_ptid;
6937   char *buf;
6938   struct stop_reply *stop_reply;
6939
6940  again:
6941
6942   status->kind = TARGET_WAITKIND_IGNORE;
6943   status->value.integer = 0;
6944
6945   stop_reply = queued_stop_reply (ptid);
6946   if (stop_reply != NULL)
6947     return process_stop_reply (stop_reply, status);
6948
6949   if (rs->cached_wait_status)
6950     /* Use the cached wait status, but only once.  */
6951     rs->cached_wait_status = 0;
6952   else
6953     {
6954       int ret;
6955       int is_notif;
6956       int forever = ((options & TARGET_WNOHANG) == 0
6957                      && wait_forever_enabled_p);
6958
6959       if (!rs->waiting_for_stop_reply)
6960         {
6961           status->kind = TARGET_WAITKIND_NO_RESUMED;
6962           return minus_one_ptid;
6963         }
6964
6965       if (!target_is_async_p ())
6966         {
6967           ofunc = signal (SIGINT, sync_remote_interrupt);
6968           /* If the user hit C-c before this packet, or between packets,
6969              pretend that it was hit right here.  */
6970           if (check_quit_flag ())
6971             {
6972               clear_quit_flag ();
6973               sync_remote_interrupt (SIGINT);
6974             }
6975         }
6976
6977       /* FIXME: cagney/1999-09-27: If we're in async mode we should
6978          _never_ wait for ever -> test on target_is_async_p().
6979          However, before we do that we need to ensure that the caller
6980          knows how to take the target into/out of async mode.  */
6981       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6982                                   forever, &is_notif);
6983
6984       if (!target_is_async_p ())
6985         signal (SIGINT, ofunc);
6986
6987       /* GDB gets a notification.  Return to core as this event is
6988          not interesting.  */
6989       if (ret != -1 && is_notif)
6990         return minus_one_ptid;
6991
6992       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6993         return minus_one_ptid;
6994     }
6995
6996   buf = rs->buf;
6997
6998   /* Assume that the target has acknowledged Ctrl-C unless we receive
6999      an 'F' or 'O' packet.  */
7000   if (buf[0] != 'F' && buf[0] != 'O')
7001     rs->ctrlc_pending_p = 0;
7002
7003   switch (buf[0])
7004     {
7005     case 'E':           /* Error of some sort.  */
7006       /* We're out of sync with the target now.  Did it continue or
7007          not?  Not is more likely, so report a stop.  */
7008       rs->waiting_for_stop_reply = 0;
7009
7010       warning (_("Remote failure reply: %s"), buf);
7011       status->kind = TARGET_WAITKIND_STOPPED;
7012       status->value.sig = GDB_SIGNAL_0;
7013       break;
7014     case 'F':           /* File-I/O request.  */
7015       /* GDB may access the inferior memory while handling the File-I/O
7016          request, but we don't want GDB accessing memory while waiting
7017          for a stop reply.  See the comments in putpkt_binary.  Set
7018          waiting_for_stop_reply to 0 temporarily.  */
7019       rs->waiting_for_stop_reply = 0;
7020       remote_fileio_request (buf, rs->ctrlc_pending_p);
7021       rs->ctrlc_pending_p = 0;
7022       /* GDB handled the File-I/O request, and the target is running
7023          again.  Keep waiting for events.  */
7024       rs->waiting_for_stop_reply = 1;
7025       break;
7026     case 'N': case 'T': case 'S': case 'X': case 'W':
7027       {
7028         struct stop_reply *stop_reply;
7029
7030         /* There is a stop reply to handle.  */
7031         rs->waiting_for_stop_reply = 0;
7032
7033         stop_reply
7034           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7035                                                       rs->buf);
7036
7037         event_ptid = process_stop_reply (stop_reply, status);
7038         break;
7039       }
7040     case 'O':           /* Console output.  */
7041       remote_console_output (buf + 1);
7042       break;
7043     case '\0':
7044       if (rs->last_sent_signal != GDB_SIGNAL_0)
7045         {
7046           /* Zero length reply means that we tried 'S' or 'C' and the
7047              remote system doesn't support it.  */
7048           target_terminal_ours_for_output ();
7049           printf_filtered
7050             ("Can't send signals to this remote system.  %s not sent.\n",
7051              gdb_signal_to_name (rs->last_sent_signal));
7052           rs->last_sent_signal = GDB_SIGNAL_0;
7053           target_terminal_inferior ();
7054
7055           strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
7056           putpkt ((char *) buf);
7057           break;
7058         }
7059       /* else fallthrough */
7060     default:
7061       warning (_("Invalid remote reply: %s"), buf);
7062       break;
7063     }
7064
7065   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7066     return minus_one_ptid;
7067   else if (status->kind == TARGET_WAITKIND_IGNORE)
7068     {
7069       /* Nothing interesting happened.  If we're doing a non-blocking
7070          poll, we're done.  Otherwise, go back to waiting.  */
7071       if (options & TARGET_WNOHANG)
7072         return minus_one_ptid;
7073       else
7074         goto again;
7075     }
7076   else if (status->kind != TARGET_WAITKIND_EXITED
7077            && status->kind != TARGET_WAITKIND_SIGNALLED)
7078     {
7079       if (!ptid_equal (event_ptid, null_ptid))
7080         record_currthread (rs, event_ptid);
7081       else
7082         event_ptid = inferior_ptid;
7083     }
7084   else
7085     /* A process exit.  Invalidate our notion of current thread.  */
7086     record_currthread (rs, minus_one_ptid);
7087
7088   return event_ptid;
7089 }
7090
7091 /* Wait until the remote machine stops, then return, storing status in
7092    STATUS just as `wait' would.  */
7093
7094 static ptid_t
7095 remote_wait (struct target_ops *ops,
7096              ptid_t ptid, struct target_waitstatus *status, int options)
7097 {
7098   ptid_t event_ptid;
7099
7100   if (target_is_non_stop_p ())
7101     event_ptid = remote_wait_ns (ptid, status, options);
7102   else
7103     event_ptid = remote_wait_as (ptid, status, options);
7104
7105   if (target_is_async_p ())
7106     {
7107       /* If there are are events left in the queue tell the event loop
7108          to return here.  */
7109       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7110         mark_async_event_handler (remote_async_inferior_event_token);
7111     }
7112
7113   return event_ptid;
7114 }
7115
7116 /* Fetch a single register using a 'p' packet.  */
7117
7118 static int
7119 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7120 {
7121   struct remote_state *rs = get_remote_state ();
7122   char *buf, *p;
7123   char regp[MAX_REGISTER_SIZE];
7124   int i;
7125
7126   if (packet_support (PACKET_p) == PACKET_DISABLE)
7127     return 0;
7128
7129   if (reg->pnum == -1)
7130     return 0;
7131
7132   p = rs->buf;
7133   *p++ = 'p';
7134   p += hexnumstr (p, reg->pnum);
7135   *p++ = '\0';
7136   putpkt (rs->buf);
7137   getpkt (&rs->buf, &rs->buf_size, 0);
7138
7139   buf = rs->buf;
7140
7141   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7142     {
7143     case PACKET_OK:
7144       break;
7145     case PACKET_UNKNOWN:
7146       return 0;
7147     case PACKET_ERROR:
7148       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7149              gdbarch_register_name (get_regcache_arch (regcache), 
7150                                     reg->regnum), 
7151              buf);
7152     }
7153
7154   /* If this register is unfetchable, tell the regcache.  */
7155   if (buf[0] == 'x')
7156     {
7157       regcache_raw_supply (regcache, reg->regnum, NULL);
7158       return 1;
7159     }
7160
7161   /* Otherwise, parse and supply the value.  */
7162   p = buf;
7163   i = 0;
7164   while (p[0] != 0)
7165     {
7166       if (p[1] == 0)
7167         error (_("fetch_register_using_p: early buf termination"));
7168
7169       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7170       p += 2;
7171     }
7172   regcache_raw_supply (regcache, reg->regnum, regp);
7173   return 1;
7174 }
7175
7176 /* Fetch the registers included in the target's 'g' packet.  */
7177
7178 static int
7179 send_g_packet (void)
7180 {
7181   struct remote_state *rs = get_remote_state ();
7182   int buf_len;
7183
7184   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7185   remote_send (&rs->buf, &rs->buf_size);
7186
7187   /* We can get out of synch in various cases.  If the first character
7188      in the buffer is not a hex character, assume that has happened
7189      and try to fetch another packet to read.  */
7190   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7191          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7192          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7193          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
7194     {
7195       if (remote_debug)
7196         fprintf_unfiltered (gdb_stdlog,
7197                             "Bad register packet; fetching a new packet\n");
7198       getpkt (&rs->buf, &rs->buf_size, 0);
7199     }
7200
7201   buf_len = strlen (rs->buf);
7202
7203   /* Sanity check the received packet.  */
7204   if (buf_len % 2 != 0)
7205     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7206
7207   return buf_len / 2;
7208 }
7209
7210 static void
7211 process_g_packet (struct regcache *regcache)
7212 {
7213   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7214   struct remote_state *rs = get_remote_state ();
7215   struct remote_arch_state *rsa = get_remote_arch_state ();
7216   int i, buf_len;
7217   char *p;
7218   char *regs;
7219
7220   buf_len = strlen (rs->buf);
7221
7222   /* Further sanity checks, with knowledge of the architecture.  */
7223   if (buf_len > 2 * rsa->sizeof_g_packet)
7224     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7225
7226   /* Save the size of the packet sent to us by the target.  It is used
7227      as a heuristic when determining the max size of packets that the
7228      target can safely receive.  */
7229   if (rsa->actual_register_packet_size == 0)
7230     rsa->actual_register_packet_size = buf_len;
7231
7232   /* If this is smaller than we guessed the 'g' packet would be,
7233      update our records.  A 'g' reply that doesn't include a register's
7234      value implies either that the register is not available, or that
7235      the 'p' packet must be used.  */
7236   if (buf_len < 2 * rsa->sizeof_g_packet)
7237     {
7238       rsa->sizeof_g_packet = buf_len / 2;
7239
7240       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7241         {
7242           if (rsa->regs[i].pnum == -1)
7243             continue;
7244
7245           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7246             rsa->regs[i].in_g_packet = 0;
7247           else
7248             rsa->regs[i].in_g_packet = 1;
7249         }
7250     }
7251
7252   regs = (char *) alloca (rsa->sizeof_g_packet);
7253
7254   /* Unimplemented registers read as all bits zero.  */
7255   memset (regs, 0, rsa->sizeof_g_packet);
7256
7257   /* Reply describes registers byte by byte, each byte encoded as two
7258      hex characters.  Suck them all up, then supply them to the
7259      register cacheing/storage mechanism.  */
7260
7261   p = rs->buf;
7262   for (i = 0; i < rsa->sizeof_g_packet; i++)
7263     {
7264       if (p[0] == 0 || p[1] == 0)
7265         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
7266         internal_error (__FILE__, __LINE__,
7267                         _("unexpected end of 'g' packet reply"));
7268
7269       if (p[0] == 'x' && p[1] == 'x')
7270         regs[i] = 0;            /* 'x' */
7271       else
7272         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7273       p += 2;
7274     }
7275
7276   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7277     {
7278       struct packet_reg *r = &rsa->regs[i];
7279
7280       if (r->in_g_packet)
7281         {
7282           if (r->offset * 2 >= strlen (rs->buf))
7283             /* This shouldn't happen - we adjusted in_g_packet above.  */
7284             internal_error (__FILE__, __LINE__,
7285                             _("unexpected end of 'g' packet reply"));
7286           else if (rs->buf[r->offset * 2] == 'x')
7287             {
7288               gdb_assert (r->offset * 2 < strlen (rs->buf));
7289               /* The register isn't available, mark it as such (at
7290                  the same time setting the value to zero).  */
7291               regcache_raw_supply (regcache, r->regnum, NULL);
7292             }
7293           else
7294             regcache_raw_supply (regcache, r->regnum,
7295                                  regs + r->offset);
7296         }
7297     }
7298 }
7299
7300 static void
7301 fetch_registers_using_g (struct regcache *regcache)
7302 {
7303   send_g_packet ();
7304   process_g_packet (regcache);
7305 }
7306
7307 /* Make the remote selected traceframe match GDB's selected
7308    traceframe.  */
7309
7310 static void
7311 set_remote_traceframe (void)
7312 {
7313   int newnum;
7314   struct remote_state *rs = get_remote_state ();
7315
7316   if (rs->remote_traceframe_number == get_traceframe_number ())
7317     return;
7318
7319   /* Avoid recursion, remote_trace_find calls us again.  */
7320   rs->remote_traceframe_number = get_traceframe_number ();
7321
7322   newnum = target_trace_find (tfind_number,
7323                               get_traceframe_number (), 0, 0, NULL);
7324
7325   /* Should not happen.  If it does, all bets are off.  */
7326   if (newnum != get_traceframe_number ())
7327     warning (_("could not set remote traceframe"));
7328 }
7329
7330 static void
7331 remote_fetch_registers (struct target_ops *ops,
7332                         struct regcache *regcache, int regnum)
7333 {
7334   struct remote_arch_state *rsa = get_remote_arch_state ();
7335   int i;
7336
7337   set_remote_traceframe ();
7338   set_general_thread (inferior_ptid);
7339
7340   if (regnum >= 0)
7341     {
7342       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7343
7344       gdb_assert (reg != NULL);
7345
7346       /* If this register might be in the 'g' packet, try that first -
7347          we are likely to read more than one register.  If this is the
7348          first 'g' packet, we might be overly optimistic about its
7349          contents, so fall back to 'p'.  */
7350       if (reg->in_g_packet)
7351         {
7352           fetch_registers_using_g (regcache);
7353           if (reg->in_g_packet)
7354             return;
7355         }
7356
7357       if (fetch_register_using_p (regcache, reg))
7358         return;
7359
7360       /* This register is not available.  */
7361       regcache_raw_supply (regcache, reg->regnum, NULL);
7362
7363       return;
7364     }
7365
7366   fetch_registers_using_g (regcache);
7367
7368   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7369     if (!rsa->regs[i].in_g_packet)
7370       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7371         {
7372           /* This register is not available.  */
7373           regcache_raw_supply (regcache, i, NULL);
7374         }
7375 }
7376
7377 /* Prepare to store registers.  Since we may send them all (using a
7378    'G' request), we have to read out the ones we don't want to change
7379    first.  */
7380
7381 static void
7382 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7383 {
7384   struct remote_arch_state *rsa = get_remote_arch_state ();
7385   int i;
7386   gdb_byte buf[MAX_REGISTER_SIZE];
7387
7388   /* Make sure the entire registers array is valid.  */
7389   switch (packet_support (PACKET_P))
7390     {
7391     case PACKET_DISABLE:
7392     case PACKET_SUPPORT_UNKNOWN:
7393       /* Make sure all the necessary registers are cached.  */
7394       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7395         if (rsa->regs[i].in_g_packet)
7396           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7397       break;
7398     case PACKET_ENABLE:
7399       break;
7400     }
7401 }
7402
7403 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
7404    packet was not recognized.  */
7405
7406 static int
7407 store_register_using_P (const struct regcache *regcache, 
7408                         struct packet_reg *reg)
7409 {
7410   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7411   struct remote_state *rs = get_remote_state ();
7412   /* Try storing a single register.  */
7413   char *buf = rs->buf;
7414   gdb_byte regp[MAX_REGISTER_SIZE];
7415   char *p;
7416
7417   if (packet_support (PACKET_P) == PACKET_DISABLE)
7418     return 0;
7419
7420   if (reg->pnum == -1)
7421     return 0;
7422
7423   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7424   p = buf + strlen (buf);
7425   regcache_raw_collect (regcache, reg->regnum, regp);
7426   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7427   putpkt (rs->buf);
7428   getpkt (&rs->buf, &rs->buf_size, 0);
7429
7430   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7431     {
7432     case PACKET_OK:
7433       return 1;
7434     case PACKET_ERROR:
7435       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7436              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7437     case PACKET_UNKNOWN:
7438       return 0;
7439     default:
7440       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7441     }
7442 }
7443
7444 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7445    contents of the register cache buffer.  FIXME: ignores errors.  */
7446
7447 static void
7448 store_registers_using_G (const struct regcache *regcache)
7449 {
7450   struct remote_state *rs = get_remote_state ();
7451   struct remote_arch_state *rsa = get_remote_arch_state ();
7452   gdb_byte *regs;
7453   char *p;
7454
7455   /* Extract all the registers in the regcache copying them into a
7456      local buffer.  */
7457   {
7458     int i;
7459
7460     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7461     memset (regs, 0, rsa->sizeof_g_packet);
7462     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7463       {
7464         struct packet_reg *r = &rsa->regs[i];
7465
7466         if (r->in_g_packet)
7467           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7468       }
7469   }
7470
7471   /* Command describes registers byte by byte,
7472      each byte encoded as two hex characters.  */
7473   p = rs->buf;
7474   *p++ = 'G';
7475   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7476      updated.  */
7477   bin2hex (regs, p, rsa->sizeof_g_packet);
7478   putpkt (rs->buf);
7479   getpkt (&rs->buf, &rs->buf_size, 0);
7480   if (packet_check_result (rs->buf) == PACKET_ERROR)
7481     error (_("Could not write registers; remote failure reply '%s'"), 
7482            rs->buf);
7483 }
7484
7485 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7486    of the register cache buffer.  FIXME: ignores errors.  */
7487
7488 static void
7489 remote_store_registers (struct target_ops *ops,
7490                         struct regcache *regcache, int regnum)
7491 {
7492   struct remote_arch_state *rsa = get_remote_arch_state ();
7493   int i;
7494
7495   set_remote_traceframe ();
7496   set_general_thread (inferior_ptid);
7497
7498   if (regnum >= 0)
7499     {
7500       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7501
7502       gdb_assert (reg != NULL);
7503
7504       /* Always prefer to store registers using the 'P' packet if
7505          possible; we often change only a small number of registers.
7506          Sometimes we change a larger number; we'd need help from a
7507          higher layer to know to use 'G'.  */
7508       if (store_register_using_P (regcache, reg))
7509         return;
7510
7511       /* For now, don't complain if we have no way to write the
7512          register.  GDB loses track of unavailable registers too
7513          easily.  Some day, this may be an error.  We don't have
7514          any way to read the register, either...  */
7515       if (!reg->in_g_packet)
7516         return;
7517
7518       store_registers_using_G (regcache);
7519       return;
7520     }
7521
7522   store_registers_using_G (regcache);
7523
7524   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7525     if (!rsa->regs[i].in_g_packet)
7526       if (!store_register_using_P (regcache, &rsa->regs[i]))
7527         /* See above for why we do not issue an error here.  */
7528         continue;
7529 }
7530 \f
7531
7532 /* Return the number of hex digits in num.  */
7533
7534 static int
7535 hexnumlen (ULONGEST num)
7536 {
7537   int i;
7538
7539   for (i = 0; num != 0; i++)
7540     num >>= 4;
7541
7542   return max (i, 1);
7543 }
7544
7545 /* Set BUF to the minimum number of hex digits representing NUM.  */
7546
7547 static int
7548 hexnumstr (char *buf, ULONGEST num)
7549 {
7550   int len = hexnumlen (num);
7551
7552   return hexnumnstr (buf, num, len);
7553 }
7554
7555
7556 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
7557
7558 static int
7559 hexnumnstr (char *buf, ULONGEST num, int width)
7560 {
7561   int i;
7562
7563   buf[width] = '\0';
7564
7565   for (i = width - 1; i >= 0; i--)
7566     {
7567       buf[i] = "0123456789abcdef"[(num & 0xf)];
7568       num >>= 4;
7569     }
7570
7571   return width;
7572 }
7573
7574 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
7575
7576 static CORE_ADDR
7577 remote_address_masked (CORE_ADDR addr)
7578 {
7579   unsigned int address_size = remote_address_size;
7580
7581   /* If "remoteaddresssize" was not set, default to target address size.  */
7582   if (!address_size)
7583     address_size = gdbarch_addr_bit (target_gdbarch ());
7584
7585   if (address_size > 0
7586       && address_size < (sizeof (ULONGEST) * 8))
7587     {
7588       /* Only create a mask when that mask can safely be constructed
7589          in a ULONGEST variable.  */
7590       ULONGEST mask = 1;
7591
7592       mask = (mask << address_size) - 1;
7593       addr &= mask;
7594     }
7595   return addr;
7596 }
7597
7598 /* Determine whether the remote target supports binary downloading.
7599    This is accomplished by sending a no-op memory write of zero length
7600    to the target at the specified address. It does not suffice to send
7601    the whole packet, since many stubs strip the eighth bit and
7602    subsequently compute a wrong checksum, which causes real havoc with
7603    remote_write_bytes.
7604
7605    NOTE: This can still lose if the serial line is not eight-bit
7606    clean.  In cases like this, the user should clear "remote
7607    X-packet".  */
7608
7609 static void
7610 check_binary_download (CORE_ADDR addr)
7611 {
7612   struct remote_state *rs = get_remote_state ();
7613
7614   switch (packet_support (PACKET_X))
7615     {
7616     case PACKET_DISABLE:
7617       break;
7618     case PACKET_ENABLE:
7619       break;
7620     case PACKET_SUPPORT_UNKNOWN:
7621       {
7622         char *p;
7623
7624         p = rs->buf;
7625         *p++ = 'X';
7626         p += hexnumstr (p, (ULONGEST) addr);
7627         *p++ = ',';
7628         p += hexnumstr (p, (ULONGEST) 0);
7629         *p++ = ':';
7630         *p = '\0';
7631
7632         putpkt_binary (rs->buf, (int) (p - rs->buf));
7633         getpkt (&rs->buf, &rs->buf_size, 0);
7634
7635         if (rs->buf[0] == '\0')
7636           {
7637             if (remote_debug)
7638               fprintf_unfiltered (gdb_stdlog,
7639                                   "binary downloading NOT "
7640                                   "supported by target\n");
7641             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7642           }
7643         else
7644           {
7645             if (remote_debug)
7646               fprintf_unfiltered (gdb_stdlog,
7647                                   "binary downloading supported by target\n");
7648             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7649           }
7650         break;
7651       }
7652     }
7653 }
7654
7655 /* Helper function to resize the payload in order to try to get a good
7656    alignment.  We try to write an amount of data such that the next write will
7657    start on an address aligned on REMOTE_ALIGN_WRITES.  */
7658
7659 static int
7660 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7661 {
7662   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7663 }
7664
7665 /* Write memory data directly to the remote machine.
7666    This does not inform the data cache; the data cache uses this.
7667    HEADER is the starting part of the packet.
7668    MEMADDR is the address in the remote memory space.
7669    MYADDR is the address of the buffer in our space.
7670    LEN_UNITS is the number of addressable units to write.
7671    UNIT_SIZE is the length in bytes of an addressable unit.
7672    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7673    should send data as binary ('X'), or hex-encoded ('M').
7674
7675    The function creates packet of the form
7676        <HEADER><ADDRESS>,<LENGTH>:<DATA>
7677
7678    where encoding of <DATA> is terminated by PACKET_FORMAT.
7679
7680    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7681    are omitted.
7682
7683    Return the transferred status, error or OK (an
7684    'enum target_xfer_status' value).  Save the number of addressable units
7685    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
7686
7687    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7688    exchange between gdb and the stub could look like (?? in place of the
7689    checksum):
7690
7691    -> $m1000,4#??
7692    <- aaaabbbbccccdddd
7693
7694    -> $M1000,3:eeeeffffeeee#??
7695    <- OK
7696
7697    -> $m1000,4#??
7698    <- eeeeffffeeeedddd  */
7699
7700 static enum target_xfer_status
7701 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7702                         const gdb_byte *myaddr, ULONGEST len_units,
7703                         int unit_size, ULONGEST *xfered_len_units,
7704                         char packet_format, int use_length)
7705 {
7706   struct remote_state *rs = get_remote_state ();
7707   char *p;
7708   char *plen = NULL;
7709   int plenlen = 0;
7710   int todo_units;
7711   int units_written;
7712   int payload_capacity_bytes;
7713   int payload_length_bytes;
7714
7715   if (packet_format != 'X' && packet_format != 'M')
7716     internal_error (__FILE__, __LINE__,
7717                     _("remote_write_bytes_aux: bad packet format"));
7718
7719   if (len_units == 0)
7720     return TARGET_XFER_EOF;
7721
7722   payload_capacity_bytes = get_memory_write_packet_size ();
7723
7724   /* The packet buffer will be large enough for the payload;
7725      get_memory_packet_size ensures this.  */
7726   rs->buf[0] = '\0';
7727
7728   /* Compute the size of the actual payload by subtracting out the
7729      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
7730
7731   payload_capacity_bytes -= strlen ("$,:#NN");
7732   if (!use_length)
7733     /* The comma won't be used.  */
7734     payload_capacity_bytes += 1;
7735   payload_capacity_bytes -= strlen (header);
7736   payload_capacity_bytes -= hexnumlen (memaddr);
7737
7738   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
7739
7740   strcat (rs->buf, header);
7741   p = rs->buf + strlen (header);
7742
7743   /* Compute a best guess of the number of bytes actually transfered.  */
7744   if (packet_format == 'X')
7745     {
7746       /* Best guess at number of bytes that will fit.  */
7747       todo_units = min (len_units, payload_capacity_bytes / unit_size);
7748       if (use_length)
7749         payload_capacity_bytes -= hexnumlen (todo_units);
7750       todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7751     }
7752   else
7753     {
7754       /* Number of bytes that will fit.  */
7755       todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7756       if (use_length)
7757         payload_capacity_bytes -= hexnumlen (todo_units);
7758       todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7759     }
7760
7761   if (todo_units <= 0)
7762     internal_error (__FILE__, __LINE__,
7763                     _("minimum packet size too small to write data"));
7764
7765   /* If we already need another packet, then try to align the end
7766      of this packet to a useful boundary.  */
7767   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7768     todo_units = align_for_efficient_write (todo_units, memaddr);
7769
7770   /* Append "<memaddr>".  */
7771   memaddr = remote_address_masked (memaddr);
7772   p += hexnumstr (p, (ULONGEST) memaddr);
7773
7774   if (use_length)
7775     {
7776       /* Append ",".  */
7777       *p++ = ',';
7778
7779       /* Append the length and retain its location and size.  It may need to be
7780          adjusted once the packet body has been created.  */
7781       plen = p;
7782       plenlen = hexnumstr (p, (ULONGEST) todo_units);
7783       p += plenlen;
7784     }
7785
7786   /* Append ":".  */
7787   *p++ = ':';
7788   *p = '\0';
7789
7790   /* Append the packet body.  */
7791   if (packet_format == 'X')
7792     {
7793       /* Binary mode.  Send target system values byte by byte, in
7794          increasing byte addresses.  Only escape certain critical
7795          characters.  */
7796       payload_length_bytes =
7797           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7798                                 &units_written, payload_capacity_bytes);
7799
7800       /* If not all TODO units fit, then we'll need another packet.  Make
7801          a second try to keep the end of the packet aligned.  Don't do
7802          this if the packet is tiny.  */
7803       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7804         {
7805           int new_todo_units;
7806
7807           new_todo_units = align_for_efficient_write (units_written, memaddr);
7808
7809           if (new_todo_units != units_written)
7810             payload_length_bytes =
7811                 remote_escape_output (myaddr, new_todo_units, unit_size,
7812                                       (gdb_byte *) p, &units_written,
7813                                       payload_capacity_bytes);
7814         }
7815
7816       p += payload_length_bytes;
7817       if (use_length && units_written < todo_units)
7818         {
7819           /* Escape chars have filled up the buffer prematurely,
7820              and we have actually sent fewer units than planned.
7821              Fix-up the length field of the packet.  Use the same
7822              number of characters as before.  */
7823           plen += hexnumnstr (plen, (ULONGEST) units_written,
7824                               plenlen);
7825           *plen = ':';  /* overwrite \0 from hexnumnstr() */
7826         }
7827     }
7828   else
7829     {
7830       /* Normal mode: Send target system values byte by byte, in
7831          increasing byte addresses.  Each byte is encoded as a two hex
7832          value.  */
7833       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7834       units_written = todo_units;
7835     }
7836
7837   putpkt_binary (rs->buf, (int) (p - rs->buf));
7838   getpkt (&rs->buf, &rs->buf_size, 0);
7839
7840   if (rs->buf[0] == 'E')
7841     return TARGET_XFER_E_IO;
7842
7843   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7844      send fewer units than we'd planned.  */
7845   *xfered_len_units = (ULONGEST) units_written;
7846   return TARGET_XFER_OK;
7847 }
7848
7849 /* Write memory data directly to the remote machine.
7850    This does not inform the data cache; the data cache uses this.
7851    MEMADDR is the address in the remote memory space.
7852    MYADDR is the address of the buffer in our space.
7853    LEN is the number of bytes.
7854
7855    Return the transferred status, error or OK (an
7856    'enum target_xfer_status' value).  Save the number of bytes
7857    transferred in *XFERED_LEN.  Only transfer a single packet.  */
7858
7859 static enum target_xfer_status
7860 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7861                     int unit_size, ULONGEST *xfered_len)
7862 {
7863   char *packet_format = 0;
7864
7865   /* Check whether the target supports binary download.  */
7866   check_binary_download (memaddr);
7867
7868   switch (packet_support (PACKET_X))
7869     {
7870     case PACKET_ENABLE:
7871       packet_format = "X";
7872       break;
7873     case PACKET_DISABLE:
7874       packet_format = "M";
7875       break;
7876     case PACKET_SUPPORT_UNKNOWN:
7877       internal_error (__FILE__, __LINE__,
7878                       _("remote_write_bytes: bad internal state"));
7879     default:
7880       internal_error (__FILE__, __LINE__, _("bad switch"));
7881     }
7882
7883   return remote_write_bytes_aux (packet_format,
7884                                  memaddr, myaddr, len, unit_size, xfered_len,
7885                                  packet_format[0], 1);
7886 }
7887
7888 /* Read memory data directly from the remote machine.
7889    This does not use the data cache; the data cache uses this.
7890    MEMADDR is the address in the remote memory space.
7891    MYADDR is the address of the buffer in our space.
7892    LEN_UNITS is the number of addressable memory units to read..
7893    UNIT_SIZE is the length in bytes of an addressable unit.
7894
7895    Return the transferred status, error or OK (an
7896    'enum target_xfer_status' value).  Save the number of bytes
7897    transferred in *XFERED_LEN_UNITS.
7898
7899    See the comment of remote_write_bytes_aux for an example of
7900    memory read/write exchange between gdb and the stub.  */
7901
7902 static enum target_xfer_status
7903 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7904                      int unit_size, ULONGEST *xfered_len_units)
7905 {
7906   struct remote_state *rs = get_remote_state ();
7907   int buf_size_bytes;           /* Max size of packet output buffer.  */
7908   char *p;
7909   int todo_units;
7910   int decoded_bytes;
7911
7912   buf_size_bytes = get_memory_read_packet_size ();
7913   /* The packet buffer will be large enough for the payload;
7914      get_memory_packet_size ensures this.  */
7915
7916   /* Number of units that will fit.  */
7917   todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7918
7919   /* Construct "m"<memaddr>","<len>".  */
7920   memaddr = remote_address_masked (memaddr);
7921   p = rs->buf;
7922   *p++ = 'm';
7923   p += hexnumstr (p, (ULONGEST) memaddr);
7924   *p++ = ',';
7925   p += hexnumstr (p, (ULONGEST) todo_units);
7926   *p = '\0';
7927   putpkt (rs->buf);
7928   getpkt (&rs->buf, &rs->buf_size, 0);
7929   if (rs->buf[0] == 'E'
7930       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7931       && rs->buf[3] == '\0')
7932     return TARGET_XFER_E_IO;
7933   /* Reply describes memory byte by byte, each byte encoded as two hex
7934      characters.  */
7935   p = rs->buf;
7936   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7937   /* Return what we have.  Let higher layers handle partial reads.  */
7938   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7939   return TARGET_XFER_OK;
7940 }
7941
7942 /* Using the set of read-only target sections of remote, read live
7943    read-only memory.
7944
7945    For interface/parameters/return description see target.h,
7946    to_xfer_partial.  */
7947
7948 static enum target_xfer_status
7949 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7950                                    ULONGEST memaddr, ULONGEST len,
7951                                    int unit_size, ULONGEST *xfered_len)
7952 {
7953   struct target_section *secp;
7954   struct target_section_table *table;
7955
7956   secp = target_section_by_addr (ops, memaddr);
7957   if (secp != NULL
7958       && (bfd_get_section_flags (secp->the_bfd_section->owner,
7959                                  secp->the_bfd_section)
7960           & SEC_READONLY))
7961     {
7962       struct target_section *p;
7963       ULONGEST memend = memaddr + len;
7964
7965       table = target_get_section_table (ops);
7966
7967       for (p = table->sections; p < table->sections_end; p++)
7968         {
7969           if (memaddr >= p->addr)
7970             {
7971               if (memend <= p->endaddr)
7972                 {
7973                   /* Entire transfer is within this section.  */
7974                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7975                                               xfered_len);
7976                 }
7977               else if (memaddr >= p->endaddr)
7978                 {
7979                   /* This section ends before the transfer starts.  */
7980                   continue;
7981                 }
7982               else
7983                 {
7984                   /* This section overlaps the transfer.  Just do half.  */
7985                   len = p->endaddr - memaddr;
7986                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7987                                               xfered_len);
7988                 }
7989             }
7990         }
7991     }
7992
7993   return TARGET_XFER_EOF;
7994 }
7995
7996 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7997    first if the requested memory is unavailable in traceframe.
7998    Otherwise, fall back to remote_read_bytes_1.  */
7999
8000 static enum target_xfer_status
8001 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8002                    gdb_byte *myaddr, ULONGEST len, int unit_size,
8003                    ULONGEST *xfered_len)
8004 {
8005   if (len == 0)
8006     return TARGET_XFER_EOF;
8007
8008   if (get_traceframe_number () != -1)
8009     {
8010       VEC(mem_range_s) *available;
8011
8012       /* If we fail to get the set of available memory, then the
8013          target does not support querying traceframe info, and so we
8014          attempt reading from the traceframe anyway (assuming the
8015          target implements the old QTro packet then).  */
8016       if (traceframe_available_memory (&available, memaddr, len))
8017         {
8018           struct cleanup *old_chain;
8019
8020           old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
8021
8022           if (VEC_empty (mem_range_s, available)
8023               || VEC_index (mem_range_s, available, 0)->start != memaddr)
8024             {
8025               enum target_xfer_status res;
8026
8027               /* Don't read into the traceframe's available
8028                  memory.  */
8029               if (!VEC_empty (mem_range_s, available))
8030                 {
8031                   LONGEST oldlen = len;
8032
8033                   len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8034                   gdb_assert (len <= oldlen);
8035                 }
8036
8037               do_cleanups (old_chain);
8038
8039               /* This goes through the topmost target again.  */
8040               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8041                                                        len, unit_size, xfered_len);
8042               if (res == TARGET_XFER_OK)
8043                 return TARGET_XFER_OK;
8044               else
8045                 {
8046                   /* No use trying further, we know some memory starting
8047                      at MEMADDR isn't available.  */
8048                   *xfered_len = len;
8049                   return TARGET_XFER_UNAVAILABLE;
8050                 }
8051             }
8052
8053           /* Don't try to read more than how much is available, in
8054              case the target implements the deprecated QTro packet to
8055              cater for older GDBs (the target's knowledge of read-only
8056              sections may be outdated by now).  */
8057           len = VEC_index (mem_range_s, available, 0)->length;
8058
8059           do_cleanups (old_chain);
8060         }
8061     }
8062
8063   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8064 }
8065
8066 \f
8067
8068 /* Sends a packet with content determined by the printf format string
8069    FORMAT and the remaining arguments, then gets the reply.  Returns
8070    whether the packet was a success, a failure, or unknown.  */
8071
8072 static enum packet_result remote_send_printf (const char *format, ...)
8073   ATTRIBUTE_PRINTF (1, 2);
8074
8075 static enum packet_result
8076 remote_send_printf (const char *format, ...)
8077 {
8078   struct remote_state *rs = get_remote_state ();
8079   int max_size = get_remote_packet_size ();
8080   va_list ap;
8081
8082   va_start (ap, format);
8083
8084   rs->buf[0] = '\0';
8085   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8086     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8087
8088   if (putpkt (rs->buf) < 0)
8089     error (_("Communication problem with target."));
8090
8091   rs->buf[0] = '\0';
8092   getpkt (&rs->buf, &rs->buf_size, 0);
8093
8094   return packet_check_result (rs->buf);
8095 }
8096
8097 static void
8098 restore_remote_timeout (void *p)
8099 {
8100   int value = *(int *)p;
8101
8102   remote_timeout = value;
8103 }
8104
8105 /* Flash writing can take quite some time.  We'll set
8106    effectively infinite timeout for flash operations.
8107    In future, we'll need to decide on a better approach.  */
8108 static const int remote_flash_timeout = 1000;
8109
8110 static void
8111 remote_flash_erase (struct target_ops *ops,
8112                     ULONGEST address, LONGEST length)
8113 {
8114   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8115   int saved_remote_timeout = remote_timeout;
8116   enum packet_result ret;
8117   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8118                                           &saved_remote_timeout);
8119
8120   remote_timeout = remote_flash_timeout;
8121
8122   ret = remote_send_printf ("vFlashErase:%s,%s",
8123                             phex (address, addr_size),
8124                             phex (length, 4));
8125   switch (ret)
8126     {
8127     case PACKET_UNKNOWN:
8128       error (_("Remote target does not support flash erase"));
8129     case PACKET_ERROR:
8130       error (_("Error erasing flash with vFlashErase packet"));
8131     default:
8132       break;
8133     }
8134
8135   do_cleanups (back_to);
8136 }
8137
8138 static enum target_xfer_status
8139 remote_flash_write (struct target_ops *ops, ULONGEST address,
8140                     ULONGEST length, ULONGEST *xfered_len,
8141                     const gdb_byte *data)
8142 {
8143   int saved_remote_timeout = remote_timeout;
8144   enum target_xfer_status ret;
8145   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8146                                           &saved_remote_timeout);
8147
8148   remote_timeout = remote_flash_timeout;
8149   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8150                                 xfered_len,'X', 0);
8151   do_cleanups (back_to);
8152
8153   return ret;
8154 }
8155
8156 static void
8157 remote_flash_done (struct target_ops *ops)
8158 {
8159   int saved_remote_timeout = remote_timeout;
8160   int ret;
8161   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8162                                           &saved_remote_timeout);
8163
8164   remote_timeout = remote_flash_timeout;
8165   ret = remote_send_printf ("vFlashDone");
8166   do_cleanups (back_to);
8167
8168   switch (ret)
8169     {
8170     case PACKET_UNKNOWN:
8171       error (_("Remote target does not support vFlashDone"));
8172     case PACKET_ERROR:
8173       error (_("Error finishing flash operation"));
8174     default:
8175       break;
8176     }
8177 }
8178
8179 static void
8180 remote_files_info (struct target_ops *ignore)
8181 {
8182   puts_filtered ("Debugging a target over a serial line.\n");
8183 }
8184 \f
8185 /* Stuff for dealing with the packets which are part of this protocol.
8186    See comment at top of file for details.  */
8187
8188 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8189    error to higher layers.  Called when a serial error is detected.
8190    The exception message is STRING, followed by a colon and a blank,
8191    the system error message for errno at function entry and final dot
8192    for output compatibility with throw_perror_with_name.  */
8193
8194 static void
8195 unpush_and_perror (const char *string)
8196 {
8197   int saved_errno = errno;
8198
8199   remote_unpush_target ();
8200   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8201                safe_strerror (saved_errno));
8202 }
8203
8204 /* Read a single character from the remote end.  */
8205
8206 static int
8207 readchar (int timeout)
8208 {
8209   int ch;
8210   struct remote_state *rs = get_remote_state ();
8211
8212   ch = serial_readchar (rs->remote_desc, timeout);
8213
8214   if (ch >= 0)
8215     return ch;
8216
8217   switch ((enum serial_rc) ch)
8218     {
8219     case SERIAL_EOF:
8220       remote_unpush_target ();
8221       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8222       /* no return */
8223     case SERIAL_ERROR:
8224       unpush_and_perror (_("Remote communication error.  "
8225                            "Target disconnected."));
8226       /* no return */
8227     case SERIAL_TIMEOUT:
8228       break;
8229     }
8230   return ch;
8231 }
8232
8233 /* Wrapper for serial_write that closes the target and throws if
8234    writing fails.  */
8235
8236 static void
8237 remote_serial_write (const char *str, int len)
8238 {
8239   struct remote_state *rs = get_remote_state ();
8240
8241   if (serial_write (rs->remote_desc, str, len))
8242     {
8243       unpush_and_perror (_("Remote communication error.  "
8244                            "Target disconnected."));
8245     }
8246 }
8247
8248 /* Send the command in *BUF to the remote machine, and read the reply
8249    into *BUF.  Report an error if we get an error reply.  Resize
8250    *BUF using xrealloc if necessary to hold the result, and update
8251    *SIZEOF_BUF.  */
8252
8253 static void
8254 remote_send (char **buf,
8255              long *sizeof_buf)
8256 {
8257   putpkt (*buf);
8258   getpkt (buf, sizeof_buf, 0);
8259
8260   if ((*buf)[0] == 'E')
8261     error (_("Remote failure reply: %s"), *buf);
8262 }
8263
8264 /* Return a pointer to an xmalloc'ed string representing an escaped
8265    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
8266    etc.  The caller is responsible for releasing the returned
8267    memory.  */
8268
8269 static char *
8270 escape_buffer (const char *buf, int n)
8271 {
8272   struct cleanup *old_chain;
8273   struct ui_file *stb;
8274   char *str;
8275
8276   stb = mem_fileopen ();
8277   old_chain = make_cleanup_ui_file_delete (stb);
8278
8279   fputstrn_unfiltered (buf, n, '\\', stb);
8280   str = ui_file_xstrdup (stb, NULL);
8281   do_cleanups (old_chain);
8282   return str;
8283 }
8284
8285 /* Display a null-terminated packet on stdout, for debugging, using C
8286    string notation.  */
8287
8288 static void
8289 print_packet (const char *buf)
8290 {
8291   puts_filtered ("\"");
8292   fputstr_filtered (buf, '"', gdb_stdout);
8293   puts_filtered ("\"");
8294 }
8295
8296 int
8297 putpkt (const char *buf)
8298 {
8299   return putpkt_binary (buf, strlen (buf));
8300 }
8301
8302 /* Send a packet to the remote machine, with error checking.  The data
8303    of the packet is in BUF.  The string in BUF can be at most
8304    get_remote_packet_size () - 5 to account for the $, # and checksum,
8305    and for a possible /0 if we are debugging (remote_debug) and want
8306    to print the sent packet as a string.  */
8307
8308 static int
8309 putpkt_binary (const char *buf, int cnt)
8310 {
8311   struct remote_state *rs = get_remote_state ();
8312   int i;
8313   unsigned char csum = 0;
8314   char *buf2 = (char *) xmalloc (cnt + 6);
8315   struct cleanup *old_chain = make_cleanup (xfree, buf2);
8316
8317   int ch;
8318   int tcount = 0;
8319   char *p;
8320
8321   /* Catch cases like trying to read memory or listing threads while
8322      we're waiting for a stop reply.  The remote server wouldn't be
8323      ready to handle this request, so we'd hang and timeout.  We don't
8324      have to worry about this in synchronous mode, because in that
8325      case it's not possible to issue a command while the target is
8326      running.  This is not a problem in non-stop mode, because in that
8327      case, the stub is always ready to process serial input.  */
8328   if (!target_is_non_stop_p ()
8329       && target_is_async_p ()
8330       && rs->waiting_for_stop_reply)
8331     {
8332       error (_("Cannot execute this command while the target is running.\n"
8333                "Use the \"interrupt\" command to stop the target\n"
8334                "and then try again."));
8335     }
8336
8337   /* We're sending out a new packet.  Make sure we don't look at a
8338      stale cached response.  */
8339   rs->cached_wait_status = 0;
8340
8341   /* Copy the packet into buffer BUF2, encapsulating it
8342      and giving it a checksum.  */
8343
8344   p = buf2;
8345   *p++ = '$';
8346
8347   for (i = 0; i < cnt; i++)
8348     {
8349       csum += buf[i];
8350       *p++ = buf[i];
8351     }
8352   *p++ = '#';
8353   *p++ = tohex ((csum >> 4) & 0xf);
8354   *p++ = tohex (csum & 0xf);
8355
8356   /* Send it over and over until we get a positive ack.  */
8357
8358   while (1)
8359     {
8360       int started_error_output = 0;
8361
8362       if (remote_debug)
8363         {
8364           struct cleanup *old_chain;
8365           char *str;
8366
8367           *p = '\0';
8368           str = escape_buffer (buf2, p - buf2);
8369           old_chain = make_cleanup (xfree, str);
8370           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8371           gdb_flush (gdb_stdlog);
8372           do_cleanups (old_chain);
8373         }
8374       remote_serial_write (buf2, p - buf2);
8375
8376       /* If this is a no acks version of the remote protocol, send the
8377          packet and move on.  */
8378       if (rs->noack_mode)
8379         break;
8380
8381       /* Read until either a timeout occurs (-2) or '+' is read.
8382          Handle any notification that arrives in the mean time.  */
8383       while (1)
8384         {
8385           ch = readchar (remote_timeout);
8386
8387           if (remote_debug)
8388             {
8389               switch (ch)
8390                 {
8391                 case '+':
8392                 case '-':
8393                 case SERIAL_TIMEOUT:
8394                 case '$':
8395                 case '%':
8396                   if (started_error_output)
8397                     {
8398                       putchar_unfiltered ('\n');
8399                       started_error_output = 0;
8400                     }
8401                 }
8402             }
8403
8404           switch (ch)
8405             {
8406             case '+':
8407               if (remote_debug)
8408                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8409               do_cleanups (old_chain);
8410               return 1;
8411             case '-':
8412               if (remote_debug)
8413                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8414               /* FALLTHROUGH */
8415             case SERIAL_TIMEOUT:
8416               tcount++;
8417               if (tcount > 3)
8418                 {
8419                   do_cleanups (old_chain);
8420                   return 0;
8421                 }
8422               break;            /* Retransmit buffer.  */
8423             case '$':
8424               {
8425                 if (remote_debug)
8426                   fprintf_unfiltered (gdb_stdlog,
8427                                       "Packet instead of Ack, ignoring it\n");
8428                 /* It's probably an old response sent because an ACK
8429                    was lost.  Gobble up the packet and ack it so it
8430                    doesn't get retransmitted when we resend this
8431                    packet.  */
8432                 skip_frame ();
8433                 remote_serial_write ("+", 1);
8434                 continue;       /* Now, go look for +.  */
8435               }
8436
8437             case '%':
8438               {
8439                 int val;
8440
8441                 /* If we got a notification, handle it, and go back to looking
8442                    for an ack.  */
8443                 /* We've found the start of a notification.  Now
8444                    collect the data.  */
8445                 val = read_frame (&rs->buf, &rs->buf_size);
8446                 if (val >= 0)
8447                   {
8448                     if (remote_debug)
8449                       {
8450                         struct cleanup *old_chain;
8451                         char *str;
8452
8453                         str = escape_buffer (rs->buf, val);
8454                         old_chain = make_cleanup (xfree, str);
8455                         fprintf_unfiltered (gdb_stdlog,
8456                                             "  Notification received: %s\n",
8457                                             str);
8458                         do_cleanups (old_chain);
8459                       }
8460                     handle_notification (rs->notif_state, rs->buf);
8461                     /* We're in sync now, rewait for the ack.  */
8462                     tcount = 0;
8463                   }
8464                 else
8465                   {
8466                     if (remote_debug)
8467                       {
8468                         if (!started_error_output)
8469                           {
8470                             started_error_output = 1;
8471                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8472                           }
8473                         fputc_unfiltered (ch & 0177, gdb_stdlog);
8474                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8475                       }
8476                   }
8477                 continue;
8478               }
8479               /* fall-through */
8480             default:
8481               if (remote_debug)
8482                 {
8483                   if (!started_error_output)
8484                     {
8485                       started_error_output = 1;
8486                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8487                     }
8488                   fputc_unfiltered (ch & 0177, gdb_stdlog);
8489                 }
8490               continue;
8491             }
8492           break;                /* Here to retransmit.  */
8493         }
8494
8495 #if 0
8496       /* This is wrong.  If doing a long backtrace, the user should be
8497          able to get out next time we call QUIT, without anything as
8498          violent as interrupt_query.  If we want to provide a way out of
8499          here without getting to the next QUIT, it should be based on
8500          hitting ^C twice as in remote_wait.  */
8501       if (quit_flag)
8502         {
8503           quit_flag = 0;
8504           interrupt_query ();
8505         }
8506 #endif
8507     }
8508
8509   do_cleanups (old_chain);
8510   return 0;
8511 }
8512
8513 /* Come here after finding the start of a frame when we expected an
8514    ack.  Do our best to discard the rest of this packet.  */
8515
8516 static void
8517 skip_frame (void)
8518 {
8519   int c;
8520
8521   while (1)
8522     {
8523       c = readchar (remote_timeout);
8524       switch (c)
8525         {
8526         case SERIAL_TIMEOUT:
8527           /* Nothing we can do.  */
8528           return;
8529         case '#':
8530           /* Discard the two bytes of checksum and stop.  */
8531           c = readchar (remote_timeout);
8532           if (c >= 0)
8533             c = readchar (remote_timeout);
8534
8535           return;
8536         case '*':               /* Run length encoding.  */
8537           /* Discard the repeat count.  */
8538           c = readchar (remote_timeout);
8539           if (c < 0)
8540             return;
8541           break;
8542         default:
8543           /* A regular character.  */
8544           break;
8545         }
8546     }
8547 }
8548
8549 /* Come here after finding the start of the frame.  Collect the rest
8550    into *BUF, verifying the checksum, length, and handling run-length
8551    compression.  NUL terminate the buffer.  If there is not enough room,
8552    expand *BUF using xrealloc.
8553
8554    Returns -1 on error, number of characters in buffer (ignoring the
8555    trailing NULL) on success. (could be extended to return one of the
8556    SERIAL status indications).  */
8557
8558 static long
8559 read_frame (char **buf_p,
8560             long *sizeof_buf)
8561 {
8562   unsigned char csum;
8563   long bc;
8564   int c;
8565   char *buf = *buf_p;
8566   struct remote_state *rs = get_remote_state ();
8567
8568   csum = 0;
8569   bc = 0;
8570
8571   while (1)
8572     {
8573       c = readchar (remote_timeout);
8574       switch (c)
8575         {
8576         case SERIAL_TIMEOUT:
8577           if (remote_debug)
8578             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8579           return -1;
8580         case '$':
8581           if (remote_debug)
8582             fputs_filtered ("Saw new packet start in middle of old one\n",
8583                             gdb_stdlog);
8584           return -1;            /* Start a new packet, count retries.  */
8585         case '#':
8586           {
8587             unsigned char pktcsum;
8588             int check_0 = 0;
8589             int check_1 = 0;
8590
8591             buf[bc] = '\0';
8592
8593             check_0 = readchar (remote_timeout);
8594             if (check_0 >= 0)
8595               check_1 = readchar (remote_timeout);
8596
8597             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8598               {
8599                 if (remote_debug)
8600                   fputs_filtered ("Timeout in checksum, retrying\n",
8601                                   gdb_stdlog);
8602                 return -1;
8603               }
8604             else if (check_0 < 0 || check_1 < 0)
8605               {
8606                 if (remote_debug)
8607                   fputs_filtered ("Communication error in checksum\n",
8608                                   gdb_stdlog);
8609                 return -1;
8610               }
8611
8612             /* Don't recompute the checksum; with no ack packets we
8613                don't have any way to indicate a packet retransmission
8614                is necessary.  */
8615             if (rs->noack_mode)
8616               return bc;
8617
8618             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8619             if (csum == pktcsum)
8620               return bc;
8621
8622             if (remote_debug)
8623               {
8624                 struct cleanup *old_chain;
8625                 char *str;
8626
8627                 str = escape_buffer (buf, bc);
8628                 old_chain = make_cleanup (xfree, str);
8629                 fprintf_unfiltered (gdb_stdlog,
8630                                     "Bad checksum, sentsum=0x%x, "
8631                                     "csum=0x%x, buf=%s\n",
8632                                     pktcsum, csum, str);
8633                 do_cleanups (old_chain);
8634               }
8635             /* Number of characters in buffer ignoring trailing
8636                NULL.  */
8637             return -1;
8638           }
8639         case '*':               /* Run length encoding.  */
8640           {
8641             int repeat;
8642
8643             csum += c;
8644             c = readchar (remote_timeout);
8645             csum += c;
8646             repeat = c - ' ' + 3;       /* Compute repeat count.  */
8647
8648             /* The character before ``*'' is repeated.  */
8649
8650             if (repeat > 0 && repeat <= 255 && bc > 0)
8651               {
8652                 if (bc + repeat - 1 >= *sizeof_buf - 1)
8653                   {
8654                     /* Make some more room in the buffer.  */
8655                     *sizeof_buf += repeat;
8656                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8657                     buf = *buf_p;
8658                   }
8659
8660                 memset (&buf[bc], buf[bc - 1], repeat);
8661                 bc += repeat;
8662                 continue;
8663               }
8664
8665             buf[bc] = '\0';
8666             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8667             return -1;
8668           }
8669         default:
8670           if (bc >= *sizeof_buf - 1)
8671             {
8672               /* Make some more room in the buffer.  */
8673               *sizeof_buf *= 2;
8674               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8675               buf = *buf_p;
8676             }
8677
8678           buf[bc++] = c;
8679           csum += c;
8680           continue;
8681         }
8682     }
8683 }
8684
8685 /* Read a packet from the remote machine, with error checking, and
8686    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8687    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8688    rather than timing out; this is used (in synchronous mode) to wait
8689    for a target that is is executing user code to stop.  */
8690 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8691    don't have to change all the calls to getpkt to deal with the
8692    return value, because at the moment I don't know what the right
8693    thing to do it for those.  */
8694 void
8695 getpkt (char **buf,
8696         long *sizeof_buf,
8697         int forever)
8698 {
8699   getpkt_sane (buf, sizeof_buf, forever);
8700 }
8701
8702
8703 /* Read a packet from the remote machine, with error checking, and
8704    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8705    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8706    rather than timing out; this is used (in synchronous mode) to wait
8707    for a target that is is executing user code to stop.  If FOREVER ==
8708    0, this function is allowed to time out gracefully and return an
8709    indication of this to the caller.  Otherwise return the number of
8710    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
8711    enough reason to return to the caller.  *IS_NOTIF is an output
8712    boolean that indicates whether *BUF holds a notification or not
8713    (a regular packet).  */
8714
8715 static int
8716 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8717                         int expecting_notif, int *is_notif)
8718 {
8719   struct remote_state *rs = get_remote_state ();
8720   int c;
8721   int tries;
8722   int timeout;
8723   int val = -1;
8724
8725   /* We're reading a new response.  Make sure we don't look at a
8726      previously cached response.  */
8727   rs->cached_wait_status = 0;
8728
8729   strcpy (*buf, "timeout");
8730
8731   if (forever)
8732     timeout = watchdog > 0 ? watchdog : -1;
8733   else if (expecting_notif)
8734     timeout = 0; /* There should already be a char in the buffer.  If
8735                     not, bail out.  */
8736   else
8737     timeout = remote_timeout;
8738
8739 #define MAX_TRIES 3
8740
8741   /* Process any number of notifications, and then return when
8742      we get a packet.  */
8743   for (;;)
8744     {
8745       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8746          times.  */
8747       for (tries = 1; tries <= MAX_TRIES; tries++)
8748         {
8749           /* This can loop forever if the remote side sends us
8750              characters continuously, but if it pauses, we'll get
8751              SERIAL_TIMEOUT from readchar because of timeout.  Then
8752              we'll count that as a retry.
8753
8754              Note that even when forever is set, we will only wait
8755              forever prior to the start of a packet.  After that, we
8756              expect characters to arrive at a brisk pace.  They should
8757              show up within remote_timeout intervals.  */
8758           do
8759             c = readchar (timeout);
8760           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8761
8762           if (c == SERIAL_TIMEOUT)
8763             {
8764               if (expecting_notif)
8765                 return -1; /* Don't complain, it's normal to not get
8766                               anything in this case.  */
8767
8768               if (forever)      /* Watchdog went off?  Kill the target.  */
8769                 {
8770                   QUIT;
8771                   remote_unpush_target ();
8772                   throw_error (TARGET_CLOSE_ERROR,
8773                                _("Watchdog timeout has expired.  "
8774                                  "Target detached."));
8775                 }
8776               if (remote_debug)
8777                 fputs_filtered ("Timed out.\n", gdb_stdlog);
8778             }
8779           else
8780             {
8781               /* We've found the start of a packet or notification.
8782                  Now collect the data.  */
8783               val = read_frame (buf, sizeof_buf);
8784               if (val >= 0)
8785                 break;
8786             }
8787
8788           remote_serial_write ("-", 1);
8789         }
8790
8791       if (tries > MAX_TRIES)
8792         {
8793           /* We have tried hard enough, and just can't receive the
8794              packet/notification.  Give up.  */
8795           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8796
8797           /* Skip the ack char if we're in no-ack mode.  */
8798           if (!rs->noack_mode)
8799             remote_serial_write ("+", 1);
8800           return -1;
8801         }
8802
8803       /* If we got an ordinary packet, return that to our caller.  */
8804       if (c == '$')
8805         {
8806           if (remote_debug)
8807             {
8808              struct cleanup *old_chain;
8809              char *str;
8810
8811              str = escape_buffer (*buf, val);
8812              old_chain = make_cleanup (xfree, str);
8813              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8814              do_cleanups (old_chain);
8815             }
8816
8817           /* Skip the ack char if we're in no-ack mode.  */
8818           if (!rs->noack_mode)
8819             remote_serial_write ("+", 1);
8820           if (is_notif != NULL)
8821             *is_notif = 0;
8822           return val;
8823         }
8824
8825        /* If we got a notification, handle it, and go back to looking
8826          for a packet.  */
8827       else
8828         {
8829           gdb_assert (c == '%');
8830
8831           if (remote_debug)
8832             {
8833               struct cleanup *old_chain;
8834               char *str;
8835
8836               str = escape_buffer (*buf, val);
8837               old_chain = make_cleanup (xfree, str);
8838               fprintf_unfiltered (gdb_stdlog,
8839                                   "  Notification received: %s\n",
8840                                   str);
8841               do_cleanups (old_chain);
8842             }
8843           if (is_notif != NULL)
8844             *is_notif = 1;
8845
8846           handle_notification (rs->notif_state, *buf);
8847
8848           /* Notifications require no acknowledgement.  */
8849
8850           if (expecting_notif)
8851             return val;
8852         }
8853     }
8854 }
8855
8856 static int
8857 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8858 {
8859   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8860 }
8861
8862 static int
8863 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8864                       int *is_notif)
8865 {
8866   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8867                                  is_notif);
8868 }
8869
8870 /* Check whether EVENT is a fork event for the process specified
8871    by the pid passed in DATA, and if it is, kill the fork child.  */
8872
8873 static int
8874 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8875                             QUEUE_ITER (stop_reply_p) *iter,
8876                             stop_reply_p event,
8877                             void *data)
8878 {
8879   struct queue_iter_param *param = (struct queue_iter_param *) data;
8880   int parent_pid = *(int *) param->input;
8881
8882   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8883     {
8884       struct remote_state *rs = get_remote_state ();
8885       int child_pid = ptid_get_pid (event->ws.value.related_pid);
8886       int res;
8887
8888       res = remote_vkill (child_pid, rs);
8889       if (res != 0)
8890         error (_("Can't kill fork child process %d"), child_pid);
8891     }
8892
8893   return 1;
8894 }
8895
8896 /* Kill any new fork children of process PID that haven't been
8897    processed by follow_fork.  */
8898
8899 static void
8900 kill_new_fork_children (int pid, struct remote_state *rs)
8901 {
8902   struct thread_info *thread;
8903   struct notif_client *notif = &notif_client_stop;
8904   struct queue_iter_param param;
8905
8906   /* Kill the fork child threads of any threads in process PID
8907      that are stopped at a fork event.  */
8908   ALL_NON_EXITED_THREADS (thread)
8909     {
8910       struct target_waitstatus *ws = &thread->pending_follow;
8911
8912       if (is_pending_fork_parent (ws, pid, thread->ptid))
8913         {
8914           struct remote_state *rs = get_remote_state ();
8915           int child_pid = ptid_get_pid (ws->value.related_pid);
8916           int res;
8917
8918           res = remote_vkill (child_pid, rs);
8919           if (res != 0)
8920             error (_("Can't kill fork child process %d"), child_pid);
8921         }
8922     }
8923
8924   /* Check for any pending fork events (not reported or processed yet)
8925      in process PID and kill those fork child threads as well.  */
8926   remote_notif_get_pending_events (notif);
8927   param.input = &pid;
8928   param.output = NULL;
8929   QUEUE_iterate (stop_reply_p, stop_reply_queue,
8930                  kill_child_of_pending_fork, &param);
8931 }
8932
8933 \f
8934 /* Target hook to kill the current inferior.  */
8935
8936 static void
8937 remote_kill (struct target_ops *ops)
8938 {
8939   int res = -1;
8940   int pid = ptid_get_pid (inferior_ptid);
8941   struct remote_state *rs = get_remote_state ();
8942
8943   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
8944     {
8945       /* If we're stopped while forking and we haven't followed yet,
8946          kill the child task.  We need to do this before killing the
8947          parent task because if this is a vfork then the parent will
8948          be sleeping.  */
8949       kill_new_fork_children (pid, rs);
8950
8951       res = remote_vkill (pid, rs);
8952       if (res == 0)
8953         {
8954           target_mourn_inferior ();
8955           return;
8956         }
8957     }
8958
8959   /* If we are in 'target remote' mode and we are killing the only
8960      inferior, then we will tell gdbserver to exit and unpush the
8961      target.  */
8962   if (res == -1 && !remote_multi_process_p (rs)
8963       && number_of_live_inferiors () == 1)
8964     {
8965       remote_kill_k ();
8966
8967       /* We've killed the remote end, we get to mourn it.  If we are
8968          not in extended mode, mourning the inferior also unpushes
8969          remote_ops from the target stack, which closes the remote
8970          connection.  */
8971       target_mourn_inferior ();
8972
8973       return;
8974     }
8975
8976   error (_("Can't kill process"));
8977 }
8978
8979 /* Send a kill request to the target using the 'vKill' packet.  */
8980
8981 static int
8982 remote_vkill (int pid, struct remote_state *rs)
8983 {
8984   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8985     return -1;
8986
8987   /* Tell the remote target to detach.  */
8988   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8989   putpkt (rs->buf);
8990   getpkt (&rs->buf, &rs->buf_size, 0);
8991
8992   switch (packet_ok (rs->buf,
8993                      &remote_protocol_packets[PACKET_vKill]))
8994     {
8995     case PACKET_OK:
8996       return 0;
8997     case PACKET_ERROR:
8998       return 1;
8999     case PACKET_UNKNOWN:
9000       return -1;
9001     default:
9002       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9003     }
9004 }
9005
9006 /* Send a kill request to the target using the 'k' packet.  */
9007
9008 static void
9009 remote_kill_k (void)
9010 {
9011   /* Catch errors so the user can quit from gdb even when we
9012      aren't on speaking terms with the remote system.  */
9013   TRY
9014     {
9015       putpkt ("k");
9016     }
9017   CATCH (ex, RETURN_MASK_ERROR)
9018     {
9019       if (ex.error == TARGET_CLOSE_ERROR)
9020         {
9021           /* If we got an (EOF) error that caused the target
9022              to go away, then we're done, that's what we wanted.
9023              "k" is susceptible to cause a premature EOF, given
9024              that the remote server isn't actually required to
9025              reply to "k", and it can happen that it doesn't
9026              even get to reply ACK to the "k".  */
9027           return;
9028         }
9029
9030       /* Otherwise, something went wrong.  We didn't actually kill
9031          the target.  Just propagate the exception, and let the
9032          user or higher layers decide what to do.  */
9033       throw_exception (ex);
9034     }
9035   END_CATCH
9036 }
9037
9038 static void
9039 remote_mourn (struct target_ops *target)
9040 {
9041   struct remote_state *rs = get_remote_state ();
9042
9043   /* In 'target remote' mode with one inferior, we close the connection.  */
9044   if (!rs->extended && number_of_live_inferiors () <= 1)
9045     {
9046       unpush_target (target);
9047
9048       /* remote_close takes care of doing most of the clean up.  */
9049       generic_mourn_inferior ();
9050       return;
9051     }
9052
9053   /* In case we got here due to an error, but we're going to stay
9054      connected.  */
9055   rs->waiting_for_stop_reply = 0;
9056
9057   /* If the current general thread belonged to the process we just
9058      detached from or has exited, the remote side current general
9059      thread becomes undefined.  Considering a case like this:
9060
9061      - We just got here due to a detach.
9062      - The process that we're detaching from happens to immediately
9063        report a global breakpoint being hit in non-stop mode, in the
9064        same thread we had selected before.
9065      - GDB attaches to this process again.
9066      - This event happens to be the next event we handle.
9067
9068      GDB would consider that the current general thread didn't need to
9069      be set on the stub side (with Hg), since for all it knew,
9070      GENERAL_THREAD hadn't changed.
9071
9072      Notice that although in all-stop mode, the remote server always
9073      sets the current thread to the thread reporting the stop event,
9074      that doesn't happen in non-stop mode; in non-stop, the stub *must
9075      not* change the current thread when reporting a breakpoint hit,
9076      due to the decoupling of event reporting and event handling.
9077
9078      To keep things simple, we always invalidate our notion of the
9079      current thread.  */
9080   record_currthread (rs, minus_one_ptid);
9081
9082   /* Call common code to mark the inferior as not running.  */
9083   generic_mourn_inferior ();
9084
9085   if (!have_inferiors ())
9086     {
9087       if (!remote_multi_process_p (rs))
9088         {
9089           /* Check whether the target is running now - some remote stubs
9090              automatically restart after kill.  */
9091           putpkt ("?");
9092           getpkt (&rs->buf, &rs->buf_size, 0);
9093
9094           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9095             {
9096               /* Assume that the target has been restarted.  Set
9097                  inferior_ptid so that bits of core GDB realizes
9098                  there's something here, e.g., so that the user can
9099                  say "kill" again.  */
9100               inferior_ptid = magic_null_ptid;
9101             }
9102         }
9103     }
9104 }
9105
9106 static int
9107 extended_remote_supports_disable_randomization (struct target_ops *self)
9108 {
9109   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9110 }
9111
9112 static void
9113 extended_remote_disable_randomization (int val)
9114 {
9115   struct remote_state *rs = get_remote_state ();
9116   char *reply;
9117
9118   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9119              val);
9120   putpkt (rs->buf);
9121   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9122   if (*reply == '\0')
9123     error (_("Target does not support QDisableRandomization."));
9124   if (strcmp (reply, "OK") != 0)
9125     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9126 }
9127
9128 static int
9129 extended_remote_run (char *args)
9130 {
9131   struct remote_state *rs = get_remote_state ();
9132   int len;
9133   const char *remote_exec_file = get_remote_exec_file ();
9134
9135   /* If the user has disabled vRun support, or we have detected that
9136      support is not available, do not try it.  */
9137   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9138     return -1;
9139
9140   strcpy (rs->buf, "vRun;");
9141   len = strlen (rs->buf);
9142
9143   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9144     error (_("Remote file name too long for run packet"));
9145   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9146                       strlen (remote_exec_file));
9147
9148   gdb_assert (args != NULL);
9149   if (*args)
9150     {
9151       struct cleanup *back_to;
9152       int i;
9153       char **argv;
9154
9155       argv = gdb_buildargv (args);
9156       back_to = make_cleanup_freeargv (argv);
9157       for (i = 0; argv[i] != NULL; i++)
9158         {
9159           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9160             error (_("Argument list too long for run packet"));
9161           rs->buf[len++] = ';';
9162           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9163                               strlen (argv[i]));
9164         }
9165       do_cleanups (back_to);
9166     }
9167
9168   rs->buf[len++] = '\0';
9169
9170   putpkt (rs->buf);
9171   getpkt (&rs->buf, &rs->buf_size, 0);
9172
9173   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9174     {
9175     case PACKET_OK:
9176       /* We have a wait response.  All is well.  */
9177       return 0;
9178     case PACKET_UNKNOWN:
9179       return -1;
9180     case PACKET_ERROR:
9181       if (remote_exec_file[0] == '\0')
9182         error (_("Running the default executable on the remote target failed; "
9183                  "try \"set remote exec-file\"?"));
9184       else
9185         error (_("Running \"%s\" on the remote target failed"),
9186                remote_exec_file);
9187     default:
9188       gdb_assert_not_reached (_("bad switch"));
9189     }
9190 }
9191
9192 /* In the extended protocol we want to be able to do things like
9193    "run" and have them basically work as expected.  So we need
9194    a special create_inferior function.  We support changing the
9195    executable file and the command line arguments, but not the
9196    environment.  */
9197
9198 static void
9199 extended_remote_create_inferior (struct target_ops *ops,
9200                                  char *exec_file, char *args,
9201                                  char **env, int from_tty)
9202 {
9203   int run_worked;
9204   char *stop_reply;
9205   struct remote_state *rs = get_remote_state ();
9206   const char *remote_exec_file = get_remote_exec_file ();
9207
9208   /* If running asynchronously, register the target file descriptor
9209      with the event loop.  */
9210   if (target_can_async_p ())
9211     target_async (1);
9212
9213   /* Disable address space randomization if requested (and supported).  */
9214   if (extended_remote_supports_disable_randomization (ops))
9215     extended_remote_disable_randomization (disable_randomization);
9216
9217   /* Now restart the remote server.  */
9218   run_worked = extended_remote_run (args) != -1;
9219   if (!run_worked)
9220     {
9221       /* vRun was not supported.  Fail if we need it to do what the
9222          user requested.  */
9223       if (remote_exec_file[0])
9224         error (_("Remote target does not support \"set remote exec-file\""));
9225       if (args[0])
9226         error (_("Remote target does not support \"set args\" or run <ARGS>"));
9227
9228       /* Fall back to "R".  */
9229       extended_remote_restart ();
9230     }
9231
9232   if (!have_inferiors ())
9233     {
9234       /* Clean up from the last time we ran, before we mark the target
9235          running again.  This will mark breakpoints uninserted, and
9236          get_offsets may insert breakpoints.  */
9237       init_thread_list ();
9238       init_wait_for_inferior ();
9239     }
9240
9241   /* vRun's success return is a stop reply.  */
9242   stop_reply = run_worked ? rs->buf : NULL;
9243   add_current_inferior_and_thread (stop_reply);
9244
9245   /* Get updated offsets, if the stub uses qOffsets.  */
9246   get_offsets ();
9247 }
9248 \f
9249
9250 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
9251    the list of conditions (in agent expression bytecode format), if any, the
9252    target needs to evaluate.  The output is placed into the packet buffer
9253    started from BUF and ended at BUF_END.  */
9254
9255 static int
9256 remote_add_target_side_condition (struct gdbarch *gdbarch,
9257                                   struct bp_target_info *bp_tgt, char *buf,
9258                                   char *buf_end)
9259 {
9260   struct agent_expr *aexpr = NULL;
9261   int i, ix;
9262
9263   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9264     return 0;
9265
9266   buf += strlen (buf);
9267   xsnprintf (buf, buf_end - buf, "%s", ";");
9268   buf++;
9269
9270   /* Send conditions to the target and free the vector.  */
9271   for (ix = 0;
9272        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9273        ix++)
9274     {
9275       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9276       buf += strlen (buf);
9277       for (i = 0; i < aexpr->len; ++i)
9278         buf = pack_hex_byte (buf, aexpr->buf[i]);
9279       *buf = '\0';
9280     }
9281   return 0;
9282 }
9283
9284 static void
9285 remote_add_target_side_commands (struct gdbarch *gdbarch,
9286                                  struct bp_target_info *bp_tgt, char *buf)
9287 {
9288   struct agent_expr *aexpr = NULL;
9289   int i, ix;
9290
9291   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9292     return;
9293
9294   buf += strlen (buf);
9295
9296   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9297   buf += strlen (buf);
9298
9299   /* Concatenate all the agent expressions that are commands into the
9300      cmds parameter.  */
9301   for (ix = 0;
9302        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9303        ix++)
9304     {
9305       sprintf (buf, "X%x,", aexpr->len);
9306       buf += strlen (buf);
9307       for (i = 0; i < aexpr->len; ++i)
9308         buf = pack_hex_byte (buf, aexpr->buf[i]);
9309       *buf = '\0';
9310     }
9311 }
9312
9313 /* Insert a breakpoint.  On targets that have software breakpoint
9314    support, we ask the remote target to do the work; on targets
9315    which don't, we insert a traditional memory breakpoint.  */
9316
9317 static int
9318 remote_insert_breakpoint (struct target_ops *ops,
9319                           struct gdbarch *gdbarch,
9320                           struct bp_target_info *bp_tgt)
9321 {
9322   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9323      If it succeeds, then set the support to PACKET_ENABLE.  If it
9324      fails, and the user has explicitly requested the Z support then
9325      report an error, otherwise, mark it disabled and go on.  */
9326
9327   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9328     {
9329       CORE_ADDR addr = bp_tgt->reqstd_address;
9330       struct remote_state *rs;
9331       char *p, *endbuf;
9332       int bpsize;
9333
9334       /* Make sure the remote is pointing at the right process, if
9335          necessary.  */
9336       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9337         set_general_process ();
9338
9339       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9340
9341       rs = get_remote_state ();
9342       p = rs->buf;
9343       endbuf = rs->buf + get_remote_packet_size ();
9344
9345       *(p++) = 'Z';
9346       *(p++) = '0';
9347       *(p++) = ',';
9348       addr = (ULONGEST) remote_address_masked (addr);
9349       p += hexnumstr (p, addr);
9350       xsnprintf (p, endbuf - p, ",%d", bpsize);
9351
9352       if (remote_supports_cond_breakpoints (ops))
9353         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9354
9355       if (remote_can_run_breakpoint_commands (ops))
9356         remote_add_target_side_commands (gdbarch, bp_tgt, p);
9357
9358       putpkt (rs->buf);
9359       getpkt (&rs->buf, &rs->buf_size, 0);
9360
9361       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9362         {
9363         case PACKET_ERROR:
9364           return -1;
9365         case PACKET_OK:
9366           bp_tgt->placed_address = addr;
9367           bp_tgt->placed_size = bpsize;
9368           return 0;
9369         case PACKET_UNKNOWN:
9370           break;
9371         }
9372     }
9373
9374   /* If this breakpoint has target-side commands but this stub doesn't
9375      support Z0 packets, throw error.  */
9376   if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9377     throw_error (NOT_SUPPORTED_ERROR, _("\
9378 Target doesn't support breakpoints that have target side commands."));
9379
9380   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9381 }
9382
9383 static int
9384 remote_remove_breakpoint (struct target_ops *ops,
9385                           struct gdbarch *gdbarch,
9386                           struct bp_target_info *bp_tgt)
9387 {
9388   CORE_ADDR addr = bp_tgt->placed_address;
9389   struct remote_state *rs = get_remote_state ();
9390
9391   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9392     {
9393       char *p = rs->buf;
9394       char *endbuf = rs->buf + get_remote_packet_size ();
9395
9396       /* Make sure the remote is pointing at the right process, if
9397          necessary.  */
9398       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9399         set_general_process ();
9400
9401       *(p++) = 'z';
9402       *(p++) = '0';
9403       *(p++) = ',';
9404
9405       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9406       p += hexnumstr (p, addr);
9407       xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9408
9409       putpkt (rs->buf);
9410       getpkt (&rs->buf, &rs->buf_size, 0);
9411
9412       return (rs->buf[0] == 'E');
9413     }
9414
9415   return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9416 }
9417
9418 static enum Z_packet_type
9419 watchpoint_to_Z_packet (int type)
9420 {
9421   switch (type)
9422     {
9423     case hw_write:
9424       return Z_PACKET_WRITE_WP;
9425       break;
9426     case hw_read:
9427       return Z_PACKET_READ_WP;
9428       break;
9429     case hw_access:
9430       return Z_PACKET_ACCESS_WP;
9431       break;
9432     default:
9433       internal_error (__FILE__, __LINE__,
9434                       _("hw_bp_to_z: bad watchpoint type %d"), type);
9435     }
9436 }
9437
9438 static int
9439 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9440                           enum target_hw_bp_type type, struct expression *cond)
9441 {
9442   struct remote_state *rs = get_remote_state ();
9443   char *endbuf = rs->buf + get_remote_packet_size ();
9444   char *p;
9445   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9446
9447   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9448     return 1;
9449
9450   /* Make sure the remote is pointing at the right process, if
9451      necessary.  */
9452   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9453     set_general_process ();
9454
9455   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9456   p = strchr (rs->buf, '\0');
9457   addr = remote_address_masked (addr);
9458   p += hexnumstr (p, (ULONGEST) addr);
9459   xsnprintf (p, endbuf - p, ",%x", len);
9460
9461   putpkt (rs->buf);
9462   getpkt (&rs->buf, &rs->buf_size, 0);
9463
9464   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9465     {
9466     case PACKET_ERROR:
9467       return -1;
9468     case PACKET_UNKNOWN:
9469       return 1;
9470     case PACKET_OK:
9471       return 0;
9472     }
9473   internal_error (__FILE__, __LINE__,
9474                   _("remote_insert_watchpoint: reached end of function"));
9475 }
9476
9477 static int
9478 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9479                                      CORE_ADDR start, int length)
9480 {
9481   CORE_ADDR diff = remote_address_masked (addr - start);
9482
9483   return diff < length;
9484 }
9485
9486
9487 static int
9488 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9489                           enum target_hw_bp_type type, struct expression *cond)
9490 {
9491   struct remote_state *rs = get_remote_state ();
9492   char *endbuf = rs->buf + get_remote_packet_size ();
9493   char *p;
9494   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9495
9496   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9497     return -1;
9498
9499   /* Make sure the remote is pointing at the right process, if
9500      necessary.  */
9501   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9502     set_general_process ();
9503
9504   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9505   p = strchr (rs->buf, '\0');
9506   addr = remote_address_masked (addr);
9507   p += hexnumstr (p, (ULONGEST) addr);
9508   xsnprintf (p, endbuf - p, ",%x", len);
9509   putpkt (rs->buf);
9510   getpkt (&rs->buf, &rs->buf_size, 0);
9511
9512   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9513     {
9514     case PACKET_ERROR:
9515     case PACKET_UNKNOWN:
9516       return -1;
9517     case PACKET_OK:
9518       return 0;
9519     }
9520   internal_error (__FILE__, __LINE__,
9521                   _("remote_remove_watchpoint: reached end of function"));
9522 }
9523
9524
9525 int remote_hw_watchpoint_limit = -1;
9526 int remote_hw_watchpoint_length_limit = -1;
9527 int remote_hw_breakpoint_limit = -1;
9528
9529 static int
9530 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9531                                     CORE_ADDR addr, int len)
9532 {
9533   if (remote_hw_watchpoint_length_limit == 0)
9534     return 0;
9535   else if (remote_hw_watchpoint_length_limit < 0)
9536     return 1;
9537   else if (len <= remote_hw_watchpoint_length_limit)
9538     return 1;
9539   else
9540     return 0;
9541 }
9542
9543 static int
9544 remote_check_watch_resources (struct target_ops *self,
9545                               enum bptype type, int cnt, int ot)
9546 {
9547   if (type == bp_hardware_breakpoint)
9548     {
9549       if (remote_hw_breakpoint_limit == 0)
9550         return 0;
9551       else if (remote_hw_breakpoint_limit < 0)
9552         return 1;
9553       else if (cnt <= remote_hw_breakpoint_limit)
9554         return 1;
9555     }
9556   else
9557     {
9558       if (remote_hw_watchpoint_limit == 0)
9559         return 0;
9560       else if (remote_hw_watchpoint_limit < 0)
9561         return 1;
9562       else if (ot)
9563         return -1;
9564       else if (cnt <= remote_hw_watchpoint_limit)
9565         return 1;
9566     }
9567   return -1;
9568 }
9569
9570 /* The to_stopped_by_sw_breakpoint method of target remote.  */
9571
9572 static int
9573 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9574 {
9575   struct thread_info *thread = inferior_thread ();
9576
9577   return (thread->priv != NULL
9578           && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9579 }
9580
9581 /* The to_supports_stopped_by_sw_breakpoint method of target
9582    remote.  */
9583
9584 static int
9585 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9586 {
9587   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9588 }
9589
9590 /* The to_stopped_by_hw_breakpoint method of target remote.  */
9591
9592 static int
9593 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9594 {
9595   struct thread_info *thread = inferior_thread ();
9596
9597   return (thread->priv != NULL
9598           && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9599 }
9600
9601 /* The to_supports_stopped_by_hw_breakpoint method of target
9602    remote.  */
9603
9604 static int
9605 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9606 {
9607   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9608 }
9609
9610 static int
9611 remote_stopped_by_watchpoint (struct target_ops *ops)
9612 {
9613   struct thread_info *thread = inferior_thread ();
9614
9615   return (thread->priv != NULL
9616           && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9617 }
9618
9619 static int
9620 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9621 {
9622   struct thread_info *thread = inferior_thread ();
9623
9624   if (thread->priv != NULL
9625       && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9626     {
9627       *addr_p = thread->priv->watch_data_address;
9628       return 1;
9629     }
9630
9631   return 0;
9632 }
9633
9634
9635 static int
9636 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9637                              struct bp_target_info *bp_tgt)
9638 {
9639   CORE_ADDR addr = bp_tgt->reqstd_address;
9640   struct remote_state *rs;
9641   char *p, *endbuf;
9642   char *message;
9643   int bpsize;
9644
9645   /* The length field should be set to the size of a breakpoint
9646      instruction, even though we aren't inserting one ourselves.  */
9647
9648   gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9649
9650   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9651     return -1;
9652
9653   /* Make sure the remote is pointing at the right process, if
9654      necessary.  */
9655   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9656     set_general_process ();
9657
9658   rs = get_remote_state ();
9659   p = rs->buf;
9660   endbuf = rs->buf + get_remote_packet_size ();
9661
9662   *(p++) = 'Z';
9663   *(p++) = '1';
9664   *(p++) = ',';
9665
9666   addr = remote_address_masked (addr);
9667   p += hexnumstr (p, (ULONGEST) addr);
9668   xsnprintf (p, endbuf - p, ",%x", bpsize);
9669
9670   if (remote_supports_cond_breakpoints (self))
9671     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9672
9673   if (remote_can_run_breakpoint_commands (self))
9674     remote_add_target_side_commands (gdbarch, bp_tgt, p);
9675
9676   putpkt (rs->buf);
9677   getpkt (&rs->buf, &rs->buf_size, 0);
9678
9679   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9680     {
9681     case PACKET_ERROR:
9682       if (rs->buf[1] == '.')
9683         {
9684           message = strchr (rs->buf + 2, '.');
9685           if (message)
9686             error (_("Remote failure reply: %s"), message + 1);
9687         }
9688       return -1;
9689     case PACKET_UNKNOWN:
9690       return -1;
9691     case PACKET_OK:
9692       bp_tgt->placed_address = addr;
9693       bp_tgt->placed_size = bpsize;
9694       return 0;
9695     }
9696   internal_error (__FILE__, __LINE__,
9697                   _("remote_insert_hw_breakpoint: reached end of function"));
9698 }
9699
9700
9701 static int
9702 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9703                              struct bp_target_info *bp_tgt)
9704 {
9705   CORE_ADDR addr;
9706   struct remote_state *rs = get_remote_state ();
9707   char *p = rs->buf;
9708   char *endbuf = rs->buf + get_remote_packet_size ();
9709
9710   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9711     return -1;
9712
9713   /* Make sure the remote is pointing at the right process, if
9714      necessary.  */
9715   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9716     set_general_process ();
9717
9718   *(p++) = 'z';
9719   *(p++) = '1';
9720   *(p++) = ',';
9721
9722   addr = remote_address_masked (bp_tgt->placed_address);
9723   p += hexnumstr (p, (ULONGEST) addr);
9724   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);
9725
9726   putpkt (rs->buf);
9727   getpkt (&rs->buf, &rs->buf_size, 0);
9728
9729   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9730     {
9731     case PACKET_ERROR:
9732     case PACKET_UNKNOWN:
9733       return -1;
9734     case PACKET_OK:
9735       return 0;
9736     }
9737   internal_error (__FILE__, __LINE__,
9738                   _("remote_remove_hw_breakpoint: reached end of function"));
9739 }
9740
9741 /* Verify memory using the "qCRC:" request.  */
9742
9743 static int
9744 remote_verify_memory (struct target_ops *ops,
9745                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9746 {
9747   struct remote_state *rs = get_remote_state ();
9748   unsigned long host_crc, target_crc;
9749   char *tmp;
9750
9751   /* It doesn't make sense to use qCRC if the remote target is
9752      connected but not running.  */
9753   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9754     {
9755       enum packet_result result;
9756
9757       /* Make sure the remote is pointing at the right process.  */
9758       set_general_process ();
9759
9760       /* FIXME: assumes lma can fit into long.  */
9761       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9762                  (long) lma, (long) size);
9763       putpkt (rs->buf);
9764
9765       /* Be clever; compute the host_crc before waiting for target
9766          reply.  */
9767       host_crc = xcrc32 (data, size, 0xffffffff);
9768
9769       getpkt (&rs->buf, &rs->buf_size, 0);
9770
9771       result = packet_ok (rs->buf,
9772                           &remote_protocol_packets[PACKET_qCRC]);
9773       if (result == PACKET_ERROR)
9774         return -1;
9775       else if (result == PACKET_OK)
9776         {
9777           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9778             target_crc = target_crc * 16 + fromhex (*tmp);
9779
9780           return (host_crc == target_crc);
9781         }
9782     }
9783
9784   return simple_verify_memory (ops, data, lma, size);
9785 }
9786
9787 /* compare-sections command
9788
9789    With no arguments, compares each loadable section in the exec bfd
9790    with the same memory range on the target, and reports mismatches.
9791    Useful for verifying the image on the target against the exec file.  */
9792
9793 static void
9794 compare_sections_command (char *args, int from_tty)
9795 {
9796   asection *s;
9797   struct cleanup *old_chain;
9798   gdb_byte *sectdata;
9799   const char *sectname;
9800   bfd_size_type size;
9801   bfd_vma lma;
9802   int matched = 0;
9803   int mismatched = 0;
9804   int res;
9805   int read_only = 0;
9806
9807   if (!exec_bfd)
9808     error (_("command cannot be used without an exec file"));
9809
9810   /* Make sure the remote is pointing at the right process.  */
9811   set_general_process ();
9812
9813   if (args != NULL && strcmp (args, "-r") == 0)
9814     {
9815       read_only = 1;
9816       args = NULL;
9817     }
9818
9819   for (s = exec_bfd->sections; s; s = s->next)
9820     {
9821       if (!(s->flags & SEC_LOAD))
9822         continue;               /* Skip non-loadable section.  */
9823
9824       if (read_only && (s->flags & SEC_READONLY) == 0)
9825         continue;               /* Skip writeable sections */
9826
9827       size = bfd_get_section_size (s);
9828       if (size == 0)
9829         continue;               /* Skip zero-length section.  */
9830
9831       sectname = bfd_get_section_name (exec_bfd, s);
9832       if (args && strcmp (args, sectname) != 0)
9833         continue;               /* Not the section selected by user.  */
9834
9835       matched = 1;              /* Do this section.  */
9836       lma = s->lma;
9837
9838       sectdata = (gdb_byte *) xmalloc (size);
9839       old_chain = make_cleanup (xfree, sectdata);
9840       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9841
9842       res = target_verify_memory (sectdata, lma, size);
9843
9844       if (res == -1)
9845         error (_("target memory fault, section %s, range %s -- %s"), sectname,
9846                paddress (target_gdbarch (), lma),
9847                paddress (target_gdbarch (), lma + size));
9848
9849       printf_filtered ("Section %s, range %s -- %s: ", sectname,
9850                        paddress (target_gdbarch (), lma),
9851                        paddress (target_gdbarch (), lma + size));
9852       if (res)
9853         printf_filtered ("matched.\n");
9854       else
9855         {
9856           printf_filtered ("MIS-MATCHED!\n");
9857           mismatched++;
9858         }
9859
9860       do_cleanups (old_chain);
9861     }
9862   if (mismatched > 0)
9863     warning (_("One or more sections of the target image does not match\n\
9864 the loaded file\n"));
9865   if (args && !matched)
9866     printf_filtered (_("No loaded section named '%s'.\n"), args);
9867 }
9868
9869 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9870    into remote target.  The number of bytes written to the remote
9871    target is returned, or -1 for error.  */
9872
9873 static enum target_xfer_status
9874 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9875                     const char *annex, const gdb_byte *writebuf, 
9876                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9877                     struct packet_config *packet)
9878 {
9879   int i, buf_len;
9880   ULONGEST n;
9881   struct remote_state *rs = get_remote_state ();
9882   int max_size = get_memory_write_packet_size (); 
9883
9884   if (packet->support == PACKET_DISABLE)
9885     return TARGET_XFER_E_IO;
9886
9887   /* Insert header.  */
9888   i = snprintf (rs->buf, max_size, 
9889                 "qXfer:%s:write:%s:%s:",
9890                 object_name, annex ? annex : "",
9891                 phex_nz (offset, sizeof offset));
9892   max_size -= (i + 1);
9893
9894   /* Escape as much data as fits into rs->buf.  */
9895   buf_len = remote_escape_output 
9896     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9897
9898   if (putpkt_binary (rs->buf, i + buf_len) < 0
9899       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9900       || packet_ok (rs->buf, packet) != PACKET_OK)
9901     return TARGET_XFER_E_IO;
9902
9903   unpack_varlen_hex (rs->buf, &n);
9904
9905   *xfered_len = n;
9906   return TARGET_XFER_OK;
9907 }
9908
9909 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9910    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9911    number of bytes read is returned, or 0 for EOF, or -1 for error.
9912    The number of bytes read may be less than LEN without indicating an
9913    EOF.  PACKET is checked and updated to indicate whether the remote
9914    target supports this object.  */
9915
9916 static enum target_xfer_status
9917 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9918                    const char *annex,
9919                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9920                    ULONGEST *xfered_len,
9921                    struct packet_config *packet)
9922 {
9923   struct remote_state *rs = get_remote_state ();
9924   LONGEST i, n, packet_len;
9925
9926   if (packet->support == PACKET_DISABLE)
9927     return TARGET_XFER_E_IO;
9928
9929   /* Check whether we've cached an end-of-object packet that matches
9930      this request.  */
9931   if (rs->finished_object)
9932     {
9933       if (strcmp (object_name, rs->finished_object) == 0
9934           && strcmp (annex ? annex : "", rs->finished_annex) == 0
9935           && offset == rs->finished_offset)
9936         return TARGET_XFER_EOF;
9937
9938
9939       /* Otherwise, we're now reading something different.  Discard
9940          the cache.  */
9941       xfree (rs->finished_object);
9942       xfree (rs->finished_annex);
9943       rs->finished_object = NULL;
9944       rs->finished_annex = NULL;
9945     }
9946
9947   /* Request only enough to fit in a single packet.  The actual data
9948      may not, since we don't know how much of it will need to be escaped;
9949      the target is free to respond with slightly less data.  We subtract
9950      five to account for the response type and the protocol frame.  */
9951   n = min (get_remote_packet_size () - 5, len);
9952   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9953             object_name, annex ? annex : "",
9954             phex_nz (offset, sizeof offset),
9955             phex_nz (n, sizeof n));
9956   i = putpkt (rs->buf);
9957   if (i < 0)
9958     return TARGET_XFER_E_IO;
9959
9960   rs->buf[0] = '\0';
9961   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9962   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9963     return TARGET_XFER_E_IO;
9964
9965   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9966     error (_("Unknown remote qXfer reply: %s"), rs->buf);
9967
9968   /* 'm' means there is (or at least might be) more data after this
9969      batch.  That does not make sense unless there's at least one byte
9970      of data in this reply.  */
9971   if (rs->buf[0] == 'm' && packet_len == 1)
9972     error (_("Remote qXfer reply contained no data."));
9973
9974   /* Got some data.  */
9975   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9976                              packet_len - 1, readbuf, n);
9977
9978   /* 'l' is an EOF marker, possibly including a final block of data,
9979      or possibly empty.  If we have the final block of a non-empty
9980      object, record this fact to bypass a subsequent partial read.  */
9981   if (rs->buf[0] == 'l' && offset + i > 0)
9982     {
9983       rs->finished_object = xstrdup (object_name);
9984       rs->finished_annex = xstrdup (annex ? annex : "");
9985       rs->finished_offset = offset + i;
9986     }
9987
9988   if (i == 0)
9989     return TARGET_XFER_EOF;
9990   else
9991     {
9992       *xfered_len = i;
9993       return TARGET_XFER_OK;
9994     }
9995 }
9996
9997 static enum target_xfer_status
9998 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9999                      const char *annex, gdb_byte *readbuf,
10000                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10001                      ULONGEST *xfered_len)
10002 {
10003   struct remote_state *rs;
10004   int i;
10005   char *p2;
10006   char query_type;
10007   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10008
10009   set_remote_traceframe ();
10010   set_general_thread (inferior_ptid);
10011
10012   rs = get_remote_state ();
10013
10014   /* Handle memory using the standard memory routines.  */
10015   if (object == TARGET_OBJECT_MEMORY)
10016     {
10017       /* If the remote target is connected but not running, we should
10018          pass this request down to a lower stratum (e.g. the executable
10019          file).  */
10020       if (!target_has_execution)
10021         return TARGET_XFER_EOF;
10022
10023       if (writebuf != NULL)
10024         return remote_write_bytes (offset, writebuf, len, unit_size,
10025                                    xfered_len);
10026       else
10027         return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10028                                   xfered_len);
10029     }
10030
10031   /* Handle SPU memory using qxfer packets.  */
10032   if (object == TARGET_OBJECT_SPU)
10033     {
10034       if (readbuf)
10035         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
10036                                   xfered_len, &remote_protocol_packets
10037                                   [PACKET_qXfer_spu_read]);
10038       else
10039         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
10040                                    xfered_len, &remote_protocol_packets
10041                                    [PACKET_qXfer_spu_write]);
10042     }
10043
10044   /* Handle extra signal info using qxfer packets.  */
10045   if (object == TARGET_OBJECT_SIGNAL_INFO)
10046     {
10047       if (readbuf)
10048         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10049                                   xfered_len, &remote_protocol_packets
10050                                   [PACKET_qXfer_siginfo_read]);
10051       else
10052         return remote_write_qxfer (ops, "siginfo", annex,
10053                                    writebuf, offset, len, xfered_len,
10054                                    &remote_protocol_packets
10055                                    [PACKET_qXfer_siginfo_write]);
10056     }
10057
10058   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10059     {
10060       if (readbuf)
10061         return remote_read_qxfer (ops, "statictrace", annex,
10062                                   readbuf, offset, len, xfered_len,
10063                                   &remote_protocol_packets
10064                                   [PACKET_qXfer_statictrace_read]);
10065       else
10066         return TARGET_XFER_E_IO;
10067     }
10068
10069   /* Only handle flash writes.  */
10070   if (writebuf != NULL)
10071     {
10072       switch (object)
10073         {
10074         case TARGET_OBJECT_FLASH:
10075           return remote_flash_write (ops, offset, len, xfered_len,
10076                                      writebuf);
10077
10078         default:
10079           return TARGET_XFER_E_IO;
10080         }
10081     }
10082
10083   /* Map pre-existing objects onto letters.  DO NOT do this for new
10084      objects!!!  Instead specify new query packets.  */
10085   switch (object)
10086     {
10087     case TARGET_OBJECT_AVR:
10088       query_type = 'R';
10089       break;
10090
10091     case TARGET_OBJECT_AUXV:
10092       gdb_assert (annex == NULL);
10093       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10094                                 xfered_len,
10095                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10096
10097     case TARGET_OBJECT_AVAILABLE_FEATURES:
10098       return remote_read_qxfer
10099         (ops, "features", annex, readbuf, offset, len, xfered_len,
10100          &remote_protocol_packets[PACKET_qXfer_features]);
10101
10102     case TARGET_OBJECT_LIBRARIES:
10103       return remote_read_qxfer
10104         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10105          &remote_protocol_packets[PACKET_qXfer_libraries]);
10106
10107     case TARGET_OBJECT_LIBRARIES_SVR4:
10108       return remote_read_qxfer
10109         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10110          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10111
10112     case TARGET_OBJECT_MEMORY_MAP:
10113       gdb_assert (annex == NULL);
10114       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10115                                  xfered_len,
10116                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10117
10118     case TARGET_OBJECT_OSDATA:
10119       /* Should only get here if we're connected.  */
10120       gdb_assert (rs->remote_desc);
10121       return remote_read_qxfer
10122         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10123         &remote_protocol_packets[PACKET_qXfer_osdata]);
10124
10125     case TARGET_OBJECT_THREADS:
10126       gdb_assert (annex == NULL);
10127       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10128                                 xfered_len,
10129                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10130
10131     case TARGET_OBJECT_TRACEFRAME_INFO:
10132       gdb_assert (annex == NULL);
10133       return remote_read_qxfer
10134         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10135          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10136
10137     case TARGET_OBJECT_FDPIC:
10138       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10139                                 xfered_len,
10140                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10141
10142     case TARGET_OBJECT_OPENVMS_UIB:
10143       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10144                                 xfered_len,
10145                                 &remote_protocol_packets[PACKET_qXfer_uib]);
10146
10147     case TARGET_OBJECT_BTRACE:
10148       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10149                                 xfered_len,
10150         &remote_protocol_packets[PACKET_qXfer_btrace]);
10151
10152     case TARGET_OBJECT_BTRACE_CONF:
10153       return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10154                                 len, xfered_len,
10155         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10156
10157     case TARGET_OBJECT_EXEC_FILE:
10158       return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10159                                 len, xfered_len,
10160         &remote_protocol_packets[PACKET_qXfer_exec_file]);
10161
10162     default:
10163       return TARGET_XFER_E_IO;
10164     }
10165
10166   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
10167      large enough let the caller deal with it.  */
10168   if (len < get_remote_packet_size ())
10169     return TARGET_XFER_E_IO;
10170   len = get_remote_packet_size ();
10171
10172   /* Except for querying the minimum buffer size, target must be open.  */
10173   if (!rs->remote_desc)
10174     error (_("remote query is only available after target open"));
10175
10176   gdb_assert (annex != NULL);
10177   gdb_assert (readbuf != NULL);
10178
10179   p2 = rs->buf;
10180   *p2++ = 'q';
10181   *p2++ = query_type;
10182
10183   /* We used one buffer char for the remote protocol q command and
10184      another for the query type.  As the remote protocol encapsulation
10185      uses 4 chars plus one extra in case we are debugging
10186      (remote_debug), we have PBUFZIZ - 7 left to pack the query
10187      string.  */
10188   i = 0;
10189   while (annex[i] && (i < (get_remote_packet_size () - 8)))
10190     {
10191       /* Bad caller may have sent forbidden characters.  */
10192       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10193       *p2++ = annex[i];
10194       i++;
10195     }
10196   *p2 = '\0';
10197   gdb_assert (annex[i] == '\0');
10198
10199   i = putpkt (rs->buf);
10200   if (i < 0)
10201     return TARGET_XFER_E_IO;
10202
10203   getpkt (&rs->buf, &rs->buf_size, 0);
10204   strcpy ((char *) readbuf, rs->buf);
10205
10206   *xfered_len = strlen ((char *) readbuf);
10207   return TARGET_XFER_OK;
10208 }
10209
10210 static int
10211 remote_search_memory (struct target_ops* ops,
10212                       CORE_ADDR start_addr, ULONGEST search_space_len,
10213                       const gdb_byte *pattern, ULONGEST pattern_len,
10214                       CORE_ADDR *found_addrp)
10215 {
10216   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10217   struct remote_state *rs = get_remote_state ();
10218   int max_size = get_memory_write_packet_size ();
10219   struct packet_config *packet =
10220     &remote_protocol_packets[PACKET_qSearch_memory];
10221   /* Number of packet bytes used to encode the pattern;
10222      this could be more than PATTERN_LEN due to escape characters.  */
10223   int escaped_pattern_len;
10224   /* Amount of pattern that was encodable in the packet.  */
10225   int used_pattern_len;
10226   int i;
10227   int found;
10228   ULONGEST found_addr;
10229
10230   /* Don't go to the target if we don't have to.
10231      This is done before checking packet->support to avoid the possibility that
10232      a success for this edge case means the facility works in general.  */
10233   if (pattern_len > search_space_len)
10234     return 0;
10235   if (pattern_len == 0)
10236     {
10237       *found_addrp = start_addr;
10238       return 1;
10239     }
10240
10241   /* If we already know the packet isn't supported, fall back to the simple
10242      way of searching memory.  */
10243
10244   if (packet_config_support (packet) == PACKET_DISABLE)
10245     {
10246       /* Target doesn't provided special support, fall back and use the
10247          standard support (copy memory and do the search here).  */
10248       return simple_search_memory (ops, start_addr, search_space_len,
10249                                    pattern, pattern_len, found_addrp);
10250     }
10251
10252   /* Make sure the remote is pointing at the right process.  */
10253   set_general_process ();
10254
10255   /* Insert header.  */
10256   i = snprintf (rs->buf, max_size, 
10257                 "qSearch:memory:%s;%s;",
10258                 phex_nz (start_addr, addr_size),
10259                 phex_nz (search_space_len, sizeof (search_space_len)));
10260   max_size -= (i + 1);
10261
10262   /* Escape as much data as fits into rs->buf.  */
10263   escaped_pattern_len =
10264     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10265                           &used_pattern_len, max_size);
10266
10267   /* Bail if the pattern is too large.  */
10268   if (used_pattern_len != pattern_len)
10269     error (_("Pattern is too large to transmit to remote target."));
10270
10271   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10272       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10273       || packet_ok (rs->buf, packet) != PACKET_OK)
10274     {
10275       /* The request may not have worked because the command is not
10276          supported.  If so, fall back to the simple way.  */
10277       if (packet->support == PACKET_DISABLE)
10278         {
10279           return simple_search_memory (ops, start_addr, search_space_len,
10280                                        pattern, pattern_len, found_addrp);
10281         }
10282       return -1;
10283     }
10284
10285   if (rs->buf[0] == '0')
10286     found = 0;
10287   else if (rs->buf[0] == '1')
10288     {
10289       found = 1;
10290       if (rs->buf[1] != ',')
10291         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10292       unpack_varlen_hex (rs->buf + 2, &found_addr);
10293       *found_addrp = found_addr;
10294     }
10295   else
10296     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10297
10298   return found;
10299 }
10300
10301 static void
10302 remote_rcmd (struct target_ops *self, const char *command,
10303              struct ui_file *outbuf)
10304 {
10305   struct remote_state *rs = get_remote_state ();
10306   char *p = rs->buf;
10307
10308   if (!rs->remote_desc)
10309     error (_("remote rcmd is only available after target open"));
10310
10311   /* Send a NULL command across as an empty command.  */
10312   if (command == NULL)
10313     command = "";
10314
10315   /* The query prefix.  */
10316   strcpy (rs->buf, "qRcmd,");
10317   p = strchr (rs->buf, '\0');
10318
10319   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10320       > get_remote_packet_size ())
10321     error (_("\"monitor\" command ``%s'' is too long."), command);
10322
10323   /* Encode the actual command.  */
10324   bin2hex ((const gdb_byte *) command, p, strlen (command));
10325
10326   if (putpkt (rs->buf) < 0)
10327     error (_("Communication problem with target."));
10328
10329   /* get/display the response */
10330   while (1)
10331     {
10332       char *buf;
10333
10334       /* XXX - see also remote_get_noisy_reply().  */
10335       QUIT;                     /* Allow user to bail out with ^C.  */
10336       rs->buf[0] = '\0';
10337       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10338         { 
10339           /* Timeout.  Continue to (try to) read responses.
10340              This is better than stopping with an error, assuming the stub
10341              is still executing the (long) monitor command.
10342              If needed, the user can interrupt gdb using C-c, obtaining
10343              an effect similar to stop on timeout.  */
10344           continue;
10345         }
10346       buf = rs->buf;
10347       if (buf[0] == '\0')
10348         error (_("Target does not support this command."));
10349       if (buf[0] == 'O' && buf[1] != 'K')
10350         {
10351           remote_console_output (buf + 1); /* 'O' message from stub.  */
10352           continue;
10353         }
10354       if (strcmp (buf, "OK") == 0)
10355         break;
10356       if (strlen (buf) == 3 && buf[0] == 'E'
10357           && isdigit (buf[1]) && isdigit (buf[2]))
10358         {
10359           error (_("Protocol error with Rcmd"));
10360         }
10361       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10362         {
10363           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10364
10365           fputc_unfiltered (c, outbuf);
10366         }
10367       break;
10368     }
10369 }
10370
10371 static VEC(mem_region_s) *
10372 remote_memory_map (struct target_ops *ops)
10373 {
10374   VEC(mem_region_s) *result = NULL;
10375   char *text = target_read_stralloc (&current_target,
10376                                      TARGET_OBJECT_MEMORY_MAP, NULL);
10377
10378   if (text)
10379     {
10380       struct cleanup *back_to = make_cleanup (xfree, text);
10381
10382       result = parse_memory_map (text);
10383       do_cleanups (back_to);
10384     }
10385
10386   return result;
10387 }
10388
10389 static void
10390 packet_command (char *args, int from_tty)
10391 {
10392   struct remote_state *rs = get_remote_state ();
10393
10394   if (!rs->remote_desc)
10395     error (_("command can only be used with remote target"));
10396
10397   if (!args)
10398     error (_("remote-packet command requires packet text as argument"));
10399
10400   puts_filtered ("sending: ");
10401   print_packet (args);
10402   puts_filtered ("\n");
10403   putpkt (args);
10404
10405   getpkt (&rs->buf, &rs->buf_size, 0);
10406   puts_filtered ("received: ");
10407   print_packet (rs->buf);
10408   puts_filtered ("\n");
10409 }
10410
10411 #if 0
10412 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10413
10414 static void display_thread_info (struct gdb_ext_thread_info *info);
10415
10416 static void threadset_test_cmd (char *cmd, int tty);
10417
10418 static void threadalive_test (char *cmd, int tty);
10419
10420 static void threadlist_test_cmd (char *cmd, int tty);
10421
10422 int get_and_display_threadinfo (threadref *ref);
10423
10424 static void threadinfo_test_cmd (char *cmd, int tty);
10425
10426 static int thread_display_step (threadref *ref, void *context);
10427
10428 static void threadlist_update_test_cmd (char *cmd, int tty);
10429
10430 static void init_remote_threadtests (void);
10431
10432 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
10433
10434 static void
10435 threadset_test_cmd (char *cmd, int tty)
10436 {
10437   int sample_thread = SAMPLE_THREAD;
10438
10439   printf_filtered (_("Remote threadset test\n"));
10440   set_general_thread (sample_thread);
10441 }
10442
10443
10444 static void
10445 threadalive_test (char *cmd, int tty)
10446 {
10447   int sample_thread = SAMPLE_THREAD;
10448   int pid = ptid_get_pid (inferior_ptid);
10449   ptid_t ptid = ptid_build (pid, sample_thread, 0);
10450
10451   if (remote_thread_alive (ptid))
10452     printf_filtered ("PASS: Thread alive test\n");
10453   else
10454     printf_filtered ("FAIL: Thread alive test\n");
10455 }
10456
10457 void output_threadid (char *title, threadref *ref);
10458
10459 void
10460 output_threadid (char *title, threadref *ref)
10461 {
10462   char hexid[20];
10463
10464   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
10465   hexid[16] = 0;
10466   printf_filtered ("%s  %s\n", title, (&hexid[0]));
10467 }
10468
10469 static void
10470 threadlist_test_cmd (char *cmd, int tty)
10471 {
10472   int startflag = 1;
10473   threadref nextthread;
10474   int done, result_count;
10475   threadref threadlist[3];
10476
10477   printf_filtered ("Remote Threadlist test\n");
10478   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10479                               &result_count, &threadlist[0]))
10480     printf_filtered ("FAIL: threadlist test\n");
10481   else
10482     {
10483       threadref *scan = threadlist;
10484       threadref *limit = scan + result_count;
10485
10486       while (scan < limit)
10487         output_threadid (" thread ", scan++);
10488     }
10489 }
10490
10491 void
10492 display_thread_info (struct gdb_ext_thread_info *info)
10493 {
10494   output_threadid ("Threadid: ", &info->threadid);
10495   printf_filtered ("Name: %s\n ", info->shortname);
10496   printf_filtered ("State: %s\n", info->display);
10497   printf_filtered ("other: %s\n\n", info->more_display);
10498 }
10499
10500 int
10501 get_and_display_threadinfo (threadref *ref)
10502 {
10503   int result;
10504   int set;
10505   struct gdb_ext_thread_info threadinfo;
10506
10507   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10508     | TAG_MOREDISPLAY | TAG_DISPLAY;
10509   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10510     display_thread_info (&threadinfo);
10511   return result;
10512 }
10513
10514 static void
10515 threadinfo_test_cmd (char *cmd, int tty)
10516 {
10517   int athread = SAMPLE_THREAD;
10518   threadref thread;
10519   int set;
10520
10521   int_to_threadref (&thread, athread);
10522   printf_filtered ("Remote Threadinfo test\n");
10523   if (!get_and_display_threadinfo (&thread))
10524     printf_filtered ("FAIL cannot get thread info\n");
10525 }
10526
10527 static int
10528 thread_display_step (threadref *ref, void *context)
10529 {
10530   /* output_threadid(" threadstep ",ref); *//* simple test */
10531   return get_and_display_threadinfo (ref);
10532 }
10533
10534 static void
10535 threadlist_update_test_cmd (char *cmd, int tty)
10536 {
10537   printf_filtered ("Remote Threadlist update test\n");
10538   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10539 }
10540
10541 static void
10542 init_remote_threadtests (void)
10543 {
10544   add_com ("tlist", class_obscure, threadlist_test_cmd,
10545            _("Fetch and print the remote list of "
10546              "thread identifiers, one pkt only"));
10547   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10548            _("Fetch and display info about one thread"));
10549   add_com ("tset", class_obscure, threadset_test_cmd,
10550            _("Test setting to a different thread"));
10551   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10552            _("Iterate through updating all remote thread info"));
10553   add_com ("talive", class_obscure, threadalive_test,
10554            _(" Remote thread alive test "));
10555 }
10556
10557 #endif /* 0 */
10558
10559 /* Convert a thread ID to a string.  Returns the string in a static
10560    buffer.  */
10561
10562 static char *
10563 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10564 {
10565   static char buf[64];
10566   struct remote_state *rs = get_remote_state ();
10567
10568   if (ptid_equal (ptid, null_ptid))
10569     return normal_pid_to_str (ptid);
10570   else if (ptid_is_pid (ptid))
10571     {
10572       /* Printing an inferior target id.  */
10573
10574       /* When multi-process extensions are off, there's no way in the
10575          remote protocol to know the remote process id, if there's any
10576          at all.  There's one exception --- when we're connected with
10577          target extended-remote, and we manually attached to a process
10578          with "attach PID".  We don't record anywhere a flag that
10579          allows us to distinguish that case from the case of
10580          connecting with extended-remote and the stub already being
10581          attached to a process, and reporting yes to qAttached, hence
10582          no smart special casing here.  */
10583       if (!remote_multi_process_p (rs))
10584         {
10585           xsnprintf (buf, sizeof buf, "Remote target");
10586           return buf;
10587         }
10588
10589       return normal_pid_to_str (ptid);
10590     }
10591   else
10592     {
10593       if (ptid_equal (magic_null_ptid, ptid))
10594         xsnprintf (buf, sizeof buf, "Thread <main>");
10595       else if (remote_multi_process_p (rs))
10596         if (ptid_get_lwp (ptid) == 0)
10597           return normal_pid_to_str (ptid);
10598         else
10599           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10600                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
10601       else
10602         xsnprintf (buf, sizeof buf, "Thread %ld",
10603                    ptid_get_lwp (ptid));
10604       return buf;
10605     }
10606 }
10607
10608 /* Get the address of the thread local variable in OBJFILE which is
10609    stored at OFFSET within the thread local storage for thread PTID.  */
10610
10611 static CORE_ADDR
10612 remote_get_thread_local_address (struct target_ops *ops,
10613                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10614 {
10615   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10616     {
10617       struct remote_state *rs = get_remote_state ();
10618       char *p = rs->buf;
10619       char *endp = rs->buf + get_remote_packet_size ();
10620       enum packet_result result;
10621
10622       strcpy (p, "qGetTLSAddr:");
10623       p += strlen (p);
10624       p = write_ptid (p, endp, ptid);
10625       *p++ = ',';
10626       p += hexnumstr (p, offset);
10627       *p++ = ',';
10628       p += hexnumstr (p, lm);
10629       *p++ = '\0';
10630
10631       putpkt (rs->buf);
10632       getpkt (&rs->buf, &rs->buf_size, 0);
10633       result = packet_ok (rs->buf,
10634                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
10635       if (result == PACKET_OK)
10636         {
10637           ULONGEST result;
10638
10639           unpack_varlen_hex (rs->buf, &result);
10640           return result;
10641         }
10642       else if (result == PACKET_UNKNOWN)
10643         throw_error (TLS_GENERIC_ERROR,
10644                      _("Remote target doesn't support qGetTLSAddr packet"));
10645       else
10646         throw_error (TLS_GENERIC_ERROR,
10647                      _("Remote target failed to process qGetTLSAddr request"));
10648     }
10649   else
10650     throw_error (TLS_GENERIC_ERROR,
10651                  _("TLS not supported or disabled on this target"));
10652   /* Not reached.  */
10653   return 0;
10654 }
10655
10656 /* Provide thread local base, i.e. Thread Information Block address.
10657    Returns 1 if ptid is found and thread_local_base is non zero.  */
10658
10659 static int
10660 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10661 {
10662   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10663     {
10664       struct remote_state *rs = get_remote_state ();
10665       char *p = rs->buf;
10666       char *endp = rs->buf + get_remote_packet_size ();
10667       enum packet_result result;
10668
10669       strcpy (p, "qGetTIBAddr:");
10670       p += strlen (p);
10671       p = write_ptid (p, endp, ptid);
10672       *p++ = '\0';
10673
10674       putpkt (rs->buf);
10675       getpkt (&rs->buf, &rs->buf_size, 0);
10676       result = packet_ok (rs->buf,
10677                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
10678       if (result == PACKET_OK)
10679         {
10680           ULONGEST result;
10681
10682           unpack_varlen_hex (rs->buf, &result);
10683           if (addr)
10684             *addr = (CORE_ADDR) result;
10685           return 1;
10686         }
10687       else if (result == PACKET_UNKNOWN)
10688         error (_("Remote target doesn't support qGetTIBAddr packet"));
10689       else
10690         error (_("Remote target failed to process qGetTIBAddr request"));
10691     }
10692   else
10693     error (_("qGetTIBAddr not supported or disabled on this target"));
10694   /* Not reached.  */
10695   return 0;
10696 }
10697
10698 /* Support for inferring a target description based on the current
10699    architecture and the size of a 'g' packet.  While the 'g' packet
10700    can have any size (since optional registers can be left off the
10701    end), some sizes are easily recognizable given knowledge of the
10702    approximate architecture.  */
10703
10704 struct remote_g_packet_guess
10705 {
10706   int bytes;
10707   const struct target_desc *tdesc;
10708 };
10709 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10710 DEF_VEC_O(remote_g_packet_guess_s);
10711
10712 struct remote_g_packet_data
10713 {
10714   VEC(remote_g_packet_guess_s) *guesses;
10715 };
10716
10717 static struct gdbarch_data *remote_g_packet_data_handle;
10718
10719 static void *
10720 remote_g_packet_data_init (struct obstack *obstack)
10721 {
10722   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10723 }
10724
10725 void
10726 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10727                                 const struct target_desc *tdesc)
10728 {
10729   struct remote_g_packet_data *data
10730     = ((struct remote_g_packet_data *)
10731        gdbarch_data (gdbarch, remote_g_packet_data_handle));
10732   struct remote_g_packet_guess new_guess, *guess;
10733   int ix;
10734
10735   gdb_assert (tdesc != NULL);
10736
10737   for (ix = 0;
10738        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10739        ix++)
10740     if (guess->bytes == bytes)
10741       internal_error (__FILE__, __LINE__,
10742                       _("Duplicate g packet description added for size %d"),
10743                       bytes);
10744
10745   new_guess.bytes = bytes;
10746   new_guess.tdesc = tdesc;
10747   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10748 }
10749
10750 /* Return 1 if remote_read_description would do anything on this target
10751    and architecture, 0 otherwise.  */
10752
10753 static int
10754 remote_read_description_p (struct target_ops *target)
10755 {
10756   struct remote_g_packet_data *data
10757     = ((struct remote_g_packet_data *)
10758        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10759
10760   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10761     return 1;
10762
10763   return 0;
10764 }
10765
10766 static const struct target_desc *
10767 remote_read_description (struct target_ops *target)
10768 {
10769   struct remote_g_packet_data *data
10770     = ((struct remote_g_packet_data *)
10771        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10772
10773   /* Do not try this during initial connection, when we do not know
10774      whether there is a running but stopped thread.  */
10775   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10776     return target->beneath->to_read_description (target->beneath);
10777
10778   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10779     {
10780       struct remote_g_packet_guess *guess;
10781       int ix;
10782       int bytes = send_g_packet ();
10783
10784       for (ix = 0;
10785            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10786            ix++)
10787         if (guess->bytes == bytes)
10788           return guess->tdesc;
10789
10790       /* We discard the g packet.  A minor optimization would be to
10791          hold on to it, and fill the register cache once we have selected
10792          an architecture, but it's too tricky to do safely.  */
10793     }
10794
10795   return target->beneath->to_read_description (target->beneath);
10796 }
10797
10798 /* Remote file transfer support.  This is host-initiated I/O, not
10799    target-initiated; for target-initiated, see remote-fileio.c.  */
10800
10801 /* If *LEFT is at least the length of STRING, copy STRING to
10802    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10803    decrease *LEFT.  Otherwise raise an error.  */
10804
10805 static void
10806 remote_buffer_add_string (char **buffer, int *left, char *string)
10807 {
10808   int len = strlen (string);
10809
10810   if (len > *left)
10811     error (_("Packet too long for target."));
10812
10813   memcpy (*buffer, string, len);
10814   *buffer += len;
10815   *left -= len;
10816
10817   /* NUL-terminate the buffer as a convenience, if there is
10818      room.  */
10819   if (*left)
10820     **buffer = '\0';
10821 }
10822
10823 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10824    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10825    decrease *LEFT.  Otherwise raise an error.  */
10826
10827 static void
10828 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10829                          int len)
10830 {
10831   if (2 * len > *left)
10832     error (_("Packet too long for target."));
10833
10834   bin2hex (bytes, *buffer, len);
10835   *buffer += 2 * len;
10836   *left -= 2 * len;
10837
10838   /* NUL-terminate the buffer as a convenience, if there is
10839      room.  */
10840   if (*left)
10841     **buffer = '\0';
10842 }
10843
10844 /* If *LEFT is large enough, convert VALUE to hex and add it to
10845    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10846    decrease *LEFT.  Otherwise raise an error.  */
10847
10848 static void
10849 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10850 {
10851   int len = hexnumlen (value);
10852
10853   if (len > *left)
10854     error (_("Packet too long for target."));
10855
10856   hexnumstr (*buffer, value);
10857   *buffer += len;
10858   *left -= len;
10859
10860   /* NUL-terminate the buffer as a convenience, if there is
10861      room.  */
10862   if (*left)
10863     **buffer = '\0';
10864 }
10865
10866 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
10867    value, *REMOTE_ERRNO to the remote error number or zero if none
10868    was included, and *ATTACHMENT to point to the start of the annex
10869    if any.  The length of the packet isn't needed here; there may
10870    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10871
10872    Return 0 if the packet could be parsed, -1 if it could not.  If
10873    -1 is returned, the other variables may not be initialized.  */
10874
10875 static int
10876 remote_hostio_parse_result (char *buffer, int *retcode,
10877                             int *remote_errno, char **attachment)
10878 {
10879   char *p, *p2;
10880
10881   *remote_errno = 0;
10882   *attachment = NULL;
10883
10884   if (buffer[0] != 'F')
10885     return -1;
10886
10887   errno = 0;
10888   *retcode = strtol (&buffer[1], &p, 16);
10889   if (errno != 0 || p == &buffer[1])
10890     return -1;
10891
10892   /* Check for ",errno".  */
10893   if (*p == ',')
10894     {
10895       errno = 0;
10896       *remote_errno = strtol (p + 1, &p2, 16);
10897       if (errno != 0 || p + 1 == p2)
10898         return -1;
10899       p = p2;
10900     }
10901
10902   /* Check for ";attachment".  If there is no attachment, the
10903      packet should end here.  */
10904   if (*p == ';')
10905     {
10906       *attachment = p + 1;
10907       return 0;
10908     }
10909   else if (*p == '\0')
10910     return 0;
10911   else
10912     return -1;
10913 }
10914
10915 /* Send a prepared I/O packet to the target and read its response.
10916    The prepared packet is in the global RS->BUF before this function
10917    is called, and the answer is there when we return.
10918
10919    COMMAND_BYTES is the length of the request to send, which may include
10920    binary data.  WHICH_PACKET is the packet configuration to check
10921    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
10922    is set to the error number and -1 is returned.  Otherwise the value
10923    returned by the function is returned.
10924
10925    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10926    attachment is expected; an error will be reported if there's a
10927    mismatch.  If one is found, *ATTACHMENT will be set to point into
10928    the packet buffer and *ATTACHMENT_LEN will be set to the
10929    attachment's length.  */
10930
10931 static int
10932 remote_hostio_send_command (int command_bytes, int which_packet,
10933                             int *remote_errno, char **attachment,
10934                             int *attachment_len)
10935 {
10936   struct remote_state *rs = get_remote_state ();
10937   int ret, bytes_read;
10938   char *attachment_tmp;
10939
10940   if (!rs->remote_desc
10941       || packet_support (which_packet) == PACKET_DISABLE)
10942     {
10943       *remote_errno = FILEIO_ENOSYS;
10944       return -1;
10945     }
10946
10947   putpkt_binary (rs->buf, command_bytes);
10948   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10949
10950   /* If it timed out, something is wrong.  Don't try to parse the
10951      buffer.  */
10952   if (bytes_read < 0)
10953     {
10954       *remote_errno = FILEIO_EINVAL;
10955       return -1;
10956     }
10957
10958   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10959     {
10960     case PACKET_ERROR:
10961       *remote_errno = FILEIO_EINVAL;
10962       return -1;
10963     case PACKET_UNKNOWN:
10964       *remote_errno = FILEIO_ENOSYS;
10965       return -1;
10966     case PACKET_OK:
10967       break;
10968     }
10969
10970   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10971                                   &attachment_tmp))
10972     {
10973       *remote_errno = FILEIO_EINVAL;
10974       return -1;
10975     }
10976
10977   /* Make sure we saw an attachment if and only if we expected one.  */
10978   if ((attachment_tmp == NULL && attachment != NULL)
10979       || (attachment_tmp != NULL && attachment == NULL))
10980     {
10981       *remote_errno = FILEIO_EINVAL;
10982       return -1;
10983     }
10984
10985   /* If an attachment was found, it must point into the packet buffer;
10986      work out how many bytes there were.  */
10987   if (attachment_tmp != NULL)
10988     {
10989       *attachment = attachment_tmp;
10990       *attachment_len = bytes_read - (*attachment - rs->buf);
10991     }
10992
10993   return ret;
10994 }
10995
10996 /* Invalidate the readahead cache.  */
10997
10998 static void
10999 readahead_cache_invalidate (void)
11000 {
11001   struct remote_state *rs = get_remote_state ();
11002
11003   rs->readahead_cache.fd = -1;
11004 }
11005
11006 /* Invalidate the readahead cache if it is holding data for FD.  */
11007
11008 static void
11009 readahead_cache_invalidate_fd (int fd)
11010 {
11011   struct remote_state *rs = get_remote_state ();
11012
11013   if (rs->readahead_cache.fd == fd)
11014     rs->readahead_cache.fd = -1;
11015 }
11016
11017 /* Set the filesystem remote_hostio functions that take FILENAME
11018    arguments will use.  Return 0 on success, or -1 if an error
11019    occurs (and set *REMOTE_ERRNO).  */
11020
11021 static int
11022 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11023 {
11024   struct remote_state *rs = get_remote_state ();
11025   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11026   char *p = rs->buf;
11027   int left = get_remote_packet_size () - 1;
11028   char arg[9];
11029   int ret;
11030
11031   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11032     return 0;
11033
11034   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11035     return 0;
11036
11037   remote_buffer_add_string (&p, &left, "vFile:setfs:");
11038
11039   xsnprintf (arg, sizeof (arg), "%x", required_pid);
11040   remote_buffer_add_string (&p, &left, arg);
11041
11042   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11043                                     remote_errno, NULL, NULL);
11044
11045   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11046     return 0;
11047
11048   if (ret == 0)
11049     rs->fs_pid = required_pid;
11050
11051   return ret;
11052 }
11053
11054 /* Implementation of to_fileio_open.  */
11055
11056 static int
11057 remote_hostio_open (struct target_ops *self,
11058                     struct inferior *inf, const char *filename,
11059                     int flags, int mode, int warn_if_slow,
11060                     int *remote_errno)
11061 {
11062   struct remote_state *rs = get_remote_state ();
11063   char *p = rs->buf;
11064   int left = get_remote_packet_size () - 1;
11065
11066   if (warn_if_slow)
11067     {
11068       static int warning_issued = 0;
11069
11070       printf_unfiltered (_("Reading %s from remote target...\n"),
11071                          filename);
11072
11073       if (!warning_issued)
11074         {
11075           warning (_("File transfers from remote targets can be slow."
11076                      " Use \"set sysroot\" to access files locally"
11077                      " instead."));
11078           warning_issued = 1;
11079         }
11080     }
11081
11082   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11083     return -1;
11084
11085   remote_buffer_add_string (&p, &left, "vFile:open:");
11086
11087   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11088                            strlen (filename));
11089   remote_buffer_add_string (&p, &left, ",");
11090
11091   remote_buffer_add_int (&p, &left, flags);
11092   remote_buffer_add_string (&p, &left, ",");
11093
11094   remote_buffer_add_int (&p, &left, mode);
11095
11096   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11097                                      remote_errno, NULL, NULL);
11098 }
11099
11100 /* Implementation of to_fileio_pwrite.  */
11101
11102 static int
11103 remote_hostio_pwrite (struct target_ops *self,
11104                       int fd, const gdb_byte *write_buf, int len,
11105                       ULONGEST offset, int *remote_errno)
11106 {
11107   struct remote_state *rs = get_remote_state ();
11108   char *p = rs->buf;
11109   int left = get_remote_packet_size ();
11110   int out_len;
11111
11112   readahead_cache_invalidate_fd (fd);
11113
11114   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11115
11116   remote_buffer_add_int (&p, &left, fd);
11117   remote_buffer_add_string (&p, &left, ",");
11118
11119   remote_buffer_add_int (&p, &left, offset);
11120   remote_buffer_add_string (&p, &left, ",");
11121
11122   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11123                              get_remote_packet_size () - (p - rs->buf));
11124
11125   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11126                                      remote_errno, NULL, NULL);
11127 }
11128
11129 /* Helper for the implementation of to_fileio_pread.  Read the file
11130    from the remote side with vFile:pread.  */
11131
11132 static int
11133 remote_hostio_pread_vFile (struct target_ops *self,
11134                            int fd, gdb_byte *read_buf, int len,
11135                            ULONGEST offset, int *remote_errno)
11136 {
11137   struct remote_state *rs = get_remote_state ();
11138   char *p = rs->buf;
11139   char *attachment;
11140   int left = get_remote_packet_size ();
11141   int ret, attachment_len;
11142   int read_len;
11143
11144   remote_buffer_add_string (&p, &left, "vFile:pread:");
11145
11146   remote_buffer_add_int (&p, &left, fd);
11147   remote_buffer_add_string (&p, &left, ",");
11148
11149   remote_buffer_add_int (&p, &left, len);
11150   remote_buffer_add_string (&p, &left, ",");
11151
11152   remote_buffer_add_int (&p, &left, offset);
11153
11154   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11155                                     remote_errno, &attachment,
11156                                     &attachment_len);
11157
11158   if (ret < 0)
11159     return ret;
11160
11161   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11162                                     read_buf, len);
11163   if (read_len != ret)
11164     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11165
11166   return ret;
11167 }
11168
11169 /* Serve pread from the readahead cache.  Returns number of bytes
11170    read, or 0 if the request can't be served from the cache.  */
11171
11172 static int
11173 remote_hostio_pread_from_cache (struct remote_state *rs,
11174                                 int fd, gdb_byte *read_buf, size_t len,
11175                                 ULONGEST offset)
11176 {
11177   struct readahead_cache *cache = &rs->readahead_cache;
11178
11179   if (cache->fd == fd
11180       && cache->offset <= offset
11181       && offset < cache->offset + cache->bufsize)
11182     {
11183       ULONGEST max = cache->offset + cache->bufsize;
11184
11185       if (offset + len > max)
11186         len = max - offset;
11187
11188       memcpy (read_buf, cache->buf + offset - cache->offset, len);
11189       return len;
11190     }
11191
11192   return 0;
11193 }
11194
11195 /* Implementation of to_fileio_pread.  */
11196
11197 static int
11198 remote_hostio_pread (struct target_ops *self,
11199                      int fd, gdb_byte *read_buf, int len,
11200                      ULONGEST offset, int *remote_errno)
11201 {
11202   int ret;
11203   struct remote_state *rs = get_remote_state ();
11204   struct readahead_cache *cache = &rs->readahead_cache;
11205
11206   ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11207   if (ret > 0)
11208     {
11209       cache->hit_count++;
11210
11211       if (remote_debug)
11212         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11213                             pulongest (cache->hit_count));
11214       return ret;
11215     }
11216
11217   cache->miss_count++;
11218   if (remote_debug)
11219     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11220                         pulongest (cache->miss_count));
11221
11222   cache->fd = fd;
11223   cache->offset = offset;
11224   cache->bufsize = get_remote_packet_size ();
11225   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11226
11227   ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11228                                    cache->offset, remote_errno);
11229   if (ret <= 0)
11230     {
11231       readahead_cache_invalidate_fd (fd);
11232       return ret;
11233     }
11234
11235   cache->bufsize = ret;
11236   return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11237 }
11238
11239 /* Implementation of to_fileio_close.  */
11240
11241 static int
11242 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11243 {
11244   struct remote_state *rs = get_remote_state ();
11245   char *p = rs->buf;
11246   int left = get_remote_packet_size () - 1;
11247
11248   readahead_cache_invalidate_fd (fd);
11249
11250   remote_buffer_add_string (&p, &left, "vFile:close:");
11251
11252   remote_buffer_add_int (&p, &left, fd);
11253
11254   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11255                                      remote_errno, NULL, NULL);
11256 }
11257
11258 /* Implementation of to_fileio_unlink.  */
11259
11260 static int
11261 remote_hostio_unlink (struct target_ops *self,
11262                       struct inferior *inf, const char *filename,
11263                       int *remote_errno)
11264 {
11265   struct remote_state *rs = get_remote_state ();
11266   char *p = rs->buf;
11267   int left = get_remote_packet_size () - 1;
11268
11269   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11270     return -1;
11271
11272   remote_buffer_add_string (&p, &left, "vFile:unlink:");
11273
11274   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11275                            strlen (filename));
11276
11277   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11278                                      remote_errno, NULL, NULL);
11279 }
11280
11281 /* Implementation of to_fileio_readlink.  */
11282
11283 static char *
11284 remote_hostio_readlink (struct target_ops *self,
11285                         struct inferior *inf, const char *filename,
11286                         int *remote_errno)
11287 {
11288   struct remote_state *rs = get_remote_state ();
11289   char *p = rs->buf;
11290   char *attachment;
11291   int left = get_remote_packet_size ();
11292   int len, attachment_len;
11293   int read_len;
11294   char *ret;
11295
11296   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11297     return NULL;
11298
11299   remote_buffer_add_string (&p, &left, "vFile:readlink:");
11300
11301   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11302                            strlen (filename));
11303
11304   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11305                                     remote_errno, &attachment,
11306                                     &attachment_len);
11307
11308   if (len < 0)
11309     return NULL;
11310
11311   ret = (char *) xmalloc (len + 1);
11312
11313   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11314                                     (gdb_byte *) ret, len);
11315   if (read_len != len)
11316     error (_("Readlink returned %d, but %d bytes."), len, read_len);
11317
11318   ret[len] = '\0';
11319   return ret;
11320 }
11321
11322 /* Implementation of to_fileio_fstat.  */
11323
11324 static int
11325 remote_hostio_fstat (struct target_ops *self,
11326                      int fd, struct stat *st,
11327                      int *remote_errno)
11328 {
11329   struct remote_state *rs = get_remote_state ();
11330   char *p = rs->buf;
11331   int left = get_remote_packet_size ();
11332   int attachment_len, ret;
11333   char *attachment;
11334   struct fio_stat fst;
11335   int read_len;
11336
11337   remote_buffer_add_string (&p, &left, "vFile:fstat:");
11338
11339   remote_buffer_add_int (&p, &left, fd);
11340
11341   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11342                                     remote_errno, &attachment,
11343                                     &attachment_len);
11344   if (ret < 0)
11345     {
11346       if (*remote_errno != FILEIO_ENOSYS)
11347         return ret;
11348
11349       /* Strictly we should return -1, ENOSYS here, but when
11350          "set sysroot remote:" was implemented in August 2008
11351          BFD's need for a stat function was sidestepped with
11352          this hack.  This was not remedied until March 2015
11353          so we retain the previous behavior to avoid breaking
11354          compatibility.
11355
11356          Note that the memset is a March 2015 addition; older
11357          GDBs set st_size *and nothing else* so the structure
11358          would have garbage in all other fields.  This might
11359          break something but retaining the previous behavior
11360          here would be just too wrong.  */
11361
11362       memset (st, 0, sizeof (struct stat));
11363       st->st_size = INT_MAX;
11364       return 0;
11365     }
11366
11367   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11368                                     (gdb_byte *) &fst, sizeof (fst));
11369
11370   if (read_len != ret)
11371     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11372
11373   if (read_len != sizeof (fst))
11374     error (_("vFile:fstat returned %d bytes, but expecting %d."),
11375            read_len, (int) sizeof (fst));
11376
11377   remote_fileio_to_host_stat (&fst, st);
11378
11379   return 0;
11380 }
11381
11382 /* Implementation of to_filesystem_is_local.  */
11383
11384 static int
11385 remote_filesystem_is_local (struct target_ops *self)
11386 {
11387   /* Valgrind GDB presents itself as a remote target but works
11388      on the local filesystem: it does not implement remote get
11389      and users are not expected to set a sysroot.  To handle
11390      this case we treat the remote filesystem as local if the
11391      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11392      does not support vFile:open.  */
11393   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11394     {
11395       enum packet_support ps = packet_support (PACKET_vFile_open);
11396
11397       if (ps == PACKET_SUPPORT_UNKNOWN)
11398         {
11399           int fd, remote_errno;
11400
11401           /* Try opening a file to probe support.  The supplied
11402              filename is irrelevant, we only care about whether
11403              the stub recognizes the packet or not.  */
11404           fd = remote_hostio_open (self, NULL, "just probing",
11405                                    FILEIO_O_RDONLY, 0700, 0,
11406                                    &remote_errno);
11407
11408           if (fd >= 0)
11409             remote_hostio_close (self, fd, &remote_errno);
11410
11411           ps = packet_support (PACKET_vFile_open);
11412         }
11413
11414       if (ps == PACKET_DISABLE)
11415         {
11416           static int warning_issued = 0;
11417
11418           if (!warning_issued)
11419             {
11420               warning (_("remote target does not support file"
11421                          " transfer, attempting to access files"
11422                          " from local filesystem."));
11423               warning_issued = 1;
11424             }
11425
11426           return 1;
11427         }
11428     }
11429
11430   return 0;
11431 }
11432
11433 static int
11434 remote_fileio_errno_to_host (int errnum)
11435 {
11436   switch (errnum)
11437     {
11438       case FILEIO_EPERM:
11439         return EPERM;
11440       case FILEIO_ENOENT:
11441         return ENOENT;
11442       case FILEIO_EINTR:
11443         return EINTR;
11444       case FILEIO_EIO:
11445         return EIO;
11446       case FILEIO_EBADF:
11447         return EBADF;
11448       case FILEIO_EACCES:
11449         return EACCES;
11450       case FILEIO_EFAULT:
11451         return EFAULT;
11452       case FILEIO_EBUSY:
11453         return EBUSY;
11454       case FILEIO_EEXIST:
11455         return EEXIST;
11456       case FILEIO_ENODEV:
11457         return ENODEV;
11458       case FILEIO_ENOTDIR:
11459         return ENOTDIR;
11460       case FILEIO_EISDIR:
11461         return EISDIR;
11462       case FILEIO_EINVAL:
11463         return EINVAL;
11464       case FILEIO_ENFILE:
11465         return ENFILE;
11466       case FILEIO_EMFILE:
11467         return EMFILE;
11468       case FILEIO_EFBIG:
11469         return EFBIG;
11470       case FILEIO_ENOSPC:
11471         return ENOSPC;
11472       case FILEIO_ESPIPE:
11473         return ESPIPE;
11474       case FILEIO_EROFS:
11475         return EROFS;
11476       case FILEIO_ENOSYS:
11477         return ENOSYS;
11478       case FILEIO_ENAMETOOLONG:
11479         return ENAMETOOLONG;
11480     }
11481   return -1;
11482 }
11483
11484 static char *
11485 remote_hostio_error (int errnum)
11486 {
11487   int host_error = remote_fileio_errno_to_host (errnum);
11488
11489   if (host_error == -1)
11490     error (_("Unknown remote I/O error %d"), errnum);
11491   else
11492     error (_("Remote I/O error: %s"), safe_strerror (host_error));
11493 }
11494
11495 static void
11496 remote_hostio_close_cleanup (void *opaque)
11497 {
11498   int fd = *(int *) opaque;
11499   int remote_errno;
11500
11501   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11502 }
11503
11504 void
11505 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11506 {
11507   struct cleanup *back_to, *close_cleanup;
11508   int retcode, fd, remote_errno, bytes, io_size;
11509   FILE *file;
11510   gdb_byte *buffer;
11511   int bytes_in_buffer;
11512   int saw_eof;
11513   ULONGEST offset;
11514   struct remote_state *rs = get_remote_state ();
11515
11516   if (!rs->remote_desc)
11517     error (_("command can only be used with remote target"));
11518
11519   file = gdb_fopen_cloexec (local_file, "rb");
11520   if (file == NULL)
11521     perror_with_name (local_file);
11522   back_to = make_cleanup_fclose (file);
11523
11524   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11525                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11526                                          | FILEIO_O_TRUNC),
11527                            0700, 0, &remote_errno);
11528   if (fd == -1)
11529     remote_hostio_error (remote_errno);
11530
11531   /* Send up to this many bytes at once.  They won't all fit in the
11532      remote packet limit, so we'll transfer slightly fewer.  */
11533   io_size = get_remote_packet_size ();
11534   buffer = (gdb_byte *) xmalloc (io_size);
11535   make_cleanup (xfree, buffer);
11536
11537   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11538
11539   bytes_in_buffer = 0;
11540   saw_eof = 0;
11541   offset = 0;
11542   while (bytes_in_buffer || !saw_eof)
11543     {
11544       if (!saw_eof)
11545         {
11546           bytes = fread (buffer + bytes_in_buffer, 1,
11547                          io_size - bytes_in_buffer,
11548                          file);
11549           if (bytes == 0)
11550             {
11551               if (ferror (file))
11552                 error (_("Error reading %s."), local_file);
11553               else
11554                 {
11555                   /* EOF.  Unless there is something still in the
11556                      buffer from the last iteration, we are done.  */
11557                   saw_eof = 1;
11558                   if (bytes_in_buffer == 0)
11559                     break;
11560                 }
11561             }
11562         }
11563       else
11564         bytes = 0;
11565
11566       bytes += bytes_in_buffer;
11567       bytes_in_buffer = 0;
11568
11569       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11570                                       fd, buffer, bytes,
11571                                       offset, &remote_errno);
11572
11573       if (retcode < 0)
11574         remote_hostio_error (remote_errno);
11575       else if (retcode == 0)
11576         error (_("Remote write of %d bytes returned 0!"), bytes);
11577       else if (retcode < bytes)
11578         {
11579           /* Short write.  Save the rest of the read data for the next
11580              write.  */
11581           bytes_in_buffer = bytes - retcode;
11582           memmove (buffer, buffer + retcode, bytes_in_buffer);
11583         }
11584
11585       offset += retcode;
11586     }
11587
11588   discard_cleanups (close_cleanup);
11589   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11590     remote_hostio_error (remote_errno);
11591
11592   if (from_tty)
11593     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11594   do_cleanups (back_to);
11595 }
11596
11597 void
11598 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11599 {
11600   struct cleanup *back_to, *close_cleanup;
11601   int fd, remote_errno, bytes, io_size;
11602   FILE *file;
11603   gdb_byte *buffer;
11604   ULONGEST offset;
11605   struct remote_state *rs = get_remote_state ();
11606
11607   if (!rs->remote_desc)
11608     error (_("command can only be used with remote target"));
11609
11610   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11611                            remote_file, FILEIO_O_RDONLY, 0, 0,
11612                            &remote_errno);
11613   if (fd == -1)
11614     remote_hostio_error (remote_errno);
11615
11616   file = gdb_fopen_cloexec (local_file, "wb");
11617   if (file == NULL)
11618     perror_with_name (local_file);
11619   back_to = make_cleanup_fclose (file);
11620
11621   /* Send up to this many bytes at once.  They won't all fit in the
11622      remote packet limit, so we'll transfer slightly fewer.  */
11623   io_size = get_remote_packet_size ();
11624   buffer = (gdb_byte *) xmalloc (io_size);
11625   make_cleanup (xfree, buffer);
11626
11627   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11628
11629   offset = 0;
11630   while (1)
11631     {
11632       bytes = remote_hostio_pread (find_target_at (process_stratum),
11633                                    fd, buffer, io_size, offset, &remote_errno);
11634       if (bytes == 0)
11635         /* Success, but no bytes, means end-of-file.  */
11636         break;
11637       if (bytes == -1)
11638         remote_hostio_error (remote_errno);
11639
11640       offset += bytes;
11641
11642       bytes = fwrite (buffer, 1, bytes, file);
11643       if (bytes == 0)
11644         perror_with_name (local_file);
11645     }
11646
11647   discard_cleanups (close_cleanup);
11648   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11649     remote_hostio_error (remote_errno);
11650
11651   if (from_tty)
11652     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11653   do_cleanups (back_to);
11654 }
11655
11656 void
11657 remote_file_delete (const char *remote_file, int from_tty)
11658 {
11659   int retcode, remote_errno;
11660   struct remote_state *rs = get_remote_state ();
11661
11662   if (!rs->remote_desc)
11663     error (_("command can only be used with remote target"));
11664
11665   retcode = remote_hostio_unlink (find_target_at (process_stratum),
11666                                   NULL, remote_file, &remote_errno);
11667   if (retcode == -1)
11668     remote_hostio_error (remote_errno);
11669
11670   if (from_tty)
11671     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11672 }
11673
11674 static void
11675 remote_put_command (char *args, int from_tty)
11676 {
11677   struct cleanup *back_to;
11678   char **argv;
11679
11680   if (args == NULL)
11681     error_no_arg (_("file to put"));
11682
11683   argv = gdb_buildargv (args);
11684   back_to = make_cleanup_freeargv (argv);
11685   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11686     error (_("Invalid parameters to remote put"));
11687
11688   remote_file_put (argv[0], argv[1], from_tty);
11689
11690   do_cleanups (back_to);
11691 }
11692
11693 static void
11694 remote_get_command (char *args, int from_tty)
11695 {
11696   struct cleanup *back_to;
11697   char **argv;
11698
11699   if (args == NULL)
11700     error_no_arg (_("file to get"));
11701
11702   argv = gdb_buildargv (args);
11703   back_to = make_cleanup_freeargv (argv);
11704   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11705     error (_("Invalid parameters to remote get"));
11706
11707   remote_file_get (argv[0], argv[1], from_tty);
11708
11709   do_cleanups (back_to);
11710 }
11711
11712 static void
11713 remote_delete_command (char *args, int from_tty)
11714 {
11715   struct cleanup *back_to;
11716   char **argv;
11717
11718   if (args == NULL)
11719     error_no_arg (_("file to delete"));
11720
11721   argv = gdb_buildargv (args);
11722   back_to = make_cleanup_freeargv (argv);
11723   if (argv[0] == NULL || argv[1] != NULL)
11724     error (_("Invalid parameters to remote delete"));
11725
11726   remote_file_delete (argv[0], from_tty);
11727
11728   do_cleanups (back_to);
11729 }
11730
11731 static void
11732 remote_command (char *args, int from_tty)
11733 {
11734   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11735 }
11736
11737 static int
11738 remote_can_execute_reverse (struct target_ops *self)
11739 {
11740   if (packet_support (PACKET_bs) == PACKET_ENABLE
11741       || packet_support (PACKET_bc) == PACKET_ENABLE)
11742     return 1;
11743   else
11744     return 0;
11745 }
11746
11747 static int
11748 remote_supports_non_stop (struct target_ops *self)
11749 {
11750   return 1;
11751 }
11752
11753 static int
11754 remote_supports_disable_randomization (struct target_ops *self)
11755 {
11756   /* Only supported in extended mode.  */
11757   return 0;
11758 }
11759
11760 static int
11761 remote_supports_multi_process (struct target_ops *self)
11762 {
11763   struct remote_state *rs = get_remote_state ();
11764
11765   return remote_multi_process_p (rs);
11766 }
11767
11768 static int
11769 remote_supports_cond_tracepoints (void)
11770 {
11771   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11772 }
11773
11774 static int
11775 remote_supports_cond_breakpoints (struct target_ops *self)
11776 {
11777   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11778 }
11779
11780 static int
11781 remote_supports_fast_tracepoints (void)
11782 {
11783   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11784 }
11785
11786 static int
11787 remote_supports_static_tracepoints (void)
11788 {
11789   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11790 }
11791
11792 static int
11793 remote_supports_install_in_trace (void)
11794 {
11795   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11796 }
11797
11798 static int
11799 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11800 {
11801   return (packet_support (PACKET_EnableDisableTracepoints_feature)
11802           == PACKET_ENABLE);
11803 }
11804
11805 static int
11806 remote_supports_string_tracing (struct target_ops *self)
11807 {
11808   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11809 }
11810
11811 static int
11812 remote_can_run_breakpoint_commands (struct target_ops *self)
11813 {
11814   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11815 }
11816
11817 static void
11818 remote_trace_init (struct target_ops *self)
11819 {
11820   putpkt ("QTinit");
11821   remote_get_noisy_reply (&target_buf, &target_buf_size);
11822   if (strcmp (target_buf, "OK") != 0)
11823     error (_("Target does not support this command."));
11824 }
11825
11826 static void free_actions_list (char **actions_list);
11827 static void free_actions_list_cleanup_wrapper (void *);
11828 static void
11829 free_actions_list_cleanup_wrapper (void *al)
11830 {
11831   free_actions_list ((char **) al);
11832 }
11833
11834 static void
11835 free_actions_list (char **actions_list)
11836 {
11837   int ndx;
11838
11839   if (actions_list == 0)
11840     return;
11841
11842   for (ndx = 0; actions_list[ndx]; ndx++)
11843     xfree (actions_list[ndx]);
11844
11845   xfree (actions_list);
11846 }
11847
11848 /* Recursive routine to walk through command list including loops, and
11849    download packets for each command.  */
11850
11851 static void
11852 remote_download_command_source (int num, ULONGEST addr,
11853                                 struct command_line *cmds)
11854 {
11855   struct remote_state *rs = get_remote_state ();
11856   struct command_line *cmd;
11857
11858   for (cmd = cmds; cmd; cmd = cmd->next)
11859     {
11860       QUIT;     /* Allow user to bail out with ^C.  */
11861       strcpy (rs->buf, "QTDPsrc:");
11862       encode_source_string (num, addr, "cmd", cmd->line,
11863                             rs->buf + strlen (rs->buf),
11864                             rs->buf_size - strlen (rs->buf));
11865       putpkt (rs->buf);
11866       remote_get_noisy_reply (&target_buf, &target_buf_size);
11867       if (strcmp (target_buf, "OK"))
11868         warning (_("Target does not support source download."));
11869
11870       if (cmd->control_type == while_control
11871           || cmd->control_type == while_stepping_control)
11872         {
11873           remote_download_command_source (num, addr, *cmd->body_list);
11874
11875           QUIT; /* Allow user to bail out with ^C.  */
11876           strcpy (rs->buf, "QTDPsrc:");
11877           encode_source_string (num, addr, "cmd", "end",
11878                                 rs->buf + strlen (rs->buf),
11879                                 rs->buf_size - strlen (rs->buf));
11880           putpkt (rs->buf);
11881           remote_get_noisy_reply (&target_buf, &target_buf_size);
11882           if (strcmp (target_buf, "OK"))
11883             warning (_("Target does not support source download."));
11884         }
11885     }
11886 }
11887
11888 static void
11889 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11890 {
11891 #define BUF_SIZE 2048
11892
11893   CORE_ADDR tpaddr;
11894   char addrbuf[40];
11895   char buf[BUF_SIZE];
11896   char **tdp_actions;
11897   char **stepping_actions;
11898   int ndx;
11899   struct cleanup *old_chain = NULL;
11900   struct agent_expr *aexpr;
11901   struct cleanup *aexpr_chain = NULL;
11902   char *pkt;
11903   struct breakpoint *b = loc->owner;
11904   struct tracepoint *t = (struct tracepoint *) b;
11905
11906   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11907   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11908                             tdp_actions);
11909   (void) make_cleanup (free_actions_list_cleanup_wrapper,
11910                        stepping_actions);
11911
11912   tpaddr = loc->address;
11913   sprintf_vma (addrbuf, tpaddr);
11914   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11915              addrbuf, /* address */
11916              (b->enable_state == bp_enabled ? 'E' : 'D'),
11917              t->step_count, t->pass_count);
11918   /* Fast tracepoints are mostly handled by the target, but we can
11919      tell the target how big of an instruction block should be moved
11920      around.  */
11921   if (b->type == bp_fast_tracepoint)
11922     {
11923       /* Only test for support at download time; we may not know
11924          target capabilities at definition time.  */
11925       if (remote_supports_fast_tracepoints ())
11926         {
11927           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11928                                                 NULL))
11929             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11930                        gdb_insn_length (loc->gdbarch, tpaddr));
11931           else
11932             /* If it passed validation at definition but fails now,
11933                something is very wrong.  */
11934             internal_error (__FILE__, __LINE__,
11935                             _("Fast tracepoint not "
11936                               "valid during download"));
11937         }
11938       else
11939         /* Fast tracepoints are functionally identical to regular
11940            tracepoints, so don't take lack of support as a reason to
11941            give up on the trace run.  */
11942         warning (_("Target does not support fast tracepoints, "
11943                    "downloading %d as regular tracepoint"), b->number);
11944     }
11945   else if (b->type == bp_static_tracepoint)
11946     {
11947       /* Only test for support at download time; we may not know
11948          target capabilities at definition time.  */
11949       if (remote_supports_static_tracepoints ())
11950         {
11951           struct static_tracepoint_marker marker;
11952
11953           if (target_static_tracepoint_marker_at (tpaddr, &marker))
11954             strcat (buf, ":S");
11955           else
11956             error (_("Static tracepoint not valid during download"));
11957         }
11958       else
11959         /* Fast tracepoints are functionally identical to regular
11960            tracepoints, so don't take lack of support as a reason
11961            to give up on the trace run.  */
11962         error (_("Target does not support static tracepoints"));
11963     }
11964   /* If the tracepoint has a conditional, make it into an agent
11965      expression and append to the definition.  */
11966   if (loc->cond)
11967     {
11968       /* Only test support at download time, we may not know target
11969          capabilities at definition time.  */
11970       if (remote_supports_cond_tracepoints ())
11971         {
11972           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11973           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11974           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11975                      aexpr->len);
11976           pkt = buf + strlen (buf);
11977           for (ndx = 0; ndx < aexpr->len; ++ndx)
11978             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11979           *pkt = '\0';
11980           do_cleanups (aexpr_chain);
11981         }
11982       else
11983         warning (_("Target does not support conditional tracepoints, "
11984                    "ignoring tp %d cond"), b->number);
11985     }
11986
11987   if (b->commands || *default_collect)
11988     strcat (buf, "-");
11989   putpkt (buf);
11990   remote_get_noisy_reply (&target_buf, &target_buf_size);
11991   if (strcmp (target_buf, "OK"))
11992     error (_("Target does not support tracepoints."));
11993
11994   /* do_single_steps (t); */
11995   if (tdp_actions)
11996     {
11997       for (ndx = 0; tdp_actions[ndx]; ndx++)
11998         {
11999           QUIT; /* Allow user to bail out with ^C.  */
12000           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12001                      b->number, addrbuf, /* address */
12002                      tdp_actions[ndx],
12003                      ((tdp_actions[ndx + 1] || stepping_actions)
12004                       ? '-' : 0));
12005           putpkt (buf);
12006           remote_get_noisy_reply (&target_buf,
12007                                   &target_buf_size);
12008           if (strcmp (target_buf, "OK"))
12009             error (_("Error on target while setting tracepoints."));
12010         }
12011     }
12012   if (stepping_actions)
12013     {
12014       for (ndx = 0; stepping_actions[ndx]; ndx++)
12015         {
12016           QUIT; /* Allow user to bail out with ^C.  */
12017           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12018                      b->number, addrbuf, /* address */
12019                      ((ndx == 0) ? "S" : ""),
12020                      stepping_actions[ndx],
12021                      (stepping_actions[ndx + 1] ? "-" : ""));
12022           putpkt (buf);
12023           remote_get_noisy_reply (&target_buf,
12024                                   &target_buf_size);
12025           if (strcmp (target_buf, "OK"))
12026             error (_("Error on target while setting tracepoints."));
12027         }
12028     }
12029
12030   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12031     {
12032       if (b->location != NULL)
12033         {
12034           strcpy (buf, "QTDPsrc:");
12035           encode_source_string (b->number, loc->address, "at",
12036                                 event_location_to_string (b->location),
12037                                 buf + strlen (buf), 2048 - strlen (buf));
12038           putpkt (buf);
12039           remote_get_noisy_reply (&target_buf, &target_buf_size);
12040           if (strcmp (target_buf, "OK"))
12041             warning (_("Target does not support source download."));
12042         }
12043       if (b->cond_string)
12044         {
12045           strcpy (buf, "QTDPsrc:");
12046           encode_source_string (b->number, loc->address,
12047                                 "cond", b->cond_string, buf + strlen (buf),
12048                                 2048 - strlen (buf));
12049           putpkt (buf);
12050           remote_get_noisy_reply (&target_buf, &target_buf_size);
12051           if (strcmp (target_buf, "OK"))
12052             warning (_("Target does not support source download."));
12053         }
12054       remote_download_command_source (b->number, loc->address,
12055                                       breakpoint_commands (b));
12056     }
12057
12058   do_cleanups (old_chain);
12059 }
12060
12061 static int
12062 remote_can_download_tracepoint (struct target_ops *self)
12063 {
12064   struct remote_state *rs = get_remote_state ();
12065   struct trace_status *ts;
12066   int status;
12067
12068   /* Don't try to install tracepoints until we've relocated our
12069      symbols, and fetched and merged the target's tracepoint list with
12070      ours.  */
12071   if (rs->starting_up)
12072     return 0;
12073
12074   ts = current_trace_status ();
12075   status = remote_get_trace_status (self, ts);
12076
12077   if (status == -1 || !ts->running_known || !ts->running)
12078     return 0;
12079
12080   /* If we are in a tracing experiment, but remote stub doesn't support
12081      installing tracepoint in trace, we have to return.  */
12082   if (!remote_supports_install_in_trace ())
12083     return 0;
12084
12085   return 1;
12086 }
12087
12088
12089 static void
12090 remote_download_trace_state_variable (struct target_ops *self,
12091                                       struct trace_state_variable *tsv)
12092 {
12093   struct remote_state *rs = get_remote_state ();
12094   char *p;
12095
12096   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12097              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12098              tsv->builtin);
12099   p = rs->buf + strlen (rs->buf);
12100   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12101     error (_("Trace state variable name too long for tsv definition packet"));
12102   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12103   *p++ = '\0';
12104   putpkt (rs->buf);
12105   remote_get_noisy_reply (&target_buf, &target_buf_size);
12106   if (*target_buf == '\0')
12107     error (_("Target does not support this command."));
12108   if (strcmp (target_buf, "OK") != 0)
12109     error (_("Error on target while downloading trace state variable."));
12110 }
12111
12112 static void
12113 remote_enable_tracepoint (struct target_ops *self,
12114                           struct bp_location *location)
12115 {
12116   struct remote_state *rs = get_remote_state ();
12117   char addr_buf[40];
12118
12119   sprintf_vma (addr_buf, location->address);
12120   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12121              location->owner->number, addr_buf);
12122   putpkt (rs->buf);
12123   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12124   if (*rs->buf == '\0')
12125     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12126   if (strcmp (rs->buf, "OK") != 0)
12127     error (_("Error on target while enabling tracepoint."));
12128 }
12129
12130 static void
12131 remote_disable_tracepoint (struct target_ops *self,
12132                            struct bp_location *location)
12133 {
12134   struct remote_state *rs = get_remote_state ();
12135   char addr_buf[40];
12136
12137   sprintf_vma (addr_buf, location->address);
12138   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12139              location->owner->number, addr_buf);
12140   putpkt (rs->buf);
12141   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12142   if (*rs->buf == '\0')
12143     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12144   if (strcmp (rs->buf, "OK") != 0)
12145     error (_("Error on target while disabling tracepoint."));
12146 }
12147
12148 static void
12149 remote_trace_set_readonly_regions (struct target_ops *self)
12150 {
12151   asection *s;
12152   bfd *abfd = NULL;
12153   bfd_size_type size;
12154   bfd_vma vma;
12155   int anysecs = 0;
12156   int offset = 0;
12157
12158   if (!exec_bfd)
12159     return;                     /* No information to give.  */
12160
12161   strcpy (target_buf, "QTro");
12162   offset = strlen (target_buf);
12163   for (s = exec_bfd->sections; s; s = s->next)
12164     {
12165       char tmp1[40], tmp2[40];
12166       int sec_length;
12167
12168       if ((s->flags & SEC_LOAD) == 0 ||
12169       /*  (s->flags & SEC_CODE) == 0 || */
12170           (s->flags & SEC_READONLY) == 0)
12171         continue;
12172
12173       anysecs = 1;
12174       vma = bfd_get_section_vma (abfd, s);
12175       size = bfd_get_section_size (s);
12176       sprintf_vma (tmp1, vma);
12177       sprintf_vma (tmp2, vma + size);
12178       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12179       if (offset + sec_length + 1 > target_buf_size)
12180         {
12181           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12182             warning (_("\
12183 Too many sections for read-only sections definition packet."));
12184           break;
12185         }
12186       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12187                  tmp1, tmp2);
12188       offset += sec_length;
12189     }
12190   if (anysecs)
12191     {
12192       putpkt (target_buf);
12193       getpkt (&target_buf, &target_buf_size, 0);
12194     }
12195 }
12196
12197 static void
12198 remote_trace_start (struct target_ops *self)
12199 {
12200   putpkt ("QTStart");
12201   remote_get_noisy_reply (&target_buf, &target_buf_size);
12202   if (*target_buf == '\0')
12203     error (_("Target does not support this command."));
12204   if (strcmp (target_buf, "OK") != 0)
12205     error (_("Bogus reply from target: %s"), target_buf);
12206 }
12207
12208 static int
12209 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12210 {
12211   /* Initialize it just to avoid a GCC false warning.  */
12212   char *p = NULL;
12213   /* FIXME we need to get register block size some other way.  */
12214   extern int trace_regblock_size;
12215   enum packet_result result;
12216
12217   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12218     return -1;
12219
12220   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12221
12222   putpkt ("qTStatus");
12223
12224   TRY
12225     {
12226       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12227     }
12228   CATCH (ex, RETURN_MASK_ERROR)
12229     {
12230       if (ex.error != TARGET_CLOSE_ERROR)
12231         {
12232           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12233           return -1;
12234         }
12235       throw_exception (ex);
12236     }
12237   END_CATCH
12238
12239   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12240
12241   /* If the remote target doesn't do tracing, flag it.  */
12242   if (result == PACKET_UNKNOWN)
12243     return -1;
12244
12245   /* We're working with a live target.  */
12246   ts->filename = NULL;
12247
12248   if (*p++ != 'T')
12249     error (_("Bogus trace status reply from target: %s"), target_buf);
12250
12251   /* Function 'parse_trace_status' sets default value of each field of
12252      'ts' at first, so we don't have to do it here.  */
12253   parse_trace_status (p, ts);
12254
12255   return ts->running;
12256 }
12257
12258 static void
12259 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12260                               struct uploaded_tp *utp)
12261 {
12262   struct remote_state *rs = get_remote_state ();
12263   char *reply;
12264   struct bp_location *loc;
12265   struct tracepoint *tp = (struct tracepoint *) bp;
12266   size_t size = get_remote_packet_size ();
12267
12268   if (tp)
12269     {
12270       tp->base.hit_count = 0;
12271       tp->traceframe_usage = 0;
12272       for (loc = tp->base.loc; loc; loc = loc->next)
12273         {
12274           /* If the tracepoint was never downloaded, don't go asking for
12275              any status.  */
12276           if (tp->number_on_target == 0)
12277             continue;
12278           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12279                      phex_nz (loc->address, 0));
12280           putpkt (rs->buf);
12281           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12282           if (reply && *reply)
12283             {
12284               if (*reply == 'V')
12285                 parse_tracepoint_status (reply + 1, bp, utp);
12286             }
12287         }
12288     }
12289   else if (utp)
12290     {
12291       utp->hit_count = 0;
12292       utp->traceframe_usage = 0;
12293       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12294                  phex_nz (utp->addr, 0));
12295       putpkt (rs->buf);
12296       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12297       if (reply && *reply)
12298         {
12299           if (*reply == 'V')
12300             parse_tracepoint_status (reply + 1, bp, utp);
12301         }
12302     }
12303 }
12304
12305 static void
12306 remote_trace_stop (struct target_ops *self)
12307 {
12308   putpkt ("QTStop");
12309   remote_get_noisy_reply (&target_buf, &target_buf_size);
12310   if (*target_buf == '\0')
12311     error (_("Target does not support this command."));
12312   if (strcmp (target_buf, "OK") != 0)
12313     error (_("Bogus reply from target: %s"), target_buf);
12314 }
12315
12316 static int
12317 remote_trace_find (struct target_ops *self,
12318                    enum trace_find_type type, int num,
12319                    CORE_ADDR addr1, CORE_ADDR addr2,
12320                    int *tpp)
12321 {
12322   struct remote_state *rs = get_remote_state ();
12323   char *endbuf = rs->buf + get_remote_packet_size ();
12324   char *p, *reply;
12325   int target_frameno = -1, target_tracept = -1;
12326
12327   /* Lookups other than by absolute frame number depend on the current
12328      trace selected, so make sure it is correct on the remote end
12329      first.  */
12330   if (type != tfind_number)
12331     set_remote_traceframe ();
12332
12333   p = rs->buf;
12334   strcpy (p, "QTFrame:");
12335   p = strchr (p, '\0');
12336   switch (type)
12337     {
12338     case tfind_number:
12339       xsnprintf (p, endbuf - p, "%x", num);
12340       break;
12341     case tfind_pc:
12342       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12343       break;
12344     case tfind_tp:
12345       xsnprintf (p, endbuf - p, "tdp:%x", num);
12346       break;
12347     case tfind_range:
12348       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12349                  phex_nz (addr2, 0));
12350       break;
12351     case tfind_outside:
12352       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12353                  phex_nz (addr2, 0));
12354       break;
12355     default:
12356       error (_("Unknown trace find type %d"), type);
12357     }
12358
12359   putpkt (rs->buf);
12360   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12361   if (*reply == '\0')
12362     error (_("Target does not support this command."));
12363
12364   while (reply && *reply)
12365     switch (*reply)
12366       {
12367       case 'F':
12368         p = ++reply;
12369         target_frameno = (int) strtol (p, &reply, 16);
12370         if (reply == p)
12371           error (_("Unable to parse trace frame number"));
12372         /* Don't update our remote traceframe number cache on failure
12373            to select a remote traceframe.  */
12374         if (target_frameno == -1)
12375           return -1;
12376         break;
12377       case 'T':
12378         p = ++reply;
12379         target_tracept = (int) strtol (p, &reply, 16);
12380         if (reply == p)
12381           error (_("Unable to parse tracepoint number"));
12382         break;
12383       case 'O':         /* "OK"? */
12384         if (reply[1] == 'K' && reply[2] == '\0')
12385           reply += 2;
12386         else
12387           error (_("Bogus reply from target: %s"), reply);
12388         break;
12389       default:
12390         error (_("Bogus reply from target: %s"), reply);
12391       }
12392   if (tpp)
12393     *tpp = target_tracept;
12394
12395   rs->remote_traceframe_number = target_frameno;
12396   return target_frameno;
12397 }
12398
12399 static int
12400 remote_get_trace_state_variable_value (struct target_ops *self,
12401                                        int tsvnum, LONGEST *val)
12402 {
12403   struct remote_state *rs = get_remote_state ();
12404   char *reply;
12405   ULONGEST uval;
12406
12407   set_remote_traceframe ();
12408
12409   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12410   putpkt (rs->buf);
12411   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12412   if (reply && *reply)
12413     {
12414       if (*reply == 'V')
12415         {
12416           unpack_varlen_hex (reply + 1, &uval);
12417           *val = (LONGEST) uval;
12418           return 1;
12419         }
12420     }
12421   return 0;
12422 }
12423
12424 static int
12425 remote_save_trace_data (struct target_ops *self, const char *filename)
12426 {
12427   struct remote_state *rs = get_remote_state ();
12428   char *p, *reply;
12429
12430   p = rs->buf;
12431   strcpy (p, "QTSave:");
12432   p += strlen (p);
12433   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12434     error (_("Remote file name too long for trace save packet"));
12435   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12436   *p++ = '\0';
12437   putpkt (rs->buf);
12438   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12439   if (*reply == '\0')
12440     error (_("Target does not support this command."));
12441   if (strcmp (reply, "OK") != 0)
12442     error (_("Bogus reply from target: %s"), reply);
12443   return 0;
12444 }
12445
12446 /* This is basically a memory transfer, but needs to be its own packet
12447    because we don't know how the target actually organizes its trace
12448    memory, plus we want to be able to ask for as much as possible, but
12449    not be unhappy if we don't get as much as we ask for.  */
12450
12451 static LONGEST
12452 remote_get_raw_trace_data (struct target_ops *self,
12453                            gdb_byte *buf, ULONGEST offset, LONGEST len)
12454 {
12455   struct remote_state *rs = get_remote_state ();
12456   char *reply;
12457   char *p;
12458   int rslt;
12459
12460   p = rs->buf;
12461   strcpy (p, "qTBuffer:");
12462   p += strlen (p);
12463   p += hexnumstr (p, offset);
12464   *p++ = ',';
12465   p += hexnumstr (p, len);
12466   *p++ = '\0';
12467
12468   putpkt (rs->buf);
12469   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12470   if (reply && *reply)
12471     {
12472       /* 'l' by itself means we're at the end of the buffer and
12473          there is nothing more to get.  */
12474       if (*reply == 'l')
12475         return 0;
12476
12477       /* Convert the reply into binary.  Limit the number of bytes to
12478          convert according to our passed-in buffer size, rather than
12479          what was returned in the packet; if the target is
12480          unexpectedly generous and gives us a bigger reply than we
12481          asked for, we don't want to crash.  */
12482       rslt = hex2bin (target_buf, buf, len);
12483       return rslt;
12484     }
12485
12486   /* Something went wrong, flag as an error.  */
12487   return -1;
12488 }
12489
12490 static void
12491 remote_set_disconnected_tracing (struct target_ops *self, int val)
12492 {
12493   struct remote_state *rs = get_remote_state ();
12494
12495   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12496     {
12497       char *reply;
12498
12499       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12500       putpkt (rs->buf);
12501       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12502       if (*reply == '\0')
12503         error (_("Target does not support this command."));
12504       if (strcmp (reply, "OK") != 0)
12505         error (_("Bogus reply from target: %s"), reply);
12506     }
12507   else if (val)
12508     warning (_("Target does not support disconnected tracing."));
12509 }
12510
12511 static int
12512 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12513 {
12514   struct thread_info *info = find_thread_ptid (ptid);
12515
12516   if (info && info->priv)
12517     return info->priv->core;
12518   return -1;
12519 }
12520
12521 static void
12522 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12523 {
12524   struct remote_state *rs = get_remote_state ();
12525   char *reply;
12526
12527   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12528   putpkt (rs->buf);
12529   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12530   if (*reply == '\0')
12531     error (_("Target does not support this command."));
12532   if (strcmp (reply, "OK") != 0)
12533     error (_("Bogus reply from target: %s"), reply);
12534 }
12535
12536 static struct traceframe_info *
12537 remote_traceframe_info (struct target_ops *self)
12538 {
12539   char *text;
12540
12541   text = target_read_stralloc (&current_target,
12542                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12543   if (text != NULL)
12544     {
12545       struct traceframe_info *info;
12546       struct cleanup *back_to = make_cleanup (xfree, text);
12547
12548       info = parse_traceframe_info (text);
12549       do_cleanups (back_to);
12550       return info;
12551     }
12552
12553   return NULL;
12554 }
12555
12556 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
12557    instruction on which a fast tracepoint may be placed.  Returns -1
12558    if the packet is not supported, and 0 if the minimum instruction
12559    length is unknown.  */
12560
12561 static int
12562 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12563 {
12564   struct remote_state *rs = get_remote_state ();
12565   char *reply;
12566
12567   /* If we're not debugging a process yet, the IPA can't be
12568      loaded.  */
12569   if (!target_has_execution)
12570     return 0;
12571
12572   /* Make sure the remote is pointing at the right process.  */
12573   set_general_process ();
12574
12575   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12576   putpkt (rs->buf);
12577   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12578   if (*reply == '\0')
12579     return -1;
12580   else
12581     {
12582       ULONGEST min_insn_len;
12583
12584       unpack_varlen_hex (reply, &min_insn_len);
12585
12586       return (int) min_insn_len;
12587     }
12588 }
12589
12590 static void
12591 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12592 {
12593   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12594     {
12595       struct remote_state *rs = get_remote_state ();
12596       char *buf = rs->buf;
12597       char *endbuf = rs->buf + get_remote_packet_size ();
12598       enum packet_result result;
12599
12600       gdb_assert (val >= 0 || val == -1);
12601       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12602       /* Send -1 as literal "-1" to avoid host size dependency.  */
12603       if (val < 0)
12604         {
12605           *buf++ = '-';
12606           buf += hexnumstr (buf, (ULONGEST) -val);
12607         }
12608       else
12609         buf += hexnumstr (buf, (ULONGEST) val);
12610
12611       putpkt (rs->buf);
12612       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12613       result = packet_ok (rs->buf,
12614                   &remote_protocol_packets[PACKET_QTBuffer_size]);
12615
12616       if (result != PACKET_OK)
12617         warning (_("Bogus reply from target: %s"), rs->buf);
12618     }
12619 }
12620
12621 static int
12622 remote_set_trace_notes (struct target_ops *self,
12623                         const char *user, const char *notes,
12624                         const char *stop_notes)
12625 {
12626   struct remote_state *rs = get_remote_state ();
12627   char *reply;
12628   char *buf = rs->buf;
12629   char *endbuf = rs->buf + get_remote_packet_size ();
12630   int nbytes;
12631
12632   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12633   if (user)
12634     {
12635       buf += xsnprintf (buf, endbuf - buf, "user:");
12636       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12637       buf += 2 * nbytes;
12638       *buf++ = ';';
12639     }
12640   if (notes)
12641     {
12642       buf += xsnprintf (buf, endbuf - buf, "notes:");
12643       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12644       buf += 2 * nbytes;
12645       *buf++ = ';';
12646     }
12647   if (stop_notes)
12648     {
12649       buf += xsnprintf (buf, endbuf - buf, "tstop:");
12650       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12651       buf += 2 * nbytes;
12652       *buf++ = ';';
12653     }
12654   /* Ensure the buffer is terminated.  */
12655   *buf = '\0';
12656
12657   putpkt (rs->buf);
12658   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12659   if (*reply == '\0')
12660     return 0;
12661
12662   if (strcmp (reply, "OK") != 0)
12663     error (_("Bogus reply from target: %s"), reply);
12664
12665   return 1;
12666 }
12667
12668 static int
12669 remote_use_agent (struct target_ops *self, int use)
12670 {
12671   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12672     {
12673       struct remote_state *rs = get_remote_state ();
12674
12675       /* If the stub supports QAgent.  */
12676       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12677       putpkt (rs->buf);
12678       getpkt (&rs->buf, &rs->buf_size, 0);
12679
12680       if (strcmp (rs->buf, "OK") == 0)
12681         {
12682           use_agent = use;
12683           return 1;
12684         }
12685     }
12686
12687   return 0;
12688 }
12689
12690 static int
12691 remote_can_use_agent (struct target_ops *self)
12692 {
12693   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12694 }
12695
12696 struct btrace_target_info
12697 {
12698   /* The ptid of the traced thread.  */
12699   ptid_t ptid;
12700
12701   /* The obtained branch trace configuration.  */
12702   struct btrace_config conf;
12703 };
12704
12705 /* Reset our idea of our target's btrace configuration.  */
12706
12707 static void
12708 remote_btrace_reset (void)
12709 {
12710   struct remote_state *rs = get_remote_state ();
12711
12712   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12713 }
12714
12715 /* Check whether the target supports branch tracing.  */
12716
12717 static int
12718 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12719 {
12720   if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12721     return 0;
12722   if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12723     return 0;
12724
12725   switch (format)
12726     {
12727       case BTRACE_FORMAT_NONE:
12728         return 0;
12729
12730       case BTRACE_FORMAT_BTS:
12731         return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12732
12733       case BTRACE_FORMAT_PT:
12734         /* The trace is decoded on the host.  Even if our target supports it,
12735            we still need to have libipt to decode the trace.  */
12736 #if defined (HAVE_LIBIPT)
12737         return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12738 #else /* !defined (HAVE_LIBIPT)  */
12739         return 0;
12740 #endif /* !defined (HAVE_LIBIPT)  */
12741     }
12742
12743   internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12744 }
12745
12746 /* Synchronize the configuration with the target.  */
12747
12748 static void
12749 btrace_sync_conf (const struct btrace_config *conf)
12750 {
12751   struct packet_config *packet;
12752   struct remote_state *rs;
12753   char *buf, *pos, *endbuf;
12754
12755   rs = get_remote_state ();
12756   buf = rs->buf;
12757   endbuf = buf + get_remote_packet_size ();
12758
12759   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12760   if (packet_config_support (packet) == PACKET_ENABLE
12761       && conf->bts.size != rs->btrace_config.bts.size)
12762     {
12763       pos = buf;
12764       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12765                         conf->bts.size);
12766
12767       putpkt (buf);
12768       getpkt (&buf, &rs->buf_size, 0);
12769
12770       if (packet_ok (buf, packet) == PACKET_ERROR)
12771         {
12772           if (buf[0] == 'E' && buf[1] == '.')
12773             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12774           else
12775             error (_("Failed to configure the BTS buffer size."));
12776         }
12777
12778       rs->btrace_config.bts.size = conf->bts.size;
12779     }
12780
12781   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12782   if (packet_config_support (packet) == PACKET_ENABLE
12783       && conf->pt.size != rs->btrace_config.pt.size)
12784     {
12785       pos = buf;
12786       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12787                         conf->pt.size);
12788
12789       putpkt (buf);
12790       getpkt (&buf, &rs->buf_size, 0);
12791
12792       if (packet_ok (buf, packet) == PACKET_ERROR)
12793         {
12794           if (buf[0] == 'E' && buf[1] == '.')
12795             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12796           else
12797             error (_("Failed to configure the trace buffer size."));
12798         }
12799
12800       rs->btrace_config.pt.size = conf->pt.size;
12801     }
12802 }
12803
12804 /* Read the current thread's btrace configuration from the target and
12805    store it into CONF.  */
12806
12807 static void
12808 btrace_read_config (struct btrace_config *conf)
12809 {
12810   char *xml;
12811
12812   xml = target_read_stralloc (&current_target,
12813                               TARGET_OBJECT_BTRACE_CONF, "");
12814   if (xml != NULL)
12815     {
12816       struct cleanup *cleanup;
12817
12818       cleanup = make_cleanup (xfree, xml);
12819       parse_xml_btrace_conf (conf, xml);
12820       do_cleanups (cleanup);
12821     }
12822 }
12823
12824 /* Enable branch tracing.  */
12825
12826 static struct btrace_target_info *
12827 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12828                       const struct btrace_config *conf)
12829 {
12830   struct btrace_target_info *tinfo = NULL;
12831   struct packet_config *packet = NULL;
12832   struct remote_state *rs = get_remote_state ();
12833   char *buf = rs->buf;
12834   char *endbuf = rs->buf + get_remote_packet_size ();
12835
12836   switch (conf->format)
12837     {
12838       case BTRACE_FORMAT_BTS:
12839         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12840         break;
12841
12842       case BTRACE_FORMAT_PT:
12843         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12844         break;
12845     }
12846
12847   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12848     error (_("Target does not support branch tracing."));
12849
12850   btrace_sync_conf (conf);
12851
12852   set_general_thread (ptid);
12853
12854   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12855   putpkt (rs->buf);
12856   getpkt (&rs->buf, &rs->buf_size, 0);
12857
12858   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12859     {
12860       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12861         error (_("Could not enable branch tracing for %s: %s"),
12862                target_pid_to_str (ptid), rs->buf + 2);
12863       else
12864         error (_("Could not enable branch tracing for %s."),
12865                target_pid_to_str (ptid));
12866     }
12867
12868   tinfo = XCNEW (struct btrace_target_info);
12869   tinfo->ptid = ptid;
12870
12871   /* If we fail to read the configuration, we lose some information, but the
12872      tracing itself is not impacted.  */
12873   TRY
12874     {
12875       btrace_read_config (&tinfo->conf);
12876     }
12877   CATCH (err, RETURN_MASK_ERROR)
12878     {
12879       if (err.message != NULL)
12880         warning ("%s", err.message);
12881     }
12882   END_CATCH
12883
12884   return tinfo;
12885 }
12886
12887 /* Disable branch tracing.  */
12888
12889 static void
12890 remote_disable_btrace (struct target_ops *self,
12891                        struct btrace_target_info *tinfo)
12892 {
12893   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12894   struct remote_state *rs = get_remote_state ();
12895   char *buf = rs->buf;
12896   char *endbuf = rs->buf + get_remote_packet_size ();
12897
12898   if (packet_config_support (packet) != PACKET_ENABLE)
12899     error (_("Target does not support branch tracing."));
12900
12901   set_general_thread (tinfo->ptid);
12902
12903   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12904   putpkt (rs->buf);
12905   getpkt (&rs->buf, &rs->buf_size, 0);
12906
12907   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12908     {
12909       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12910         error (_("Could not disable branch tracing for %s: %s"),
12911                target_pid_to_str (tinfo->ptid), rs->buf + 2);
12912       else
12913         error (_("Could not disable branch tracing for %s."),
12914                target_pid_to_str (tinfo->ptid));
12915     }
12916
12917   xfree (tinfo);
12918 }
12919
12920 /* Teardown branch tracing.  */
12921
12922 static void
12923 remote_teardown_btrace (struct target_ops *self,
12924                         struct btrace_target_info *tinfo)
12925 {
12926   /* We must not talk to the target during teardown.  */
12927   xfree (tinfo);
12928 }
12929
12930 /* Read the branch trace.  */
12931
12932 static enum btrace_error
12933 remote_read_btrace (struct target_ops *self,
12934                     struct btrace_data *btrace,
12935                     struct btrace_target_info *tinfo,
12936                     enum btrace_read_type type)
12937 {
12938   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12939   struct cleanup *cleanup;
12940   const char *annex;
12941   char *xml;
12942
12943   if (packet_config_support (packet) != PACKET_ENABLE)
12944     error (_("Target does not support branch tracing."));
12945
12946 #if !defined(HAVE_LIBEXPAT)
12947   error (_("Cannot process branch tracing result. XML parsing not supported."));
12948 #endif
12949
12950   switch (type)
12951     {
12952     case BTRACE_READ_ALL:
12953       annex = "all";
12954       break;
12955     case BTRACE_READ_NEW:
12956       annex = "new";
12957       break;
12958     case BTRACE_READ_DELTA:
12959       annex = "delta";
12960       break;
12961     default:
12962       internal_error (__FILE__, __LINE__,
12963                       _("Bad branch tracing read type: %u."),
12964                       (unsigned int) type);
12965     }
12966
12967   xml = target_read_stralloc (&current_target,
12968                               TARGET_OBJECT_BTRACE, annex);
12969   if (xml == NULL)
12970     return BTRACE_ERR_UNKNOWN;
12971
12972   cleanup = make_cleanup (xfree, xml);
12973   parse_xml_btrace (btrace, xml);
12974   do_cleanups (cleanup);
12975
12976   return BTRACE_ERR_NONE;
12977 }
12978
12979 static const struct btrace_config *
12980 remote_btrace_conf (struct target_ops *self,
12981                     const struct btrace_target_info *tinfo)
12982 {
12983   return &tinfo->conf;
12984 }
12985
12986 static int
12987 remote_augmented_libraries_svr4_read (struct target_ops *self)
12988 {
12989   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12990           == PACKET_ENABLE);
12991 }
12992
12993 /* Implementation of to_load.  */
12994
12995 static void
12996 remote_load (struct target_ops *self, const char *name, int from_tty)
12997 {
12998   generic_load (name, from_tty);
12999 }
13000
13001 /* Accepts an integer PID; returns a string representing a file that
13002    can be opened on the remote side to get the symbols for the child
13003    process.  Returns NULL if the operation is not supported.  */
13004
13005 static char *
13006 remote_pid_to_exec_file (struct target_ops *self, int pid)
13007 {
13008   static char *filename = NULL;
13009   struct inferior *inf;
13010   char *annex = NULL;
13011
13012   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13013     return NULL;
13014
13015   if (filename != NULL)
13016     xfree (filename);
13017
13018   inf = find_inferior_pid (pid);
13019   if (inf == NULL)
13020     internal_error (__FILE__, __LINE__,
13021                     _("not currently attached to process %d"), pid);
13022
13023   if (!inf->fake_pid_p)
13024     {
13025       const int annex_size = 9;
13026
13027       annex = (char *) alloca (annex_size);
13028       xsnprintf (annex, annex_size, "%x", pid);
13029     }
13030
13031   filename = target_read_stralloc (&current_target,
13032                                    TARGET_OBJECT_EXEC_FILE, annex);
13033
13034   return filename;
13035 }
13036
13037 /* Implement the to_can_do_single_step target_ops method.  */
13038
13039 static int
13040 remote_can_do_single_step (struct target_ops *ops)
13041 {
13042   /* We can only tell whether target supports single step or not by
13043      supported s and S vCont actions if the stub supports vContSupported
13044      feature.  If the stub doesn't support vContSupported feature,
13045      we have conservatively to think target doesn't supports single
13046      step.  */
13047   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13048     {
13049       struct remote_state *rs = get_remote_state ();
13050
13051       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13052         remote_vcont_probe (rs);
13053
13054       return rs->supports_vCont.s && rs->supports_vCont.S;
13055     }
13056   else
13057     return 0;
13058 }
13059
13060 static void
13061 init_remote_ops (void)
13062 {
13063   remote_ops.to_shortname = "remote";
13064   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13065   remote_ops.to_doc =
13066     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13067 Specify the serial device it is connected to\n\
13068 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13069   remote_ops.to_open = remote_open;
13070   remote_ops.to_close = remote_close;
13071   remote_ops.to_detach = remote_detach;
13072   remote_ops.to_disconnect = remote_disconnect;
13073   remote_ops.to_resume = remote_resume;
13074   remote_ops.to_wait = remote_wait;
13075   remote_ops.to_fetch_registers = remote_fetch_registers;
13076   remote_ops.to_store_registers = remote_store_registers;
13077   remote_ops.to_prepare_to_store = remote_prepare_to_store;
13078   remote_ops.to_files_info = remote_files_info;
13079   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13080   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13081   remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13082   remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13083   remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13084   remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13085   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13086   remote_ops.to_stopped_data_address = remote_stopped_data_address;
13087   remote_ops.to_watchpoint_addr_within_range =
13088     remote_watchpoint_addr_within_range;
13089   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13090   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13091   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13092   remote_ops.to_region_ok_for_hw_watchpoint
13093      = remote_region_ok_for_hw_watchpoint;
13094   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13095   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13096   remote_ops.to_kill = remote_kill;
13097   remote_ops.to_load = remote_load;
13098   remote_ops.to_mourn_inferior = remote_mourn;
13099   remote_ops.to_pass_signals = remote_pass_signals;
13100   remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13101   remote_ops.to_program_signals = remote_program_signals;
13102   remote_ops.to_thread_alive = remote_thread_alive;
13103   remote_ops.to_thread_name = remote_thread_name;
13104   remote_ops.to_update_thread_list = remote_update_thread_list;
13105   remote_ops.to_pid_to_str = remote_pid_to_str;
13106   remote_ops.to_extra_thread_info = remote_threads_extra_info;
13107   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13108   remote_ops.to_stop = remote_stop;
13109   remote_ops.to_interrupt = remote_interrupt;
13110   remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
13111   remote_ops.to_xfer_partial = remote_xfer_partial;
13112   remote_ops.to_rcmd = remote_rcmd;
13113   remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13114   remote_ops.to_log_command = serial_log_command;
13115   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13116   remote_ops.to_stratum = process_stratum;
13117   remote_ops.to_has_all_memory = default_child_has_all_memory;
13118   remote_ops.to_has_memory = default_child_has_memory;
13119   remote_ops.to_has_stack = default_child_has_stack;
13120   remote_ops.to_has_registers = default_child_has_registers;
13121   remote_ops.to_has_execution = default_child_has_execution;
13122   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
13123   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13124   remote_ops.to_magic = OPS_MAGIC;
13125   remote_ops.to_memory_map = remote_memory_map;
13126   remote_ops.to_flash_erase = remote_flash_erase;
13127   remote_ops.to_flash_done = remote_flash_done;
13128   remote_ops.to_read_description = remote_read_description;
13129   remote_ops.to_search_memory = remote_search_memory;
13130   remote_ops.to_can_async_p = remote_can_async_p;
13131   remote_ops.to_is_async_p = remote_is_async_p;
13132   remote_ops.to_async = remote_async;
13133   remote_ops.to_thread_events = remote_thread_events;
13134   remote_ops.to_can_do_single_step = remote_can_do_single_step;
13135   remote_ops.to_terminal_inferior = remote_terminal_inferior;
13136   remote_ops.to_terminal_ours = remote_terminal_ours;
13137   remote_ops.to_supports_non_stop = remote_supports_non_stop;
13138   remote_ops.to_supports_multi_process = remote_supports_multi_process;
13139   remote_ops.to_supports_disable_randomization
13140     = remote_supports_disable_randomization;
13141   remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13142   remote_ops.to_fileio_open = remote_hostio_open;
13143   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13144   remote_ops.to_fileio_pread = remote_hostio_pread;
13145   remote_ops.to_fileio_fstat = remote_hostio_fstat;
13146   remote_ops.to_fileio_close = remote_hostio_close;
13147   remote_ops.to_fileio_unlink = remote_hostio_unlink;
13148   remote_ops.to_fileio_readlink = remote_hostio_readlink;
13149   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13150   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13151   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13152   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13153   remote_ops.to_trace_init = remote_trace_init;
13154   remote_ops.to_download_tracepoint = remote_download_tracepoint;
13155   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13156   remote_ops.to_download_trace_state_variable
13157     = remote_download_trace_state_variable;
13158   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13159   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13160   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13161   remote_ops.to_trace_start = remote_trace_start;
13162   remote_ops.to_get_trace_status = remote_get_trace_status;
13163   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13164   remote_ops.to_trace_stop = remote_trace_stop;
13165   remote_ops.to_trace_find = remote_trace_find;
13166   remote_ops.to_get_trace_state_variable_value
13167     = remote_get_trace_state_variable_value;
13168   remote_ops.to_save_trace_data = remote_save_trace_data;
13169   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13170   remote_ops.to_upload_trace_state_variables
13171     = remote_upload_trace_state_variables;
13172   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13173   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13174   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13175   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13176   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13177   remote_ops.to_set_trace_notes = remote_set_trace_notes;
13178   remote_ops.to_core_of_thread = remote_core_of_thread;
13179   remote_ops.to_verify_memory = remote_verify_memory;
13180   remote_ops.to_get_tib_address = remote_get_tib_address;
13181   remote_ops.to_set_permissions = remote_set_permissions;
13182   remote_ops.to_static_tracepoint_marker_at
13183     = remote_static_tracepoint_marker_at;
13184   remote_ops.to_static_tracepoint_markers_by_strid
13185     = remote_static_tracepoint_markers_by_strid;
13186   remote_ops.to_traceframe_info = remote_traceframe_info;
13187   remote_ops.to_use_agent = remote_use_agent;
13188   remote_ops.to_can_use_agent = remote_can_use_agent;
13189   remote_ops.to_supports_btrace = remote_supports_btrace;
13190   remote_ops.to_enable_btrace = remote_enable_btrace;
13191   remote_ops.to_disable_btrace = remote_disable_btrace;
13192   remote_ops.to_teardown_btrace = remote_teardown_btrace;
13193   remote_ops.to_read_btrace = remote_read_btrace;
13194   remote_ops.to_btrace_conf = remote_btrace_conf;
13195   remote_ops.to_augmented_libraries_svr4_read =
13196     remote_augmented_libraries_svr4_read;
13197   remote_ops.to_follow_fork = remote_follow_fork;
13198   remote_ops.to_follow_exec = remote_follow_exec;
13199   remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13200   remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13201   remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13202   remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13203   remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13204   remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13205 }
13206
13207 /* Set up the extended remote vector by making a copy of the standard
13208    remote vector and adding to it.  */
13209
13210 static void
13211 init_extended_remote_ops (void)
13212 {
13213   extended_remote_ops = remote_ops;
13214
13215   extended_remote_ops.to_shortname = "extended-remote";
13216   extended_remote_ops.to_longname =
13217     "Extended remote serial target in gdb-specific protocol";
13218   extended_remote_ops.to_doc =
13219     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13220 Specify the serial device it is connected to (e.g. /dev/ttya).";
13221   extended_remote_ops.to_open = extended_remote_open;
13222   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13223   extended_remote_ops.to_detach = extended_remote_detach;
13224   extended_remote_ops.to_attach = extended_remote_attach;
13225   extended_remote_ops.to_post_attach = extended_remote_post_attach;
13226   extended_remote_ops.to_supports_disable_randomization
13227     = extended_remote_supports_disable_randomization;
13228 }
13229
13230 static int
13231 remote_can_async_p (struct target_ops *ops)
13232 {
13233   struct remote_state *rs = get_remote_state ();
13234
13235   if (!target_async_permitted)
13236     /* We only enable async when the user specifically asks for it.  */
13237     return 0;
13238
13239   /* We're async whenever the serial device is.  */
13240   return serial_can_async_p (rs->remote_desc);
13241 }
13242
13243 static int
13244 remote_is_async_p (struct target_ops *ops)
13245 {
13246   struct remote_state *rs = get_remote_state ();
13247
13248   if (!target_async_permitted)
13249     /* We only enable async when the user specifically asks for it.  */
13250     return 0;
13251
13252   /* We're async whenever the serial device is.  */
13253   return serial_is_async_p (rs->remote_desc);
13254 }
13255
13256 /* Pass the SERIAL event on and up to the client.  One day this code
13257    will be able to delay notifying the client of an event until the
13258    point where an entire packet has been received.  */
13259
13260 static serial_event_ftype remote_async_serial_handler;
13261
13262 static void
13263 remote_async_serial_handler (struct serial *scb, void *context)
13264 {
13265   /* Don't propogate error information up to the client.  Instead let
13266      the client find out about the error by querying the target.  */
13267   inferior_event_handler (INF_REG_EVENT, NULL);
13268 }
13269
13270 static void
13271 remote_async_inferior_event_handler (gdb_client_data data)
13272 {
13273   inferior_event_handler (INF_REG_EVENT, NULL);
13274 }
13275
13276 static void
13277 remote_async (struct target_ops *ops, int enable)
13278 {
13279   struct remote_state *rs = get_remote_state ();
13280
13281   if (enable)
13282     {
13283       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13284
13285       /* If there are pending events in the stop reply queue tell the
13286          event loop to process them.  */
13287       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13288         mark_async_event_handler (remote_async_inferior_event_token);
13289       /* For simplicity, below we clear the pending events token
13290          without remembering whether it is marked, so here we always
13291          mark it.  If there's actually no pending notification to
13292          process, this ends up being a no-op (other than a spurious
13293          event-loop wakeup).  */
13294       if (target_is_non_stop_p ())
13295         mark_async_event_handler (rs->notif_state->get_pending_events_token);
13296     }
13297   else
13298     {
13299       serial_async (rs->remote_desc, NULL, NULL);
13300       /* If the core is disabling async, it doesn't want to be
13301          disturbed with target events.  Clear all async event sources
13302          too.  */
13303       clear_async_event_handler (remote_async_inferior_event_token);
13304       if (target_is_non_stop_p ())
13305         clear_async_event_handler (rs->notif_state->get_pending_events_token);
13306     }
13307 }
13308
13309 /* Implementation of the to_thread_events method.  */
13310
13311 static void
13312 remote_thread_events (struct target_ops *ops, int enable)
13313 {
13314   struct remote_state *rs = get_remote_state ();
13315   size_t size = get_remote_packet_size ();
13316
13317   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13318     return;
13319
13320   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13321   putpkt (rs->buf);
13322   getpkt (&rs->buf, &rs->buf_size, 0);
13323
13324   switch (packet_ok (rs->buf,
13325                      &remote_protocol_packets[PACKET_QThreadEvents]))
13326     {
13327     case PACKET_OK:
13328       if (strcmp (rs->buf, "OK") != 0)
13329         error (_("Remote refused setting thread events: %s"), rs->buf);
13330       break;
13331     case PACKET_ERROR:
13332       warning (_("Remote failure reply: %s"), rs->buf);
13333       break;
13334     case PACKET_UNKNOWN:
13335       break;
13336     }
13337 }
13338
13339 static void
13340 set_remote_cmd (char *args, int from_tty)
13341 {
13342   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13343 }
13344
13345 static void
13346 show_remote_cmd (char *args, int from_tty)
13347 {
13348   /* We can't just use cmd_show_list here, because we want to skip
13349      the redundant "show remote Z-packet" and the legacy aliases.  */
13350   struct cleanup *showlist_chain;
13351   struct cmd_list_element *list = remote_show_cmdlist;
13352   struct ui_out *uiout = current_uiout;
13353
13354   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13355   for (; list != NULL; list = list->next)
13356     if (strcmp (list->name, "Z-packet") == 0)
13357       continue;
13358     else if (list->type == not_set_cmd)
13359       /* Alias commands are exactly like the original, except they
13360          don't have the normal type.  */
13361       continue;
13362     else
13363       {
13364         struct cleanup *option_chain
13365           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13366
13367         ui_out_field_string (uiout, "name", list->name);
13368         ui_out_text (uiout, ":  ");
13369         if (list->type == show_cmd)
13370           do_show_command ((char *) NULL, from_tty, list);
13371         else
13372           cmd_func (list, NULL, from_tty);
13373         /* Close the tuple.  */
13374         do_cleanups (option_chain);
13375       }
13376
13377   /* Close the tuple.  */
13378   do_cleanups (showlist_chain);
13379 }
13380
13381
13382 /* Function to be called whenever a new objfile (shlib) is detected.  */
13383 static void
13384 remote_new_objfile (struct objfile *objfile)
13385 {
13386   struct remote_state *rs = get_remote_state ();
13387
13388   if (rs->remote_desc != 0)             /* Have a remote connection.  */
13389     remote_check_symbols ();
13390 }
13391
13392 /* Pull all the tracepoints defined on the target and create local
13393    data structures representing them.  We don't want to create real
13394    tracepoints yet, we don't want to mess up the user's existing
13395    collection.  */
13396   
13397 static int
13398 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13399 {
13400   struct remote_state *rs = get_remote_state ();
13401   char *p;
13402
13403   /* Ask for a first packet of tracepoint definition.  */
13404   putpkt ("qTfP");
13405   getpkt (&rs->buf, &rs->buf_size, 0);
13406   p = rs->buf;
13407   while (*p && *p != 'l')
13408     {
13409       parse_tracepoint_definition (p, utpp);
13410       /* Ask for another packet of tracepoint definition.  */
13411       putpkt ("qTsP");
13412       getpkt (&rs->buf, &rs->buf_size, 0);
13413       p = rs->buf;
13414     }
13415   return 0;
13416 }
13417
13418 static int
13419 remote_upload_trace_state_variables (struct target_ops *self,
13420                                      struct uploaded_tsv **utsvp)
13421 {
13422   struct remote_state *rs = get_remote_state ();
13423   char *p;
13424
13425   /* Ask for a first packet of variable definition.  */
13426   putpkt ("qTfV");
13427   getpkt (&rs->buf, &rs->buf_size, 0);
13428   p = rs->buf;
13429   while (*p && *p != 'l')
13430     {
13431       parse_tsv_definition (p, utsvp);
13432       /* Ask for another packet of variable definition.  */
13433       putpkt ("qTsV");
13434       getpkt (&rs->buf, &rs->buf_size, 0);
13435       p = rs->buf;
13436     }
13437   return 0;
13438 }
13439
13440 /* The "set/show range-stepping" show hook.  */
13441
13442 static void
13443 show_range_stepping (struct ui_file *file, int from_tty,
13444                      struct cmd_list_element *c,
13445                      const char *value)
13446 {
13447   fprintf_filtered (file,
13448                     _("Debugger's willingness to use range stepping "
13449                       "is %s.\n"), value);
13450 }
13451
13452 /* The "set/show range-stepping" set hook.  */
13453
13454 static void
13455 set_range_stepping (char *ignore_args, int from_tty,
13456                     struct cmd_list_element *c)
13457 {
13458   struct remote_state *rs = get_remote_state ();
13459
13460   /* Whene enabling, check whether range stepping is actually
13461      supported by the target, and warn if not.  */
13462   if (use_range_stepping)
13463     {
13464       if (rs->remote_desc != NULL)
13465         {
13466           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13467             remote_vcont_probe (rs);
13468
13469           if (packet_support (PACKET_vCont) == PACKET_ENABLE
13470               && rs->supports_vCont.r)
13471             return;
13472         }
13473
13474       warning (_("Range stepping is not supported by the current target"));
13475     }
13476 }
13477
13478 void
13479 _initialize_remote (void)
13480 {
13481   struct cmd_list_element *cmd;
13482   const char *cmd_name;
13483
13484   /* architecture specific data */
13485   remote_gdbarch_data_handle =
13486     gdbarch_data_register_post_init (init_remote_state);
13487   remote_g_packet_data_handle =
13488     gdbarch_data_register_pre_init (remote_g_packet_data_init);
13489
13490   remote_pspace_data
13491     = register_program_space_data_with_cleanup (NULL,
13492                                                 remote_pspace_data_cleanup);
13493
13494   /* Initialize the per-target state.  At the moment there is only one
13495      of these, not one per target.  Only one target is active at a
13496      time.  */
13497   remote_state = new_remote_state ();
13498
13499   init_remote_ops ();
13500   add_target (&remote_ops);
13501
13502   init_extended_remote_ops ();
13503   add_target (&extended_remote_ops);
13504
13505   /* Hook into new objfile notification.  */
13506   observer_attach_new_objfile (remote_new_objfile);
13507   /* We're no longer interested in notification events of an inferior
13508      when it exits.  */
13509   observer_attach_inferior_exit (discard_pending_stop_replies);
13510
13511   /* Set up signal handlers.  */
13512   async_sigint_remote_token =
13513     create_async_signal_handler (async_remote_interrupt, NULL);
13514   async_sigint_remote_twice_token =
13515     create_async_signal_handler (async_remote_interrupt_twice, NULL);
13516
13517 #if 0
13518   init_remote_threadtests ();
13519 #endif
13520
13521   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13522   /* set/show remote ...  */
13523
13524   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13525 Remote protocol specific variables\n\
13526 Configure various remote-protocol specific variables such as\n\
13527 the packets being used"),
13528                   &remote_set_cmdlist, "set remote ",
13529                   0 /* allow-unknown */, &setlist);
13530   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13531 Remote protocol specific variables\n\
13532 Configure various remote-protocol specific variables such as\n\
13533 the packets being used"),
13534                   &remote_show_cmdlist, "show remote ",
13535                   0 /* allow-unknown */, &showlist);
13536
13537   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13538 Compare section data on target to the exec file.\n\
13539 Argument is a single section name (default: all loaded sections).\n\
13540 To compare only read-only loaded sections, specify the -r option."),
13541            &cmdlist);
13542
13543   add_cmd ("packet", class_maintenance, packet_command, _("\
13544 Send an arbitrary packet to a remote target.\n\
13545    maintenance packet TEXT\n\
13546 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13547 this command sends the string TEXT to the inferior, and displays the\n\
13548 response packet.  GDB supplies the initial `$' character, and the\n\
13549 terminating `#' character and checksum."),
13550            &maintenancelist);
13551
13552   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13553 Set whether to send break if interrupted."), _("\
13554 Show whether to send break if interrupted."), _("\
13555 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13556                            set_remotebreak, show_remotebreak,
13557                            &setlist, &showlist);
13558   cmd_name = "remotebreak";
13559   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13560   deprecate_cmd (cmd, "set remote interrupt-sequence");
13561   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13562   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13563   deprecate_cmd (cmd, "show remote interrupt-sequence");
13564
13565   add_setshow_enum_cmd ("interrupt-sequence", class_support,
13566                         interrupt_sequence_modes, &interrupt_sequence_mode,
13567                         _("\
13568 Set interrupt sequence to remote target."), _("\
13569 Show interrupt sequence to remote target."), _("\
13570 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13571                         NULL, show_interrupt_sequence,
13572                         &remote_set_cmdlist,
13573                         &remote_show_cmdlist);
13574
13575   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13576                            &interrupt_on_connect, _("\
13577 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
13578 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
13579 If set, interrupt sequence is sent to remote target."),
13580                            NULL, NULL,
13581                            &remote_set_cmdlist, &remote_show_cmdlist);
13582
13583   /* Install commands for configuring memory read/write packets.  */
13584
13585   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13586 Set the maximum number of bytes per memory write packet (deprecated)."),
13587            &setlist);
13588   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13589 Show the maximum number of bytes per memory write packet (deprecated)."),
13590            &showlist);
13591   add_cmd ("memory-write-packet-size", no_class,
13592            set_memory_write_packet_size, _("\
13593 Set the maximum number of bytes per memory-write packet.\n\
13594 Specify the number of bytes in a packet or 0 (zero) for the\n\
13595 default packet size.  The actual limit is further reduced\n\
13596 dependent on the target.  Specify ``fixed'' to disable the\n\
13597 further restriction and ``limit'' to enable that restriction."),
13598            &remote_set_cmdlist);
13599   add_cmd ("memory-read-packet-size", no_class,
13600            set_memory_read_packet_size, _("\
13601 Set the maximum number of bytes per memory-read packet.\n\
13602 Specify the number of bytes in a packet or 0 (zero) for the\n\
13603 default packet size.  The actual limit is further reduced\n\
13604 dependent on the target.  Specify ``fixed'' to disable the\n\
13605 further restriction and ``limit'' to enable that restriction."),
13606            &remote_set_cmdlist);
13607   add_cmd ("memory-write-packet-size", no_class,
13608            show_memory_write_packet_size,
13609            _("Show the maximum number of bytes per memory-write packet."),
13610            &remote_show_cmdlist);
13611   add_cmd ("memory-read-packet-size", no_class,
13612            show_memory_read_packet_size,
13613            _("Show the maximum number of bytes per memory-read packet."),
13614            &remote_show_cmdlist);
13615
13616   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13617                             &remote_hw_watchpoint_limit, _("\
13618 Set the maximum number of target hardware watchpoints."), _("\
13619 Show the maximum number of target hardware watchpoints."), _("\
13620 Specify a negative limit for unlimited."),
13621                             NULL, NULL, /* FIXME: i18n: The maximum
13622                                            number of target hardware
13623                                            watchpoints is %s.  */
13624                             &remote_set_cmdlist, &remote_show_cmdlist);
13625   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13626                             &remote_hw_watchpoint_length_limit, _("\
13627 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13628 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13629 Specify a negative limit for unlimited."),
13630                             NULL, NULL, /* FIXME: i18n: The maximum
13631                                            length (in bytes) of a target
13632                                            hardware watchpoint is %s.  */
13633                             &remote_set_cmdlist, &remote_show_cmdlist);
13634   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13635                             &remote_hw_breakpoint_limit, _("\
13636 Set the maximum number of target hardware breakpoints."), _("\
13637 Show the maximum number of target hardware breakpoints."), _("\
13638 Specify a negative limit for unlimited."),
13639                             NULL, NULL, /* FIXME: i18n: The maximum
13640                                            number of target hardware
13641                                            breakpoints is %s.  */
13642                             &remote_set_cmdlist, &remote_show_cmdlist);
13643
13644   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13645                              &remote_address_size, _("\
13646 Set the maximum size of the address (in bits) in a memory packet."), _("\
13647 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13648                              NULL,
13649                              NULL, /* FIXME: i18n: */
13650                              &setlist, &showlist);
13651
13652   init_all_packet_configs ();
13653
13654   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13655                          "X", "binary-download", 1);
13656
13657   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13658                          "vCont", "verbose-resume", 0);
13659
13660   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13661                          "QPassSignals", "pass-signals", 0);
13662
13663   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13664                          "QCatchSyscalls", "catch-syscalls", 0);
13665
13666   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13667                          "QProgramSignals", "program-signals", 0);
13668
13669   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13670                          "qSymbol", "symbol-lookup", 0);
13671
13672   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13673                          "P", "set-register", 1);
13674
13675   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13676                          "p", "fetch-register", 1);
13677
13678   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13679                          "Z0", "software-breakpoint", 0);
13680
13681   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13682                          "Z1", "hardware-breakpoint", 0);
13683
13684   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13685                          "Z2", "write-watchpoint", 0);
13686
13687   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13688                          "Z3", "read-watchpoint", 0);
13689
13690   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13691                          "Z4", "access-watchpoint", 0);
13692
13693   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13694                          "qXfer:auxv:read", "read-aux-vector", 0);
13695
13696   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13697                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
13698
13699   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13700                          "qXfer:features:read", "target-features", 0);
13701
13702   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13703                          "qXfer:libraries:read", "library-info", 0);
13704
13705   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13706                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13707
13708   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13709                          "qXfer:memory-map:read", "memory-map", 0);
13710
13711   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13712                          "qXfer:spu:read", "read-spu-object", 0);
13713
13714   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13715                          "qXfer:spu:write", "write-spu-object", 0);
13716
13717   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13718                         "qXfer:osdata:read", "osdata", 0);
13719
13720   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13721                          "qXfer:threads:read", "threads", 0);
13722
13723   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13724                          "qXfer:siginfo:read", "read-siginfo-object", 0);
13725
13726   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13727                          "qXfer:siginfo:write", "write-siginfo-object", 0);
13728
13729   add_packet_config_cmd
13730     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13731      "qXfer:traceframe-info:read", "traceframe-info", 0);
13732
13733   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13734                          "qXfer:uib:read", "unwind-info-block", 0);
13735
13736   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13737                          "qGetTLSAddr", "get-thread-local-storage-address",
13738                          0);
13739
13740   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13741                          "qGetTIBAddr", "get-thread-information-block-address",
13742                          0);
13743
13744   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13745                          "bc", "reverse-continue", 0);
13746
13747   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13748                          "bs", "reverse-step", 0);
13749
13750   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13751                          "qSupported", "supported-packets", 0);
13752
13753   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13754                          "qSearch:memory", "search-memory", 0);
13755
13756   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13757                          "qTStatus", "trace-status", 0);
13758
13759   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13760                          "vFile:setfs", "hostio-setfs", 0);
13761
13762   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13763                          "vFile:open", "hostio-open", 0);
13764
13765   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13766                          "vFile:pread", "hostio-pread", 0);
13767
13768   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13769                          "vFile:pwrite", "hostio-pwrite", 0);
13770
13771   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13772                          "vFile:close", "hostio-close", 0);
13773
13774   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13775                          "vFile:unlink", "hostio-unlink", 0);
13776
13777   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13778                          "vFile:readlink", "hostio-readlink", 0);
13779
13780   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13781                          "vFile:fstat", "hostio-fstat", 0);
13782
13783   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13784                          "vAttach", "attach", 0);
13785
13786   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13787                          "vRun", "run", 0);
13788
13789   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13790                          "QStartNoAckMode", "noack", 0);
13791
13792   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13793                          "vKill", "kill", 0);
13794
13795   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13796                          "qAttached", "query-attached", 0);
13797
13798   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13799                          "ConditionalTracepoints",
13800                          "conditional-tracepoints", 0);
13801
13802   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13803                          "ConditionalBreakpoints",
13804                          "conditional-breakpoints", 0);
13805
13806   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13807                          "BreakpointCommands",
13808                          "breakpoint-commands", 0);
13809
13810   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13811                          "FastTracepoints", "fast-tracepoints", 0);
13812
13813   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13814                          "TracepointSource", "TracepointSource", 0);
13815
13816   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13817                          "QAllow", "allow", 0);
13818
13819   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13820                          "StaticTracepoints", "static-tracepoints", 0);
13821
13822   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13823                          "InstallInTrace", "install-in-trace", 0);
13824
13825   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13826                          "qXfer:statictrace:read", "read-sdata-object", 0);
13827
13828   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13829                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13830
13831   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13832                          "QDisableRandomization", "disable-randomization", 0);
13833
13834   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13835                          "QAgent", "agent", 0);
13836
13837   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13838                          "QTBuffer:size", "trace-buffer-size", 0);
13839
13840   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13841        "Qbtrace:off", "disable-btrace", 0);
13842
13843   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13844        "Qbtrace:bts", "enable-btrace-bts", 0);
13845
13846   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13847        "Qbtrace:pt", "enable-btrace-pt", 0);
13848
13849   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13850        "qXfer:btrace", "read-btrace", 0);
13851
13852   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13853        "qXfer:btrace-conf", "read-btrace-conf", 0);
13854
13855   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13856        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13857
13858   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13859        "multiprocess-feature", "multiprocess-feature", 0);
13860
13861   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13862                          "swbreak-feature", "swbreak-feature", 0);
13863
13864   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13865                          "hwbreak-feature", "hwbreak-feature", 0);
13866
13867   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13868                          "fork-event-feature", "fork-event-feature", 0);
13869
13870   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13871                          "vfork-event-feature", "vfork-event-feature", 0);
13872
13873   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13874        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13875
13876   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13877                          "vContSupported", "verbose-resume-supported", 0);
13878
13879   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13880                          "exec-event-feature", "exec-event-feature", 0);
13881
13882   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13883                          "vCtrlC", "ctrl-c", 0);
13884
13885   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13886                          "QThreadEvents", "thread-events", 0);
13887
13888   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13889                          "N stop reply", "no-resumed-stop-reply", 0);
13890
13891   /* Assert that we've registered "set remote foo-packet" commands
13892      for all packet configs.  */
13893   {
13894     int i;
13895
13896     for (i = 0; i < PACKET_MAX; i++)
13897       {
13898         /* Ideally all configs would have a command associated.  Some
13899            still don't though.  */
13900         int excepted;
13901
13902         switch (i)
13903           {
13904           case PACKET_QNonStop:
13905           case PACKET_EnableDisableTracepoints_feature:
13906           case PACKET_tracenz_feature:
13907           case PACKET_DisconnectedTracing_feature:
13908           case PACKET_augmented_libraries_svr4_read_feature:
13909           case PACKET_qCRC:
13910             /* Additions to this list need to be well justified:
13911                pre-existing packets are OK; new packets are not.  */
13912             excepted = 1;
13913             break;
13914           default:
13915             excepted = 0;
13916             break;
13917           }
13918
13919         /* This catches both forgetting to add a config command, and
13920            forgetting to remove a packet from the exception list.  */
13921         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13922       }
13923   }
13924
13925   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
13926      Z sub-packet has its own set and show commands, but users may
13927      have sets to this variable in their .gdbinit files (or in their
13928      documentation).  */
13929   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13930                                 &remote_Z_packet_detect, _("\
13931 Set use of remote protocol `Z' packets"), _("\
13932 Show use of remote protocol `Z' packets "), _("\
13933 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13934 packets."),
13935                                 set_remote_protocol_Z_packet_cmd,
13936                                 show_remote_protocol_Z_packet_cmd,
13937                                 /* FIXME: i18n: Use of remote protocol
13938                                    `Z' packets is %s.  */
13939                                 &remote_set_cmdlist, &remote_show_cmdlist);
13940
13941   add_prefix_cmd ("remote", class_files, remote_command, _("\
13942 Manipulate files on the remote system\n\
13943 Transfer files to and from the remote target system."),
13944                   &remote_cmdlist, "remote ",
13945                   0 /* allow-unknown */, &cmdlist);
13946
13947   add_cmd ("put", class_files, remote_put_command,
13948            _("Copy a local file to the remote system."),
13949            &remote_cmdlist);
13950
13951   add_cmd ("get", class_files, remote_get_command,
13952            _("Copy a remote file to the local system."),
13953            &remote_cmdlist);
13954
13955   add_cmd ("delete", class_files, remote_delete_command,
13956            _("Delete a remote file."),
13957            &remote_cmdlist);
13958
13959   add_setshow_string_noescape_cmd ("exec-file", class_files,
13960                                    &remote_exec_file_var, _("\
13961 Set the remote pathname for \"run\""), _("\
13962 Show the remote pathname for \"run\""), NULL,
13963                                    set_remote_exec_file,
13964                                    show_remote_exec_file,
13965                                    &remote_set_cmdlist,
13966                                    &remote_show_cmdlist);
13967
13968   add_setshow_boolean_cmd ("range-stepping", class_run,
13969                            &use_range_stepping, _("\
13970 Enable or disable range stepping."), _("\
13971 Show whether target-assisted range stepping is enabled."), _("\
13972 If on, and the target supports it, when stepping a source line, GDB\n\
13973 tells the target to step the corresponding range of addresses itself instead\n\
13974 of issuing multiple single-steps.  This speeds up source level\n\
13975 stepping.  If off, GDB always issues single-steps, even if range\n\
13976 stepping is supported by the target.  The default is on."),
13977                            set_range_stepping,
13978                            show_range_stepping,
13979                            &setlist,
13980                            &showlist);
13981
13982   /* Eventually initialize fileio.  See fileio.c */
13983   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13984
13985   /* Take advantage of the fact that the TID field is not used, to tag
13986      special ptids with it set to != 0.  */
13987   magic_null_ptid = ptid_build (42000, -1, 1);
13988   not_sent_ptid = ptid_build (42000, -2, 1);
13989   any_thread_ptid = ptid_build (42000, 0, 1);
13990
13991   target_buf_size = 2048;
13992   target_buf = (char *) xmalloc (target_buf_size);
13993 }
13994