remote.c: Add missing cast
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2015 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_mourn (struct target_ops *ops);
123
124 static void extended_remote_restart (void);
125
126 static void extended_remote_mourn (struct target_ops *);
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 sync_remote_interrupt_twice (int signo);
143
144 static void interrupt_query (void);
145
146 static void set_general_thread (struct ptid ptid);
147 static void set_continue_thread (struct ptid ptid);
148
149 static void get_offsets (void);
150
151 static void skip_frame (void);
152
153 static long read_frame (char **buf_p, long *sizeof_buf);
154
155 static int hexnumlen (ULONGEST num);
156
157 static void init_remote_ops (void);
158
159 static void init_extended_remote_ops (void);
160
161 static void remote_stop (struct target_ops *self, ptid_t);
162
163 static int stubhex (int ch);
164
165 static int hexnumstr (char *, ULONGEST);
166
167 static int hexnumnstr (char *, ULONGEST, int);
168
169 static CORE_ADDR remote_address_masked (CORE_ADDR);
170
171 static void print_packet (const char *);
172
173 static void compare_sections_command (char *, int);
174
175 static void packet_command (char *, int);
176
177 static int stub_unpack_int (char *buff, int fieldlength);
178
179 static ptid_t remote_current_thread (ptid_t oldptid);
180
181 static int putpkt_binary (const char *buf, int cnt);
182
183 static void check_binary_download (CORE_ADDR addr);
184
185 struct packet_config;
186
187 static void show_packet_config_cmd (struct packet_config *config);
188
189 static void show_remote_protocol_packet_cmd (struct ui_file *file,
190                                              int from_tty,
191                                              struct cmd_list_element *c,
192                                              const char *value);
193
194 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
195 static ptid_t read_ptid (char *buf, char **obuf);
196
197 static void remote_set_permissions (struct target_ops *self);
198
199 static int remote_get_trace_status (struct target_ops *self,
200                                     struct trace_status *ts);
201
202 static int remote_upload_tracepoints (struct target_ops *self,
203                                       struct uploaded_tp **utpp);
204
205 static int remote_upload_trace_state_variables (struct target_ops *self,
206                                                 struct uploaded_tsv **utsvp);
207   
208 static void remote_query_supported (void);
209
210 static void remote_check_symbols (void);
211
212 void _initialize_remote (void);
213
214 struct stop_reply;
215 static void stop_reply_xfree (struct stop_reply *);
216 static void remote_parse_stop_reply (char *, struct stop_reply *);
217 static void push_stop_reply (struct stop_reply *);
218 static void discard_pending_stop_replies_in_queue (struct remote_state *);
219 static int peek_stop_reply (ptid_t ptid);
220
221 struct threads_listing_context;
222 static void remove_new_fork_children (struct threads_listing_context *);
223
224 static void remote_async_inferior_event_handler (gdb_client_data);
225
226 static void remote_terminal_ours (struct target_ops *self);
227
228 static int remote_read_description_p (struct target_ops *target);
229
230 static void remote_console_output (char *msg);
231
232 static int remote_supports_cond_breakpoints (struct target_ops *self);
233
234 static int remote_can_run_breakpoint_commands (struct target_ops *self);
235
236 static void remote_btrace_reset (void);
237
238 static int stop_reply_queue_length (void);
239
240 static void readahead_cache_invalidate (void);
241
242 /* For "remote".  */
243
244 static struct cmd_list_element *remote_cmdlist;
245
246 /* For "set remote" and "show remote".  */
247
248 static struct cmd_list_element *remote_set_cmdlist;
249 static struct cmd_list_element *remote_show_cmdlist;
250
251 /* Stub vCont actions support.
252
253    Each field is a boolean flag indicating whether the stub reports
254    support for the corresponding action.  */
255
256 struct vCont_action_support
257 {
258   /* vCont;t */
259   int t;
260
261   /* vCont;r */
262   int r;
263
264   /* vCont;s */
265   int s;
266
267   /* vCont;S */
268   int S;
269 };
270
271 /* Controls whether GDB is willing to use range stepping.  */
272
273 static int use_range_stepping = 1;
274
275 #define OPAQUETHREADBYTES 8
276
277 /* a 64 bit opaque identifier */
278 typedef unsigned char threadref[OPAQUETHREADBYTES];
279
280 /* About this many threadisds fit in a packet.  */
281
282 #define MAXTHREADLISTRESULTS 32
283
284 /* Data for the vFile:pread readahead cache.  */
285
286 struct readahead_cache
287 {
288   /* The file descriptor for the file that is being cached.  -1 if the
289      cache is invalid.  */
290   int fd;
291
292   /* The offset into the file that the cache buffer corresponds
293      to.  */
294   ULONGEST offset;
295
296   /* The buffer holding the cache contents.  */
297   gdb_byte *buf;
298   /* The buffer's size.  We try to read as much as fits into a packet
299      at a time.  */
300   size_t bufsize;
301
302   /* Cache hit and miss counters.  */
303   ULONGEST hit_count;
304   ULONGEST miss_count;
305 };
306
307 /* Description of the remote protocol state for the currently
308    connected target.  This is per-target state, and independent of the
309    selected architecture.  */
310
311 struct remote_state
312 {
313   /* A buffer to use for incoming packets, and its current size.  The
314      buffer is grown dynamically for larger incoming packets.
315      Outgoing packets may also be constructed in this buffer.
316      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
317      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
318      packets.  */
319   char *buf;
320   long buf_size;
321
322   /* True if we're going through initial connection setup (finding out
323      about the remote side's threads, relocating symbols, etc.).  */
324   int starting_up;
325
326   /* If we negotiated packet size explicitly (and thus can bypass
327      heuristics for the largest packet size that will not overflow
328      a buffer in the stub), this will be set to that packet size.
329      Otherwise zero, meaning to use the guessed size.  */
330   long explicit_packet_size;
331
332   /* remote_wait is normally called when the target is running and
333      waits for a stop reply packet.  But sometimes we need to call it
334      when the target is already stopped.  We can send a "?" packet
335      and have remote_wait read the response.  Or, if we already have
336      the response, we can stash it in BUF and tell remote_wait to
337      skip calling getpkt.  This flag is set when BUF contains a
338      stop reply packet and the target is not waiting.  */
339   int cached_wait_status;
340
341   /* True, if in no ack mode.  That is, neither GDB nor the stub will
342      expect acks from each other.  The connection is assumed to be
343      reliable.  */
344   int noack_mode;
345
346   /* True if we're connected in extended remote mode.  */
347   int extended;
348
349   /* True if we resumed the target and we're waiting for the target to
350      stop.  In the mean time, we can't start another command/query.
351      The remote server wouldn't be ready to process it, so we'd
352      timeout waiting for a reply that would never come and eventually
353      we'd close the connection.  This can happen in asynchronous mode
354      because we allow GDB commands while the target is running.  */
355   int waiting_for_stop_reply;
356
357   /* The status of the stub support for the various vCont actions.  */
358   struct vCont_action_support supports_vCont;
359
360   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
361      responded to that.  */
362   int ctrlc_pending_p;
363
364   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
365      remote_open knows that we don't have a file open when the program
366      starts.  */
367   struct serial *remote_desc;
368
369   /* These are the threads which we last sent to the remote system.  The
370      TID member will be -1 for all or -2 for not sent yet.  */
371   ptid_t general_thread;
372   ptid_t continue_thread;
373
374   /* This is the traceframe which we last selected on the remote system.
375      It will be -1 if no traceframe is selected.  */
376   int remote_traceframe_number;
377
378   char *last_pass_packet;
379
380   /* The last QProgramSignals packet sent to the target.  We bypass
381      sending a new program signals list down to the target if the new
382      packet is exactly the same as the last we sent.  IOW, we only let
383      the target know about program signals list changes.  */
384   char *last_program_signals_packet;
385
386   enum gdb_signal last_sent_signal;
387
388   int last_sent_step;
389
390   char *finished_object;
391   char *finished_annex;
392   ULONGEST finished_offset;
393
394   /* Should we try the 'ThreadInfo' query packet?
395
396      This variable (NOT available to the user: auto-detect only!)
397      determines whether GDB will use the new, simpler "ThreadInfo"
398      query or the older, more complex syntax for thread queries.
399      This is an auto-detect variable (set to true at each connect,
400      and set to false when the target fails to recognize it).  */
401   int use_threadinfo_query;
402   int use_threadextra_query;
403
404   /* This is set to the data address of the access causing the target
405      to stop for a watchpoint.  */
406   CORE_ADDR remote_watch_data_address;
407
408   /* Whether the target stopped for a breakpoint/watchpoint.  */
409   enum target_stop_reason stop_reason;
410
411   threadref echo_nextthread;
412   threadref nextthread;
413   threadref resultthreadlist[MAXTHREADLISTRESULTS];
414
415   /* The state of remote notification.  */
416   struct remote_notif_state *notif_state;
417
418   /* The branch trace configuration.  */
419   struct btrace_config btrace_config;
420
421   /* The argument to the last "vFile:setfs:" packet we sent, used
422      to avoid sending repeated unnecessary "vFile:setfs:" packets.
423      Initialized to -1 to indicate that no "vFile:setfs:" packet
424      has yet been sent.  */
425   int fs_pid;
426
427   /* A readahead cache for vFile:pread.  Often, reading a binary
428      involves a sequence of small reads.  E.g., when parsing an ELF
429      file.  A readahead cache helps mostly the case of remote
430      debugging on a connection with higher latency, due to the
431      request/reply nature of the RSP.  We only cache data for a single
432      file descriptor at a time.  */
433   struct readahead_cache readahead_cache;
434 };
435
436 /* Private data that we'll store in (struct thread_info)->private.  */
437 struct private_thread_info
438 {
439   char *extra;
440   char *name;
441   int core;
442 };
443
444 static void
445 free_private_thread_info (struct private_thread_info *info)
446 {
447   xfree (info->extra);
448   xfree (info->name);
449   xfree (info);
450 }
451
452 /* This data could be associated with a target, but we do not always
453    have access to the current target when we need it, so for now it is
454    static.  This will be fine for as long as only one target is in use
455    at a time.  */
456 static struct remote_state *remote_state;
457
458 static struct remote_state *
459 get_remote_state_raw (void)
460 {
461   return remote_state;
462 }
463
464 /* Allocate a new struct remote_state with xmalloc, initialize it, and
465    return it.  */
466
467 static struct remote_state *
468 new_remote_state (void)
469 {
470   struct remote_state *result = XCNEW (struct remote_state);
471
472   /* The default buffer size is unimportant; it will be expanded
473      whenever a larger buffer is needed. */
474   result->buf_size = 400;
475   result->buf = (char *) xmalloc (result->buf_size);
476   result->remote_traceframe_number = -1;
477   result->last_sent_signal = GDB_SIGNAL_0;
478   result->fs_pid = -1;
479
480   return result;
481 }
482
483 /* Description of the remote protocol for a given architecture.  */
484
485 struct packet_reg
486 {
487   long offset; /* Offset into G packet.  */
488   long regnum; /* GDB's internal register number.  */
489   LONGEST pnum; /* Remote protocol register number.  */
490   int in_g_packet; /* Always part of G packet.  */
491   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
492      at present.  */
493   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
494      at present.  */
495 };
496
497 struct remote_arch_state
498 {
499   /* Description of the remote protocol registers.  */
500   long sizeof_g_packet;
501
502   /* Description of the remote protocol registers indexed by REGNUM
503      (making an array gdbarch_num_regs in size).  */
504   struct packet_reg *regs;
505
506   /* This is the size (in chars) of the first response to the ``g''
507      packet.  It is used as a heuristic when determining the maximum
508      size of memory-read and memory-write packets.  A target will
509      typically only reserve a buffer large enough to hold the ``g''
510      packet.  The size does not include packet overhead (headers and
511      trailers).  */
512   long actual_register_packet_size;
513
514   /* This is the maximum size (in chars) of a non read/write packet.
515      It is also used as a cap on the size of read/write packets.  */
516   long remote_packet_size;
517 };
518
519 /* Utility: generate error from an incoming stub packet.  */
520 static void
521 trace_error (char *buf)
522 {
523   if (*buf++ != 'E')
524     return;                     /* not an error msg */
525   switch (*buf)
526     {
527     case '1':                   /* malformed packet error */
528       if (*++buf == '0')        /*   general case: */
529         error (_("remote.c: error in outgoing packet."));
530       else
531         error (_("remote.c: error in outgoing packet at field #%ld."),
532                strtol (buf, NULL, 16));
533     default:
534       error (_("Target returns error code '%s'."), buf);
535     }
536 }
537
538 /* Utility: wait for reply from stub, while accepting "O" packets.  */
539 static char *
540 remote_get_noisy_reply (char **buf_p,
541                         long *sizeof_buf)
542 {
543   do                            /* Loop on reply from remote stub.  */
544     {
545       char *buf;
546
547       QUIT;                     /* Allow user to bail out with ^C.  */
548       getpkt (buf_p, sizeof_buf, 0);
549       buf = *buf_p;
550       if (buf[0] == 'E')
551         trace_error (buf);
552       else if (startswith (buf, "qRelocInsn:"))
553         {
554           ULONGEST ul;
555           CORE_ADDR from, to, org_to;
556           char *p, *pp;
557           int adjusted_size = 0;
558           int relocated = 0;
559
560           p = buf + strlen ("qRelocInsn:");
561           pp = unpack_varlen_hex (p, &ul);
562           if (*pp != ';')
563             error (_("invalid qRelocInsn packet: %s"), buf);
564           from = ul;
565
566           p = pp + 1;
567           unpack_varlen_hex (p, &ul);
568           to = ul;
569
570           org_to = to;
571
572           TRY
573             {
574               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
575               relocated = 1;
576             }
577           CATCH (ex, RETURN_MASK_ALL)
578             {
579               if (ex.error == MEMORY_ERROR)
580                 {
581                   /* Propagate memory errors silently back to the
582                      target.  The stub may have limited the range of
583                      addresses we can write to, for example.  */
584                 }
585               else
586                 {
587                   /* Something unexpectedly bad happened.  Be verbose
588                      so we can tell what, and propagate the error back
589                      to the stub, so it doesn't get stuck waiting for
590                      a response.  */
591                   exception_fprintf (gdb_stderr, ex,
592                                      _("warning: relocating instruction: "));
593                 }
594               putpkt ("E01");
595             }
596           END_CATCH
597
598           if (relocated)
599             {
600               adjusted_size = to - org_to;
601
602               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
603               putpkt (buf);
604             }
605         }
606       else if (buf[0] == 'O' && buf[1] != 'K')
607         remote_console_output (buf + 1);        /* 'O' message from stub */
608       else
609         return buf;             /* Here's the actual reply.  */
610     }
611   while (1);
612 }
613
614 /* Handle for retreving the remote protocol data from gdbarch.  */
615 static struct gdbarch_data *remote_gdbarch_data_handle;
616
617 static struct remote_arch_state *
618 get_remote_arch_state (void)
619 {
620   gdb_assert (target_gdbarch () != NULL);
621   return ((struct remote_arch_state *)
622           gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
623 }
624
625 /* Fetch the global remote target state.  */
626
627 static struct remote_state *
628 get_remote_state (void)
629 {
630   /* Make sure that the remote architecture state has been
631      initialized, because doing so might reallocate rs->buf.  Any
632      function which calls getpkt also needs to be mindful of changes
633      to rs->buf, but this call limits the number of places which run
634      into trouble.  */
635   get_remote_arch_state ();
636
637   return get_remote_state_raw ();
638 }
639
640 /* Cleanup routine for the remote module's pspace data.  */
641
642 static void
643 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
644 {
645   char *remote_exec_file = (char *) arg;
646
647   xfree (remote_exec_file);
648 }
649
650 /* Fetch the remote exec-file from the current program space.  */
651
652 static const char *
653 get_remote_exec_file (void)
654 {
655   char *remote_exec_file;
656
657   remote_exec_file
658     = (char *) program_space_data (current_program_space,
659                                    remote_pspace_data);
660   if (remote_exec_file == NULL)
661     return "";
662
663   return remote_exec_file;
664 }
665
666 /* Set the remote exec file for PSPACE.  */
667
668 static void
669 set_pspace_remote_exec_file (struct program_space *pspace,
670                         char *remote_exec_file)
671 {
672   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
673
674   xfree (old_file);
675   set_program_space_data (pspace, remote_pspace_data,
676                           xstrdup (remote_exec_file));
677 }
678
679 /* The "set/show remote exec-file" set command hook.  */
680
681 static void
682 set_remote_exec_file (char *ignored, int from_tty,
683                       struct cmd_list_element *c)
684 {
685   gdb_assert (remote_exec_file_var != NULL);
686   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
687 }
688
689 /* The "set/show remote exec-file" show command hook.  */
690
691 static void
692 show_remote_exec_file (struct ui_file *file, int from_tty,
693                        struct cmd_list_element *cmd, const char *value)
694 {
695   fprintf_filtered (file, "%s\n", remote_exec_file_var);
696 }
697
698 static int
699 compare_pnums (const void *lhs_, const void *rhs_)
700 {
701   const struct packet_reg * const *lhs
702     = (const struct packet_reg * const *) lhs_;
703   const struct packet_reg * const *rhs
704     = (const struct packet_reg * const *) rhs_;
705
706   if ((*lhs)->pnum < (*rhs)->pnum)
707     return -1;
708   else if ((*lhs)->pnum == (*rhs)->pnum)
709     return 0;
710   else
711     return 1;
712 }
713
714 static int
715 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
716 {
717   int regnum, num_remote_regs, offset;
718   struct packet_reg **remote_regs;
719
720   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
721     {
722       struct packet_reg *r = &regs[regnum];
723
724       if (register_size (gdbarch, regnum) == 0)
725         /* Do not try to fetch zero-sized (placeholder) registers.  */
726         r->pnum = -1;
727       else
728         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
729
730       r->regnum = regnum;
731     }
732
733   /* Define the g/G packet format as the contents of each register
734      with a remote protocol number, in order of ascending protocol
735      number.  */
736
737   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
738   for (num_remote_regs = 0, regnum = 0;
739        regnum < gdbarch_num_regs (gdbarch);
740        regnum++)
741     if (regs[regnum].pnum != -1)
742       remote_regs[num_remote_regs++] = &regs[regnum];
743
744   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
745          compare_pnums);
746
747   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
748     {
749       remote_regs[regnum]->in_g_packet = 1;
750       remote_regs[regnum]->offset = offset;
751       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
752     }
753
754   return offset;
755 }
756
757 /* Given the architecture described by GDBARCH, return the remote
758    protocol register's number and the register's offset in the g/G
759    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
760    If the target does not have a mapping for REGNUM, return false,
761    otherwise, return true.  */
762
763 int
764 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
765                                    int *pnum, int *poffset)
766 {
767   int sizeof_g_packet;
768   struct packet_reg *regs;
769   struct cleanup *old_chain;
770
771   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
772
773   regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
774   old_chain = make_cleanup (xfree, regs);
775
776   sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
777
778   *pnum = regs[regnum].pnum;
779   *poffset = regs[regnum].offset;
780
781   do_cleanups (old_chain);
782
783   return *pnum != -1;
784 }
785
786 static void *
787 init_remote_state (struct gdbarch *gdbarch)
788 {
789   struct remote_state *rs = get_remote_state_raw ();
790   struct remote_arch_state *rsa;
791
792   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
793
794   /* Use the architecture to build a regnum<->pnum table, which will be
795      1:1 unless a feature set specifies otherwise.  */
796   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
797                                       gdbarch_num_regs (gdbarch),
798                                       struct packet_reg);
799
800   /* Record the maximum possible size of the g packet - it may turn out
801      to be smaller.  */
802   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
803
804   /* Default maximum number of characters in a packet body.  Many
805      remote stubs have a hardwired buffer size of 400 bytes
806      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
807      as the maximum packet-size to ensure that the packet and an extra
808      NUL character can always fit in the buffer.  This stops GDB
809      trashing stubs that try to squeeze an extra NUL into what is
810      already a full buffer (As of 1999-12-04 that was most stubs).  */
811   rsa->remote_packet_size = 400 - 1;
812
813   /* This one is filled in when a ``g'' packet is received.  */
814   rsa->actual_register_packet_size = 0;
815
816   /* Should rsa->sizeof_g_packet needs more space than the
817      default, adjust the size accordingly.  Remember that each byte is
818      encoded as two characters.  32 is the overhead for the packet
819      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
820      (``$NN:G...#NN'') is a better guess, the below has been padded a
821      little.  */
822   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
823     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
824
825   /* Make sure that the packet buffer is plenty big enough for
826      this architecture.  */
827   if (rs->buf_size < rsa->remote_packet_size)
828     {
829       rs->buf_size = 2 * rsa->remote_packet_size;
830       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
831     }
832
833   return rsa;
834 }
835
836 /* Return the current allowed size of a remote packet.  This is
837    inferred from the current architecture, and should be used to
838    limit the length of outgoing packets.  */
839 static long
840 get_remote_packet_size (void)
841 {
842   struct remote_state *rs = get_remote_state ();
843   struct remote_arch_state *rsa = get_remote_arch_state ();
844
845   if (rs->explicit_packet_size)
846     return rs->explicit_packet_size;
847
848   return rsa->remote_packet_size;
849 }
850
851 static struct packet_reg *
852 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
853 {
854   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
855     return NULL;
856   else
857     {
858       struct packet_reg *r = &rsa->regs[regnum];
859
860       gdb_assert (r->regnum == regnum);
861       return r;
862     }
863 }
864
865 static struct packet_reg *
866 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
867 {
868   int i;
869
870   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
871     {
872       struct packet_reg *r = &rsa->regs[i];
873
874       if (r->pnum == pnum)
875         return r;
876     }
877   return NULL;
878 }
879
880 static struct target_ops remote_ops;
881
882 static struct target_ops extended_remote_ops;
883
884 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
885    ``forever'' still use the normal timeout mechanism.  This is
886    currently used by the ASYNC code to guarentee that target reads
887    during the initial connect always time-out.  Once getpkt has been
888    modified to return a timeout indication and, in turn
889    remote_wait()/wait_for_inferior() have gained a timeout parameter
890    this can go away.  */
891 static int wait_forever_enabled_p = 1;
892
893 /* Allow the user to specify what sequence to send to the remote
894    when he requests a program interruption: Although ^C is usually
895    what remote systems expect (this is the default, here), it is
896    sometimes preferable to send a break.  On other systems such
897    as the Linux kernel, a break followed by g, which is Magic SysRq g
898    is required in order to interrupt the execution.  */
899 const char interrupt_sequence_control_c[] = "Ctrl-C";
900 const char interrupt_sequence_break[] = "BREAK";
901 const char interrupt_sequence_break_g[] = "BREAK-g";
902 static const char *const interrupt_sequence_modes[] =
903   {
904     interrupt_sequence_control_c,
905     interrupt_sequence_break,
906     interrupt_sequence_break_g,
907     NULL
908   };
909 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
910
911 static void
912 show_interrupt_sequence (struct ui_file *file, int from_tty,
913                          struct cmd_list_element *c,
914                          const char *value)
915 {
916   if (interrupt_sequence_mode == interrupt_sequence_control_c)
917     fprintf_filtered (file,
918                       _("Send the ASCII ETX character (Ctrl-c) "
919                         "to the remote target to interrupt the "
920                         "execution of the program.\n"));
921   else if (interrupt_sequence_mode == interrupt_sequence_break)
922     fprintf_filtered (file,
923                       _("send a break signal to the remote target "
924                         "to interrupt the execution of the program.\n"));
925   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
926     fprintf_filtered (file,
927                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
928                         "the remote target to interrupt the execution "
929                         "of Linux kernel.\n"));
930   else
931     internal_error (__FILE__, __LINE__,
932                     _("Invalid value for interrupt_sequence_mode: %s."),
933                     interrupt_sequence_mode);
934 }
935
936 /* This boolean variable specifies whether interrupt_sequence is sent
937    to the remote target when gdb connects to it.
938    This is mostly needed when you debug the Linux kernel: The Linux kernel
939    expects BREAK g which is Magic SysRq g for connecting gdb.  */
940 static int interrupt_on_connect = 0;
941
942 /* This variable is used to implement the "set/show remotebreak" commands.
943    Since these commands are now deprecated in favor of "set/show remote
944    interrupt-sequence", it no longer has any effect on the code.  */
945 static int remote_break;
946
947 static void
948 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
949 {
950   if (remote_break)
951     interrupt_sequence_mode = interrupt_sequence_break;
952   else
953     interrupt_sequence_mode = interrupt_sequence_control_c;
954 }
955
956 static void
957 show_remotebreak (struct ui_file *file, int from_tty,
958                   struct cmd_list_element *c,
959                   const char *value)
960 {
961 }
962
963 /* This variable sets the number of bits in an address that are to be
964    sent in a memory ("M" or "m") packet.  Normally, after stripping
965    leading zeros, the entire address would be sent.  This variable
966    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
967    initial implementation of remote.c restricted the address sent in
968    memory packets to ``host::sizeof long'' bytes - (typically 32
969    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
970    address was never sent.  Since fixing this bug may cause a break in
971    some remote targets this variable is principly provided to
972    facilitate backward compatibility.  */
973
974 static unsigned int remote_address_size;
975
976 /* Temporary to track who currently owns the terminal.  See
977    remote_terminal_* for more details.  */
978
979 static int remote_async_terminal_ours_p;
980
981 \f
982 /* User configurable variables for the number of characters in a
983    memory read/write packet.  MIN (rsa->remote_packet_size,
984    rsa->sizeof_g_packet) is the default.  Some targets need smaller
985    values (fifo overruns, et.al.) and some users need larger values
986    (speed up transfers).  The variables ``preferred_*'' (the user
987    request), ``current_*'' (what was actually set) and ``forced_*''
988    (Positive - a soft limit, negative - a hard limit).  */
989
990 struct memory_packet_config
991 {
992   char *name;
993   long size;
994   int fixed_p;
995 };
996
997 /* The default max memory-write-packet-size.  The 16k is historical.
998    (It came from older GDB's using alloca for buffers and the
999    knowledge (folklore?) that some hosts don't cope very well with
1000    large alloca calls.)  */
1001 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1002
1003 /* The minimum remote packet size for memory transfers.  Ensures we
1004    can write at least one byte.  */
1005 #define MIN_MEMORY_PACKET_SIZE 20
1006
1007 /* Compute the current size of a read/write packet.  Since this makes
1008    use of ``actual_register_packet_size'' the computation is dynamic.  */
1009
1010 static long
1011 get_memory_packet_size (struct memory_packet_config *config)
1012 {
1013   struct remote_state *rs = get_remote_state ();
1014   struct remote_arch_state *rsa = get_remote_arch_state ();
1015
1016   long what_they_get;
1017   if (config->fixed_p)
1018     {
1019       if (config->size <= 0)
1020         what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1021       else
1022         what_they_get = config->size;
1023     }
1024   else
1025     {
1026       what_they_get = get_remote_packet_size ();
1027       /* Limit the packet to the size specified by the user.  */
1028       if (config->size > 0
1029           && what_they_get > config->size)
1030         what_they_get = config->size;
1031
1032       /* Limit it to the size of the targets ``g'' response unless we have
1033          permission from the stub to use a larger packet size.  */
1034       if (rs->explicit_packet_size == 0
1035           && rsa->actual_register_packet_size > 0
1036           && what_they_get > rsa->actual_register_packet_size)
1037         what_they_get = rsa->actual_register_packet_size;
1038     }
1039   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1040     what_they_get = MIN_MEMORY_PACKET_SIZE;
1041
1042   /* Make sure there is room in the global buffer for this packet
1043      (including its trailing NUL byte).  */
1044   if (rs->buf_size < what_they_get + 1)
1045     {
1046       rs->buf_size = 2 * what_they_get;
1047       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1048     }
1049
1050   return what_they_get;
1051 }
1052
1053 /* Update the size of a read/write packet.  If they user wants
1054    something really big then do a sanity check.  */
1055
1056 static void
1057 set_memory_packet_size (char *args, struct memory_packet_config *config)
1058 {
1059   int fixed_p = config->fixed_p;
1060   long size = config->size;
1061
1062   if (args == NULL)
1063     error (_("Argument required (integer, `fixed' or `limited')."));
1064   else if (strcmp (args, "hard") == 0
1065       || strcmp (args, "fixed") == 0)
1066     fixed_p = 1;
1067   else if (strcmp (args, "soft") == 0
1068            || strcmp (args, "limit") == 0)
1069     fixed_p = 0;
1070   else
1071     {
1072       char *end;
1073
1074       size = strtoul (args, &end, 0);
1075       if (args == end)
1076         error (_("Invalid %s (bad syntax)."), config->name);
1077
1078       /* Instead of explicitly capping the size of a packet to or
1079          disallowing it, the user is allowed to set the size to
1080          something arbitrarily large.  */
1081     }
1082
1083   /* So that the query shows the correct value.  */
1084   if (size <= 0)
1085     size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1086
1087   /* Extra checks?  */
1088   if (fixed_p && !config->fixed_p)
1089     {
1090       if (! query (_("The target may not be able to correctly handle a %s\n"
1091                    "of %ld bytes. Change the packet size? "),
1092                    config->name, size))
1093         error (_("Packet size not changed."));
1094     }
1095   /* Update the config.  */
1096   config->fixed_p = fixed_p;
1097   config->size = size;
1098 }
1099
1100 static void
1101 show_memory_packet_size (struct memory_packet_config *config)
1102 {
1103   printf_filtered (_("The %s is %ld. "), config->name, config->size);
1104   if (config->fixed_p)
1105     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1106                      get_memory_packet_size (config));
1107   else
1108     printf_filtered (_("Packets are limited to %ld bytes.\n"),
1109                      get_memory_packet_size (config));
1110 }
1111
1112 static struct memory_packet_config memory_write_packet_config =
1113 {
1114   "memory-write-packet-size",
1115 };
1116
1117 static void
1118 set_memory_write_packet_size (char *args, int from_tty)
1119 {
1120   set_memory_packet_size (args, &memory_write_packet_config);
1121 }
1122
1123 static void
1124 show_memory_write_packet_size (char *args, int from_tty)
1125 {
1126   show_memory_packet_size (&memory_write_packet_config);
1127 }
1128
1129 static long
1130 get_memory_write_packet_size (void)
1131 {
1132   return get_memory_packet_size (&memory_write_packet_config);
1133 }
1134
1135 static struct memory_packet_config memory_read_packet_config =
1136 {
1137   "memory-read-packet-size",
1138 };
1139
1140 static void
1141 set_memory_read_packet_size (char *args, int from_tty)
1142 {
1143   set_memory_packet_size (args, &memory_read_packet_config);
1144 }
1145
1146 static void
1147 show_memory_read_packet_size (char *args, int from_tty)
1148 {
1149   show_memory_packet_size (&memory_read_packet_config);
1150 }
1151
1152 static long
1153 get_memory_read_packet_size (void)
1154 {
1155   long size = get_memory_packet_size (&memory_read_packet_config);
1156
1157   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1158      extra buffer size argument before the memory read size can be
1159      increased beyond this.  */
1160   if (size > get_remote_packet_size ())
1161     size = get_remote_packet_size ();
1162   return size;
1163 }
1164
1165 \f
1166 /* Generic configuration support for packets the stub optionally
1167    supports.  Allows the user to specify the use of the packet as well
1168    as allowing GDB to auto-detect support in the remote stub.  */
1169
1170 enum packet_support
1171   {
1172     PACKET_SUPPORT_UNKNOWN = 0,
1173     PACKET_ENABLE,
1174     PACKET_DISABLE
1175   };
1176
1177 struct packet_config
1178   {
1179     const char *name;
1180     const char *title;
1181
1182     /* If auto, GDB auto-detects support for this packet or feature,
1183        either through qSupported, or by trying the packet and looking
1184        at the response.  If true, GDB assumes the target supports this
1185        packet.  If false, the packet is disabled.  Configs that don't
1186        have an associated command always have this set to auto.  */
1187     enum auto_boolean detect;
1188
1189     /* Does the target support this packet?  */
1190     enum packet_support support;
1191   };
1192
1193 /* Analyze a packet's return value and update the packet config
1194    accordingly.  */
1195
1196 enum packet_result
1197 {
1198   PACKET_ERROR,
1199   PACKET_OK,
1200   PACKET_UNKNOWN
1201 };
1202
1203 static enum packet_support packet_config_support (struct packet_config *config);
1204 static enum packet_support packet_support (int packet);
1205
1206 static void
1207 show_packet_config_cmd (struct packet_config *config)
1208 {
1209   char *support = "internal-error";
1210
1211   switch (packet_config_support (config))
1212     {
1213     case PACKET_ENABLE:
1214       support = "enabled";
1215       break;
1216     case PACKET_DISABLE:
1217       support = "disabled";
1218       break;
1219     case PACKET_SUPPORT_UNKNOWN:
1220       support = "unknown";
1221       break;
1222     }
1223   switch (config->detect)
1224     {
1225     case AUTO_BOOLEAN_AUTO:
1226       printf_filtered (_("Support for the `%s' packet "
1227                          "is auto-detected, currently %s.\n"),
1228                        config->name, support);
1229       break;
1230     case AUTO_BOOLEAN_TRUE:
1231     case AUTO_BOOLEAN_FALSE:
1232       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1233                        config->name, support);
1234       break;
1235     }
1236 }
1237
1238 static void
1239 add_packet_config_cmd (struct packet_config *config, const char *name,
1240                        const char *title, int legacy)
1241 {
1242   char *set_doc;
1243   char *show_doc;
1244   char *cmd_name;
1245
1246   config->name = name;
1247   config->title = title;
1248   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1249                         name, title);
1250   show_doc = xstrprintf ("Show current use of remote "
1251                          "protocol `%s' (%s) packet",
1252                          name, title);
1253   /* set/show TITLE-packet {auto,on,off} */
1254   cmd_name = xstrprintf ("%s-packet", title);
1255   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1256                                 &config->detect, set_doc,
1257                                 show_doc, NULL, /* help_doc */
1258                                 NULL,
1259                                 show_remote_protocol_packet_cmd,
1260                                 &remote_set_cmdlist, &remote_show_cmdlist);
1261   /* The command code copies the documentation strings.  */
1262   xfree (set_doc);
1263   xfree (show_doc);
1264   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1265   if (legacy)
1266     {
1267       char *legacy_name;
1268
1269       legacy_name = xstrprintf ("%s-packet", name);
1270       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1271                      &remote_set_cmdlist);
1272       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1273                      &remote_show_cmdlist);
1274     }
1275 }
1276
1277 static enum packet_result
1278 packet_check_result (const char *buf)
1279 {
1280   if (buf[0] != '\0')
1281     {
1282       /* The stub recognized the packet request.  Check that the
1283          operation succeeded.  */
1284       if (buf[0] == 'E'
1285           && isxdigit (buf[1]) && isxdigit (buf[2])
1286           && buf[3] == '\0')
1287         /* "Enn"  - definitly an error.  */
1288         return PACKET_ERROR;
1289
1290       /* Always treat "E." as an error.  This will be used for
1291          more verbose error messages, such as E.memtypes.  */
1292       if (buf[0] == 'E' && buf[1] == '.')
1293         return PACKET_ERROR;
1294
1295       /* The packet may or may not be OK.  Just assume it is.  */
1296       return PACKET_OK;
1297     }
1298   else
1299     /* The stub does not support the packet.  */
1300     return PACKET_UNKNOWN;
1301 }
1302
1303 static enum packet_result
1304 packet_ok (const char *buf, struct packet_config *config)
1305 {
1306   enum packet_result result;
1307
1308   if (config->detect != AUTO_BOOLEAN_TRUE
1309       && config->support == PACKET_DISABLE)
1310     internal_error (__FILE__, __LINE__,
1311                     _("packet_ok: attempt to use a disabled packet"));
1312
1313   result = packet_check_result (buf);
1314   switch (result)
1315     {
1316     case PACKET_OK:
1317     case PACKET_ERROR:
1318       /* The stub recognized the packet request.  */
1319       if (config->support == PACKET_SUPPORT_UNKNOWN)
1320         {
1321           if (remote_debug)
1322             fprintf_unfiltered (gdb_stdlog,
1323                                 "Packet %s (%s) is supported\n",
1324                                 config->name, config->title);
1325           config->support = PACKET_ENABLE;
1326         }
1327       break;
1328     case PACKET_UNKNOWN:
1329       /* The stub does not support the packet.  */
1330       if (config->detect == AUTO_BOOLEAN_AUTO
1331           && config->support == PACKET_ENABLE)
1332         {
1333           /* If the stub previously indicated that the packet was
1334              supported then there is a protocol error.  */
1335           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1336                  config->name, config->title);
1337         }
1338       else if (config->detect == AUTO_BOOLEAN_TRUE)
1339         {
1340           /* The user set it wrong.  */
1341           error (_("Enabled packet %s (%s) not recognized by stub"),
1342                  config->name, config->title);
1343         }
1344
1345       if (remote_debug)
1346         fprintf_unfiltered (gdb_stdlog,
1347                             "Packet %s (%s) is NOT supported\n",
1348                             config->name, config->title);
1349       config->support = PACKET_DISABLE;
1350       break;
1351     }
1352
1353   return result;
1354 }
1355
1356 enum {
1357   PACKET_vCont = 0,
1358   PACKET_X,
1359   PACKET_qSymbol,
1360   PACKET_P,
1361   PACKET_p,
1362   PACKET_Z0,
1363   PACKET_Z1,
1364   PACKET_Z2,
1365   PACKET_Z3,
1366   PACKET_Z4,
1367   PACKET_vFile_setfs,
1368   PACKET_vFile_open,
1369   PACKET_vFile_pread,
1370   PACKET_vFile_pwrite,
1371   PACKET_vFile_close,
1372   PACKET_vFile_unlink,
1373   PACKET_vFile_readlink,
1374   PACKET_vFile_fstat,
1375   PACKET_qXfer_auxv,
1376   PACKET_qXfer_features,
1377   PACKET_qXfer_exec_file,
1378   PACKET_qXfer_libraries,
1379   PACKET_qXfer_libraries_svr4,
1380   PACKET_qXfer_memory_map,
1381   PACKET_qXfer_spu_read,
1382   PACKET_qXfer_spu_write,
1383   PACKET_qXfer_osdata,
1384   PACKET_qXfer_threads,
1385   PACKET_qXfer_statictrace_read,
1386   PACKET_qXfer_traceframe_info,
1387   PACKET_qXfer_uib,
1388   PACKET_qGetTIBAddr,
1389   PACKET_qGetTLSAddr,
1390   PACKET_qSupported,
1391   PACKET_qTStatus,
1392   PACKET_QPassSignals,
1393   PACKET_QProgramSignals,
1394   PACKET_qCRC,
1395   PACKET_qSearch_memory,
1396   PACKET_vAttach,
1397   PACKET_vRun,
1398   PACKET_QStartNoAckMode,
1399   PACKET_vKill,
1400   PACKET_qXfer_siginfo_read,
1401   PACKET_qXfer_siginfo_write,
1402   PACKET_qAttached,
1403
1404   /* Support for conditional tracepoints.  */
1405   PACKET_ConditionalTracepoints,
1406
1407   /* Support for target-side breakpoint conditions.  */
1408   PACKET_ConditionalBreakpoints,
1409
1410   /* Support for target-side breakpoint commands.  */
1411   PACKET_BreakpointCommands,
1412
1413   /* Support for fast tracepoints.  */
1414   PACKET_FastTracepoints,
1415
1416   /* Support for static tracepoints.  */
1417   PACKET_StaticTracepoints,
1418
1419   /* Support for installing tracepoints while a trace experiment is
1420      running.  */
1421   PACKET_InstallInTrace,
1422
1423   PACKET_bc,
1424   PACKET_bs,
1425   PACKET_TracepointSource,
1426   PACKET_QAllow,
1427   PACKET_qXfer_fdpic,
1428   PACKET_QDisableRandomization,
1429   PACKET_QAgent,
1430   PACKET_QTBuffer_size,
1431   PACKET_Qbtrace_off,
1432   PACKET_Qbtrace_bts,
1433   PACKET_Qbtrace_pt,
1434   PACKET_qXfer_btrace,
1435
1436   /* Support for the QNonStop packet.  */
1437   PACKET_QNonStop,
1438
1439   /* Support for multi-process extensions.  */
1440   PACKET_multiprocess_feature,
1441
1442   /* Support for enabling and disabling tracepoints while a trace
1443      experiment is running.  */
1444   PACKET_EnableDisableTracepoints_feature,
1445
1446   /* Support for collecting strings using the tracenz bytecode.  */
1447   PACKET_tracenz_feature,
1448
1449   /* Support for continuing to run a trace experiment while GDB is
1450      disconnected.  */
1451   PACKET_DisconnectedTracing_feature,
1452
1453   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1454   PACKET_augmented_libraries_svr4_read_feature,
1455
1456   /* Support for the qXfer:btrace-conf:read packet.  */
1457   PACKET_qXfer_btrace_conf,
1458
1459   /* Support for the Qbtrace-conf:bts:size packet.  */
1460   PACKET_Qbtrace_conf_bts_size,
1461
1462   /* Support for swbreak+ feature.  */
1463   PACKET_swbreak_feature,
1464
1465   /* Support for hwbreak+ feature.  */
1466   PACKET_hwbreak_feature,
1467
1468   /* Support for fork events.  */
1469   PACKET_fork_event_feature,
1470
1471   /* Support for vfork events.  */
1472   PACKET_vfork_event_feature,
1473
1474   /* Support for the Qbtrace-conf:pt:size packet.  */
1475   PACKET_Qbtrace_conf_pt_size,
1476
1477   /* Support for exec events.  */
1478   PACKET_exec_event_feature,
1479
1480   /* Support for query supported vCont actions.  */
1481   PACKET_vContSupported,
1482
1483   PACKET_MAX
1484 };
1485
1486 static struct packet_config remote_protocol_packets[PACKET_MAX];
1487
1488 /* Returns the packet's corresponding "set remote foo-packet" command
1489    state.  See struct packet_config for more details.  */
1490
1491 static enum auto_boolean
1492 packet_set_cmd_state (int packet)
1493 {
1494   return remote_protocol_packets[packet].detect;
1495 }
1496
1497 /* Returns whether a given packet or feature is supported.  This takes
1498    into account the state of the corresponding "set remote foo-packet"
1499    command, which may be used to bypass auto-detection.  */
1500
1501 static enum packet_support
1502 packet_config_support (struct packet_config *config)
1503 {
1504   switch (config->detect)
1505     {
1506     case AUTO_BOOLEAN_TRUE:
1507       return PACKET_ENABLE;
1508     case AUTO_BOOLEAN_FALSE:
1509       return PACKET_DISABLE;
1510     case AUTO_BOOLEAN_AUTO:
1511       return config->support;
1512     default:
1513       gdb_assert_not_reached (_("bad switch"));
1514     }
1515 }
1516
1517 /* Same as packet_config_support, but takes the packet's enum value as
1518    argument.  */
1519
1520 static enum packet_support
1521 packet_support (int packet)
1522 {
1523   struct packet_config *config = &remote_protocol_packets[packet];
1524
1525   return packet_config_support (config);
1526 }
1527
1528 static void
1529 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1530                                  struct cmd_list_element *c,
1531                                  const char *value)
1532 {
1533   struct packet_config *packet;
1534
1535   for (packet = remote_protocol_packets;
1536        packet < &remote_protocol_packets[PACKET_MAX];
1537        packet++)
1538     {
1539       if (&packet->detect == c->var)
1540         {
1541           show_packet_config_cmd (packet);
1542           return;
1543         }
1544     }
1545   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1546                   c->name);
1547 }
1548
1549 /* Should we try one of the 'Z' requests?  */
1550
1551 enum Z_packet_type
1552 {
1553   Z_PACKET_SOFTWARE_BP,
1554   Z_PACKET_HARDWARE_BP,
1555   Z_PACKET_WRITE_WP,
1556   Z_PACKET_READ_WP,
1557   Z_PACKET_ACCESS_WP,
1558   NR_Z_PACKET_TYPES
1559 };
1560
1561 /* For compatibility with older distributions.  Provide a ``set remote
1562    Z-packet ...'' command that updates all the Z packet types.  */
1563
1564 static enum auto_boolean remote_Z_packet_detect;
1565
1566 static void
1567 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1568                                   struct cmd_list_element *c)
1569 {
1570   int i;
1571
1572   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1573     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1574 }
1575
1576 static void
1577 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1578                                    struct cmd_list_element *c,
1579                                    const char *value)
1580 {
1581   int i;
1582
1583   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1584     {
1585       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1586     }
1587 }
1588
1589 /* Returns true if the multi-process extensions are in effect.  */
1590
1591 static int
1592 remote_multi_process_p (struct remote_state *rs)
1593 {
1594   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1595 }
1596
1597 /* Returns true if fork events are supported.  */
1598
1599 static int
1600 remote_fork_event_p (struct remote_state *rs)
1601 {
1602   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1603 }
1604
1605 /* Returns true if vfork events are supported.  */
1606
1607 static int
1608 remote_vfork_event_p (struct remote_state *rs)
1609 {
1610   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1611 }
1612
1613 /* Returns true if exec events are supported.  */
1614
1615 static int
1616 remote_exec_event_p (struct remote_state *rs)
1617 {
1618   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1619 }
1620
1621 /* Insert fork catchpoint target routine.  If fork events are enabled
1622    then return success, nothing more to do.  */
1623
1624 static int
1625 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1626 {
1627   struct remote_state *rs = get_remote_state ();
1628
1629   return !remote_fork_event_p (rs);
1630 }
1631
1632 /* Remove fork catchpoint target routine.  Nothing to do, just
1633    return success.  */
1634
1635 static int
1636 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1637 {
1638   return 0;
1639 }
1640
1641 /* Insert vfork catchpoint target routine.  If vfork events are enabled
1642    then return success, nothing more to do.  */
1643
1644 static int
1645 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1646 {
1647   struct remote_state *rs = get_remote_state ();
1648
1649   return !remote_vfork_event_p (rs);
1650 }
1651
1652 /* Remove vfork catchpoint target routine.  Nothing to do, just
1653    return success.  */
1654
1655 static int
1656 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1657 {
1658   return 0;
1659 }
1660
1661 /* Insert exec catchpoint target routine.  If exec events are
1662    enabled, just return success.  */
1663
1664 static int
1665 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1666 {
1667   struct remote_state *rs = get_remote_state ();
1668
1669   return !remote_exec_event_p (rs);
1670 }
1671
1672 /* Remove exec catchpoint target routine.  Nothing to do, just
1673    return success.  */
1674
1675 static int
1676 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1677 {
1678   return 0;
1679 }
1680
1681 /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
1682 static struct async_signal_handler *async_sigint_remote_twice_token;
1683 static struct async_signal_handler *async_sigint_remote_token;
1684
1685 \f
1686 /* Asynchronous signal handle registered as event loop source for
1687    when we have pending events ready to be passed to the core.  */
1688
1689 static struct async_event_handler *remote_async_inferior_event_token;
1690
1691 \f
1692
1693 static ptid_t magic_null_ptid;
1694 static ptid_t not_sent_ptid;
1695 static ptid_t any_thread_ptid;
1696
1697 /* Find out if the stub attached to PID (and hence GDB should offer to
1698    detach instead of killing it when bailing out).  */
1699
1700 static int
1701 remote_query_attached (int pid)
1702 {
1703   struct remote_state *rs = get_remote_state ();
1704   size_t size = get_remote_packet_size ();
1705
1706   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1707     return 0;
1708
1709   if (remote_multi_process_p (rs))
1710     xsnprintf (rs->buf, size, "qAttached:%x", pid);
1711   else
1712     xsnprintf (rs->buf, size, "qAttached");
1713
1714   putpkt (rs->buf);
1715   getpkt (&rs->buf, &rs->buf_size, 0);
1716
1717   switch (packet_ok (rs->buf,
1718                      &remote_protocol_packets[PACKET_qAttached]))
1719     {
1720     case PACKET_OK:
1721       if (strcmp (rs->buf, "1") == 0)
1722         return 1;
1723       break;
1724     case PACKET_ERROR:
1725       warning (_("Remote failure reply: %s"), rs->buf);
1726       break;
1727     case PACKET_UNKNOWN:
1728       break;
1729     }
1730
1731   return 0;
1732 }
1733
1734 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
1735    has been invented by GDB, instead of reported by the target.  Since
1736    we can be connected to a remote system before before knowing about
1737    any inferior, mark the target with execution when we find the first
1738    inferior.  If ATTACHED is 1, then we had just attached to this
1739    inferior.  If it is 0, then we just created this inferior.  If it
1740    is -1, then try querying the remote stub to find out if it had
1741    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
1742    attempt to open this inferior's executable as the main executable
1743    if no main executable is open already.  */
1744
1745 static struct inferior *
1746 remote_add_inferior (int fake_pid_p, int pid, int attached,
1747                      int try_open_exec)
1748 {
1749   struct inferior *inf;
1750
1751   /* Check whether this process we're learning about is to be
1752      considered attached, or if is to be considered to have been
1753      spawned by the stub.  */
1754   if (attached == -1)
1755     attached = remote_query_attached (pid);
1756
1757   if (gdbarch_has_global_solist (target_gdbarch ()))
1758     {
1759       /* If the target shares code across all inferiors, then every
1760          attach adds a new inferior.  */
1761       inf = add_inferior (pid);
1762
1763       /* ... and every inferior is bound to the same program space.
1764          However, each inferior may still have its own address
1765          space.  */
1766       inf->aspace = maybe_new_address_space ();
1767       inf->pspace = current_program_space;
1768     }
1769   else
1770     {
1771       /* In the traditional debugging scenario, there's a 1-1 match
1772          between program/address spaces.  We simply bind the inferior
1773          to the program space's address space.  */
1774       inf = current_inferior ();
1775       inferior_appeared (inf, pid);
1776     }
1777
1778   inf->attach_flag = attached;
1779   inf->fake_pid_p = fake_pid_p;
1780
1781   /* If no main executable is currently open then attempt to
1782      open the file that was executed to create this inferior.  */
1783   if (try_open_exec && get_exec_file (0) == NULL)
1784     exec_file_locate_attach (pid, 1);
1785
1786   return inf;
1787 }
1788
1789 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1790    according to RUNNING.  */
1791
1792 static void
1793 remote_add_thread (ptid_t ptid, int running)
1794 {
1795   struct remote_state *rs = get_remote_state ();
1796
1797   /* GDB historically didn't pull threads in the initial connection
1798      setup.  If the remote target doesn't even have a concept of
1799      threads (e.g., a bare-metal target), even if internally we
1800      consider that a single-threaded target, mentioning a new thread
1801      might be confusing to the user.  Be silent then, preserving the
1802      age old behavior.  */
1803   if (rs->starting_up)
1804     add_thread_silent (ptid);
1805   else
1806     add_thread (ptid);
1807
1808   set_executing (ptid, running);
1809   set_running (ptid, running);
1810 }
1811
1812 /* Come here when we learn about a thread id from the remote target.
1813    It may be the first time we hear about such thread, so take the
1814    opportunity to add it to GDB's thread list.  In case this is the
1815    first time we're noticing its corresponding inferior, add it to
1816    GDB's inferior list as well.  */
1817
1818 static void
1819 remote_notice_new_inferior (ptid_t currthread, int running)
1820 {
1821   /* If this is a new thread, add it to GDB's thread list.
1822      If we leave it up to WFI to do this, bad things will happen.  */
1823
1824   if (in_thread_list (currthread) && is_exited (currthread))
1825     {
1826       /* We're seeing an event on a thread id we knew had exited.
1827          This has to be a new thread reusing the old id.  Add it.  */
1828       remote_add_thread (currthread, running);
1829       return;
1830     }
1831
1832   if (!in_thread_list (currthread))
1833     {
1834       struct inferior *inf = NULL;
1835       int pid = ptid_get_pid (currthread);
1836
1837       if (ptid_is_pid (inferior_ptid)
1838           && pid == ptid_get_pid (inferior_ptid))
1839         {
1840           /* inferior_ptid has no thread member yet.  This can happen
1841              with the vAttach -> remote_wait,"TAAthread:" path if the
1842              stub doesn't support qC.  This is the first stop reported
1843              after an attach, so this is the main thread.  Update the
1844              ptid in the thread list.  */
1845           if (in_thread_list (pid_to_ptid (pid)))
1846             thread_change_ptid (inferior_ptid, currthread);
1847           else
1848             {
1849               remote_add_thread (currthread, running);
1850               inferior_ptid = currthread;
1851             }
1852           return;
1853         }
1854
1855       if (ptid_equal (magic_null_ptid, inferior_ptid))
1856         {
1857           /* inferior_ptid is not set yet.  This can happen with the
1858              vRun -> remote_wait,"TAAthread:" path if the stub
1859              doesn't support qC.  This is the first stop reported
1860              after an attach, so this is the main thread.  Update the
1861              ptid in the thread list.  */
1862           thread_change_ptid (inferior_ptid, currthread);
1863           return;
1864         }
1865
1866       /* When connecting to a target remote, or to a target
1867          extended-remote which already was debugging an inferior, we
1868          may not know about it yet.  Add it before adding its child
1869          thread, so notifications are emitted in a sensible order.  */
1870       if (!in_inferior_list (ptid_get_pid (currthread)))
1871         {
1872           struct remote_state *rs = get_remote_state ();
1873           int fake_pid_p = !remote_multi_process_p (rs);
1874
1875           inf = remote_add_inferior (fake_pid_p,
1876                                      ptid_get_pid (currthread), -1, 1);
1877         }
1878
1879       /* This is really a new thread.  Add it.  */
1880       remote_add_thread (currthread, running);
1881
1882       /* If we found a new inferior, let the common code do whatever
1883          it needs to with it (e.g., read shared libraries, insert
1884          breakpoints), unless we're just setting up an all-stop
1885          connection.  */
1886       if (inf != NULL)
1887         {
1888           struct remote_state *rs = get_remote_state ();
1889
1890           if (non_stop || !rs->starting_up)
1891             notice_new_inferior (currthread, running, 0);
1892         }
1893     }
1894 }
1895
1896 /* Return the private thread data, creating it if necessary.  */
1897
1898 static struct private_thread_info *
1899 demand_private_info (ptid_t ptid)
1900 {
1901   struct thread_info *info = find_thread_ptid (ptid);
1902
1903   gdb_assert (info);
1904
1905   if (!info->priv)
1906     {
1907       info->priv = XNEW (struct private_thread_info);
1908       info->private_dtor = free_private_thread_info;
1909       info->priv->core = -1;
1910       info->priv->extra = 0;
1911     }
1912
1913   return info->priv;
1914 }
1915
1916 /* Call this function as a result of
1917    1) A halt indication (T packet) containing a thread id
1918    2) A direct query of currthread
1919    3) Successful execution of set thread */
1920
1921 static void
1922 record_currthread (struct remote_state *rs, ptid_t currthread)
1923 {
1924   rs->general_thread = currthread;
1925 }
1926
1927 /* If 'QPassSignals' is supported, tell the remote stub what signals
1928    it can simply pass through to the inferior without reporting.  */
1929
1930 static void
1931 remote_pass_signals (struct target_ops *self,
1932                      int numsigs, unsigned char *pass_signals)
1933 {
1934   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1935     {
1936       char *pass_packet, *p;
1937       int count = 0, i;
1938       struct remote_state *rs = get_remote_state ();
1939
1940       gdb_assert (numsigs < 256);
1941       for (i = 0; i < numsigs; i++)
1942         {
1943           if (pass_signals[i])
1944             count++;
1945         }
1946       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1947       strcpy (pass_packet, "QPassSignals:");
1948       p = pass_packet + strlen (pass_packet);
1949       for (i = 0; i < numsigs; i++)
1950         {
1951           if (pass_signals[i])
1952             {
1953               if (i >= 16)
1954                 *p++ = tohex (i >> 4);
1955               *p++ = tohex (i & 15);
1956               if (count)
1957                 *p++ = ';';
1958               else
1959                 break;
1960               count--;
1961             }
1962         }
1963       *p = 0;
1964       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1965         {
1966           putpkt (pass_packet);
1967           getpkt (&rs->buf, &rs->buf_size, 0);
1968           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1969           if (rs->last_pass_packet)
1970             xfree (rs->last_pass_packet);
1971           rs->last_pass_packet = pass_packet;
1972         }
1973       else
1974         xfree (pass_packet);
1975     }
1976 }
1977
1978 /* If 'QProgramSignals' is supported, tell the remote stub what
1979    signals it should pass through to the inferior when detaching.  */
1980
1981 static void
1982 remote_program_signals (struct target_ops *self,
1983                         int numsigs, unsigned char *signals)
1984 {
1985   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1986     {
1987       char *packet, *p;
1988       int count = 0, i;
1989       struct remote_state *rs = get_remote_state ();
1990
1991       gdb_assert (numsigs < 256);
1992       for (i = 0; i < numsigs; i++)
1993         {
1994           if (signals[i])
1995             count++;
1996         }
1997       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1998       strcpy (packet, "QProgramSignals:");
1999       p = packet + strlen (packet);
2000       for (i = 0; i < numsigs; i++)
2001         {
2002           if (signal_pass_state (i))
2003             {
2004               if (i >= 16)
2005                 *p++ = tohex (i >> 4);
2006               *p++ = tohex (i & 15);
2007               if (count)
2008                 *p++ = ';';
2009               else
2010                 break;
2011               count--;
2012             }
2013         }
2014       *p = 0;
2015       if (!rs->last_program_signals_packet
2016           || strcmp (rs->last_program_signals_packet, packet) != 0)
2017         {
2018           putpkt (packet);
2019           getpkt (&rs->buf, &rs->buf_size, 0);
2020           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2021           xfree (rs->last_program_signals_packet);
2022           rs->last_program_signals_packet = packet;
2023         }
2024       else
2025         xfree (packet);
2026     }
2027 }
2028
2029 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2030    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2031    thread.  If GEN is set, set the general thread, if not, then set
2032    the step/continue thread.  */
2033 static void
2034 set_thread (struct ptid ptid, int gen)
2035 {
2036   struct remote_state *rs = get_remote_state ();
2037   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2038   char *buf = rs->buf;
2039   char *endbuf = rs->buf + get_remote_packet_size ();
2040
2041   if (ptid_equal (state, ptid))
2042     return;
2043
2044   *buf++ = 'H';
2045   *buf++ = gen ? 'g' : 'c';
2046   if (ptid_equal (ptid, magic_null_ptid))
2047     xsnprintf (buf, endbuf - buf, "0");
2048   else if (ptid_equal (ptid, any_thread_ptid))
2049     xsnprintf (buf, endbuf - buf, "0");
2050   else if (ptid_equal (ptid, minus_one_ptid))
2051     xsnprintf (buf, endbuf - buf, "-1");
2052   else
2053     write_ptid (buf, endbuf, ptid);
2054   putpkt (rs->buf);
2055   getpkt (&rs->buf, &rs->buf_size, 0);
2056   if (gen)
2057     rs->general_thread = ptid;
2058   else
2059     rs->continue_thread = ptid;
2060 }
2061
2062 static void
2063 set_general_thread (struct ptid ptid)
2064 {
2065   set_thread (ptid, 1);
2066 }
2067
2068 static void
2069 set_continue_thread (struct ptid ptid)
2070 {
2071   set_thread (ptid, 0);
2072 }
2073
2074 /* Change the remote current process.  Which thread within the process
2075    ends up selected isn't important, as long as it is the same process
2076    as what INFERIOR_PTID points to.
2077
2078    This comes from that fact that there is no explicit notion of
2079    "selected process" in the protocol.  The selected process for
2080    general operations is the process the selected general thread
2081    belongs to.  */
2082
2083 static void
2084 set_general_process (void)
2085 {
2086   struct remote_state *rs = get_remote_state ();
2087
2088   /* If the remote can't handle multiple processes, don't bother.  */
2089   if (!rs->extended || !remote_multi_process_p (rs))
2090     return;
2091
2092   /* We only need to change the remote current thread if it's pointing
2093      at some other process.  */
2094   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2095     set_general_thread (inferior_ptid);
2096 }
2097
2098 \f
2099 /* Return nonzero if this is the main thread that we made up ourselves
2100    to model non-threaded targets as single-threaded.  */
2101
2102 static int
2103 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2104 {
2105   struct remote_state *rs = get_remote_state ();
2106   char *p, *endp;
2107
2108   if (ptid_equal (ptid, magic_null_ptid))
2109     /* The main thread is always alive.  */
2110     return 1;
2111
2112   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2113     /* The main thread is always alive.  This can happen after a
2114        vAttach, if the remote side doesn't support
2115        multi-threading.  */
2116     return 1;
2117
2118   return 0;
2119 }
2120
2121 /* Return nonzero if the thread PTID is still alive on the remote
2122    system.  */
2123
2124 static int
2125 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2126 {
2127   struct remote_state *rs = get_remote_state ();
2128   char *p, *endp;
2129
2130   /* Check if this is a thread that we made up ourselves to model
2131      non-threaded targets as single-threaded.  */
2132   if (remote_thread_always_alive (ops, ptid))
2133     return 1;
2134
2135   p = rs->buf;
2136   endp = rs->buf + get_remote_packet_size ();
2137
2138   *p++ = 'T';
2139   write_ptid (p, endp, ptid);
2140
2141   putpkt (rs->buf);
2142   getpkt (&rs->buf, &rs->buf_size, 0);
2143   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2144 }
2145
2146 /* Return a pointer to a thread name if we know it and NULL otherwise.
2147    The thread_info object owns the memory for the name.  */
2148
2149 static const char *
2150 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2151 {
2152   if (info->priv != NULL)
2153     return info->priv->name;
2154
2155   return NULL;
2156 }
2157
2158 /* About these extended threadlist and threadinfo packets.  They are
2159    variable length packets but, the fields within them are often fixed
2160    length.  They are redundent enough to send over UDP as is the
2161    remote protocol in general.  There is a matching unit test module
2162    in libstub.  */
2163
2164 /* WARNING: This threadref data structure comes from the remote O.S.,
2165    libstub protocol encoding, and remote.c.  It is not particularly
2166    changable.  */
2167
2168 /* Right now, the internal structure is int. We want it to be bigger.
2169    Plan to fix this.  */
2170
2171 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2172
2173 /* gdb_ext_thread_info is an internal GDB data structure which is
2174    equivalent to the reply of the remote threadinfo packet.  */
2175
2176 struct gdb_ext_thread_info
2177   {
2178     threadref threadid;         /* External form of thread reference.  */
2179     int active;                 /* Has state interesting to GDB?
2180                                    regs, stack.  */
2181     char display[256];          /* Brief state display, name,
2182                                    blocked/suspended.  */
2183     char shortname[32];         /* To be used to name threads.  */
2184     char more_display[256];     /* Long info, statistics, queue depth,
2185                                    whatever.  */
2186   };
2187
2188 /* The volume of remote transfers can be limited by submitting
2189    a mask containing bits specifying the desired information.
2190    Use a union of these values as the 'selection' parameter to
2191    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2192
2193 #define TAG_THREADID 1
2194 #define TAG_EXISTS 2
2195 #define TAG_DISPLAY 4
2196 #define TAG_THREADNAME 8
2197 #define TAG_MOREDISPLAY 16
2198
2199 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2200
2201 static char *unpack_nibble (char *buf, int *val);
2202
2203 static char *unpack_byte (char *buf, int *value);
2204
2205 static char *pack_int (char *buf, int value);
2206
2207 static char *unpack_int (char *buf, int *value);
2208
2209 static char *unpack_string (char *src, char *dest, int length);
2210
2211 static char *pack_threadid (char *pkt, threadref *id);
2212
2213 static char *unpack_threadid (char *inbuf, threadref *id);
2214
2215 void int_to_threadref (threadref *id, int value);
2216
2217 static int threadref_to_int (threadref *ref);
2218
2219 static void copy_threadref (threadref *dest, threadref *src);
2220
2221 static int threadmatch (threadref *dest, threadref *src);
2222
2223 static char *pack_threadinfo_request (char *pkt, int mode,
2224                                       threadref *id);
2225
2226 static int remote_unpack_thread_info_response (char *pkt,
2227                                                threadref *expectedref,
2228                                                struct gdb_ext_thread_info
2229                                                *info);
2230
2231
2232 static int remote_get_threadinfo (threadref *threadid,
2233                                   int fieldset, /*TAG mask */
2234                                   struct gdb_ext_thread_info *info);
2235
2236 static char *pack_threadlist_request (char *pkt, int startflag,
2237                                       int threadcount,
2238                                       threadref *nextthread);
2239
2240 static int parse_threadlist_response (char *pkt,
2241                                       int result_limit,
2242                                       threadref *original_echo,
2243                                       threadref *resultlist,
2244                                       int *doneflag);
2245
2246 static int remote_get_threadlist (int startflag,
2247                                   threadref *nextthread,
2248                                   int result_limit,
2249                                   int *done,
2250                                   int *result_count,
2251                                   threadref *threadlist);
2252
2253 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2254
2255 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2256                                        void *context, int looplimit);
2257
2258 static int remote_newthread_step (threadref *ref, void *context);
2259
2260
2261 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2262    buffer we're allowed to write to.  Returns
2263    BUF+CHARACTERS_WRITTEN.  */
2264
2265 static char *
2266 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2267 {
2268   int pid, tid;
2269   struct remote_state *rs = get_remote_state ();
2270
2271   if (remote_multi_process_p (rs))
2272     {
2273       pid = ptid_get_pid (ptid);
2274       if (pid < 0)
2275         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2276       else
2277         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2278     }
2279   tid = ptid_get_lwp (ptid);
2280   if (tid < 0)
2281     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2282   else
2283     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2284
2285   return buf;
2286 }
2287
2288 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
2289    passed the last parsed char.  Returns null_ptid on error.  */
2290
2291 static ptid_t
2292 read_ptid (char *buf, char **obuf)
2293 {
2294   char *p = buf;
2295   char *pp;
2296   ULONGEST pid = 0, tid = 0;
2297
2298   if (*p == 'p')
2299     {
2300       /* Multi-process ptid.  */
2301       pp = unpack_varlen_hex (p + 1, &pid);
2302       if (*pp != '.')
2303         error (_("invalid remote ptid: %s"), p);
2304
2305       p = pp;
2306       pp = unpack_varlen_hex (p + 1, &tid);
2307       if (obuf)
2308         *obuf = pp;
2309       return ptid_build (pid, tid, 0);
2310     }
2311
2312   /* No multi-process.  Just a tid.  */
2313   pp = unpack_varlen_hex (p, &tid);
2314
2315   /* Return null_ptid when no thread id is found.  */
2316   if (p == pp)
2317     {
2318       if (obuf)
2319         *obuf = pp;
2320       return null_ptid;
2321     }
2322
2323   /* Since the stub is not sending a process id, then default to
2324      what's in inferior_ptid, unless it's null at this point.  If so,
2325      then since there's no way to know the pid of the reported
2326      threads, use the magic number.  */
2327   if (ptid_equal (inferior_ptid, null_ptid))
2328     pid = ptid_get_pid (magic_null_ptid);
2329   else
2330     pid = ptid_get_pid (inferior_ptid);
2331
2332   if (obuf)
2333     *obuf = pp;
2334   return ptid_build (pid, tid, 0);
2335 }
2336
2337 static int
2338 stubhex (int ch)
2339 {
2340   if (ch >= 'a' && ch <= 'f')
2341     return ch - 'a' + 10;
2342   if (ch >= '0' && ch <= '9')
2343     return ch - '0';
2344   if (ch >= 'A' && ch <= 'F')
2345     return ch - 'A' + 10;
2346   return -1;
2347 }
2348
2349 static int
2350 stub_unpack_int (char *buff, int fieldlength)
2351 {
2352   int nibble;
2353   int retval = 0;
2354
2355   while (fieldlength)
2356     {
2357       nibble = stubhex (*buff++);
2358       retval |= nibble;
2359       fieldlength--;
2360       if (fieldlength)
2361         retval = retval << 4;
2362     }
2363   return retval;
2364 }
2365
2366 static char *
2367 unpack_nibble (char *buf, int *val)
2368 {
2369   *val = fromhex (*buf++);
2370   return buf;
2371 }
2372
2373 static char *
2374 unpack_byte (char *buf, int *value)
2375 {
2376   *value = stub_unpack_int (buf, 2);
2377   return buf + 2;
2378 }
2379
2380 static char *
2381 pack_int (char *buf, int value)
2382 {
2383   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2384   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2385   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2386   buf = pack_hex_byte (buf, (value & 0xff));
2387   return buf;
2388 }
2389
2390 static char *
2391 unpack_int (char *buf, int *value)
2392 {
2393   *value = stub_unpack_int (buf, 8);
2394   return buf + 8;
2395 }
2396
2397 #if 0                   /* Currently unused, uncomment when needed.  */
2398 static char *pack_string (char *pkt, char *string);
2399
2400 static char *
2401 pack_string (char *pkt, char *string)
2402 {
2403   char ch;
2404   int len;
2405
2406   len = strlen (string);
2407   if (len > 200)
2408     len = 200;          /* Bigger than most GDB packets, junk???  */
2409   pkt = pack_hex_byte (pkt, len);
2410   while (len-- > 0)
2411     {
2412       ch = *string++;
2413       if ((ch == '\0') || (ch == '#'))
2414         ch = '*';               /* Protect encapsulation.  */
2415       *pkt++ = ch;
2416     }
2417   return pkt;
2418 }
2419 #endif /* 0 (unused) */
2420
2421 static char *
2422 unpack_string (char *src, char *dest, int length)
2423 {
2424   while (length--)
2425     *dest++ = *src++;
2426   *dest = '\0';
2427   return src;
2428 }
2429
2430 static char *
2431 pack_threadid (char *pkt, threadref *id)
2432 {
2433   char *limit;
2434   unsigned char *altid;
2435
2436   altid = (unsigned char *) id;
2437   limit = pkt + BUF_THREAD_ID_SIZE;
2438   while (pkt < limit)
2439     pkt = pack_hex_byte (pkt, *altid++);
2440   return pkt;
2441 }
2442
2443
2444 static char *
2445 unpack_threadid (char *inbuf, threadref *id)
2446 {
2447   char *altref;
2448   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2449   int x, y;
2450
2451   altref = (char *) id;
2452
2453   while (inbuf < limit)
2454     {
2455       x = stubhex (*inbuf++);
2456       y = stubhex (*inbuf++);
2457       *altref++ = (x << 4) | y;
2458     }
2459   return inbuf;
2460 }
2461
2462 /* Externally, threadrefs are 64 bits but internally, they are still
2463    ints.  This is due to a mismatch of specifications.  We would like
2464    to use 64bit thread references internally.  This is an adapter
2465    function.  */
2466
2467 void
2468 int_to_threadref (threadref *id, int value)
2469 {
2470   unsigned char *scan;
2471
2472   scan = (unsigned char *) id;
2473   {
2474     int i = 4;
2475     while (i--)
2476       *scan++ = 0;
2477   }
2478   *scan++ = (value >> 24) & 0xff;
2479   *scan++ = (value >> 16) & 0xff;
2480   *scan++ = (value >> 8) & 0xff;
2481   *scan++ = (value & 0xff);
2482 }
2483
2484 static int
2485 threadref_to_int (threadref *ref)
2486 {
2487   int i, value = 0;
2488   unsigned char *scan;
2489
2490   scan = *ref;
2491   scan += 4;
2492   i = 4;
2493   while (i-- > 0)
2494     value = (value << 8) | ((*scan++) & 0xff);
2495   return value;
2496 }
2497
2498 static void
2499 copy_threadref (threadref *dest, threadref *src)
2500 {
2501   int i;
2502   unsigned char *csrc, *cdest;
2503
2504   csrc = (unsigned char *) src;
2505   cdest = (unsigned char *) dest;
2506   i = 8;
2507   while (i--)
2508     *cdest++ = *csrc++;
2509 }
2510
2511 static int
2512 threadmatch (threadref *dest, threadref *src)
2513 {
2514   /* Things are broken right now, so just assume we got a match.  */
2515 #if 0
2516   unsigned char *srcp, *destp;
2517   int i, result;
2518   srcp = (char *) src;
2519   destp = (char *) dest;
2520
2521   result = 1;
2522   while (i-- > 0)
2523     result &= (*srcp++ == *destp++) ? 1 : 0;
2524   return result;
2525 #endif
2526   return 1;
2527 }
2528
2529 /*
2530    threadid:1,        # always request threadid
2531    context_exists:2,
2532    display:4,
2533    unique_name:8,
2534    more_display:16
2535  */
2536
2537 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2538
2539 static char *
2540 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2541 {
2542   *pkt++ = 'q';                         /* Info Query */
2543   *pkt++ = 'P';                         /* process or thread info */
2544   pkt = pack_int (pkt, mode);           /* mode */
2545   pkt = pack_threadid (pkt, id);        /* threadid */
2546   *pkt = '\0';                          /* terminate */
2547   return pkt;
2548 }
2549
2550 /* These values tag the fields in a thread info response packet.  */
2551 /* Tagging the fields allows us to request specific fields and to
2552    add more fields as time goes by.  */
2553
2554 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2555 #define TAG_EXISTS 2            /* Is this process defined enough to
2556                                    fetch registers and its stack?  */
2557 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2558 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2559 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2560                                    the process.  */
2561
2562 static int
2563 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2564                                     struct gdb_ext_thread_info *info)
2565 {
2566   struct remote_state *rs = get_remote_state ();
2567   int mask, length;
2568   int tag;
2569   threadref ref;
2570   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2571   int retval = 1;
2572
2573   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2574   info->active = 0;
2575   info->display[0] = '\0';
2576   info->shortname[0] = '\0';
2577   info->more_display[0] = '\0';
2578
2579   /* Assume the characters indicating the packet type have been
2580      stripped.  */
2581   pkt = unpack_int (pkt, &mask);        /* arg mask */
2582   pkt = unpack_threadid (pkt, &ref);
2583
2584   if (mask == 0)
2585     warning (_("Incomplete response to threadinfo request."));
2586   if (!threadmatch (&ref, expectedref))
2587     {                   /* This is an answer to a different request.  */
2588       warning (_("ERROR RMT Thread info mismatch."));
2589       return 0;
2590     }
2591   copy_threadref (&info->threadid, &ref);
2592
2593   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
2594
2595   /* Packets are terminated with nulls.  */
2596   while ((pkt < limit) && mask && *pkt)
2597     {
2598       pkt = unpack_int (pkt, &tag);     /* tag */
2599       pkt = unpack_byte (pkt, &length); /* length */
2600       if (!(tag & mask))                /* Tags out of synch with mask.  */
2601         {
2602           warning (_("ERROR RMT: threadinfo tag mismatch."));
2603           retval = 0;
2604           break;
2605         }
2606       if (tag == TAG_THREADID)
2607         {
2608           if (length != 16)
2609             {
2610               warning (_("ERROR RMT: length of threadid is not 16."));
2611               retval = 0;
2612               break;
2613             }
2614           pkt = unpack_threadid (pkt, &ref);
2615           mask = mask & ~TAG_THREADID;
2616           continue;
2617         }
2618       if (tag == TAG_EXISTS)
2619         {
2620           info->active = stub_unpack_int (pkt, length);
2621           pkt += length;
2622           mask = mask & ~(TAG_EXISTS);
2623           if (length > 8)
2624             {
2625               warning (_("ERROR RMT: 'exists' length too long."));
2626               retval = 0;
2627               break;
2628             }
2629           continue;
2630         }
2631       if (tag == TAG_THREADNAME)
2632         {
2633           pkt = unpack_string (pkt, &info->shortname[0], length);
2634           mask = mask & ~TAG_THREADNAME;
2635           continue;
2636         }
2637       if (tag == TAG_DISPLAY)
2638         {
2639           pkt = unpack_string (pkt, &info->display[0], length);
2640           mask = mask & ~TAG_DISPLAY;
2641           continue;
2642         }
2643       if (tag == TAG_MOREDISPLAY)
2644         {
2645           pkt = unpack_string (pkt, &info->more_display[0], length);
2646           mask = mask & ~TAG_MOREDISPLAY;
2647           continue;
2648         }
2649       warning (_("ERROR RMT: unknown thread info tag."));
2650       break;                    /* Not a tag we know about.  */
2651     }
2652   return retval;
2653 }
2654
2655 static int
2656 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2657                        struct gdb_ext_thread_info *info)
2658 {
2659   struct remote_state *rs = get_remote_state ();
2660   int result;
2661
2662   pack_threadinfo_request (rs->buf, fieldset, threadid);
2663   putpkt (rs->buf);
2664   getpkt (&rs->buf, &rs->buf_size, 0);
2665
2666   if (rs->buf[0] == '\0')
2667     return 0;
2668
2669   result = remote_unpack_thread_info_response (rs->buf + 2,
2670                                                threadid, info);
2671   return result;
2672 }
2673
2674 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2675
2676 static char *
2677 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2678                          threadref *nextthread)
2679 {
2680   *pkt++ = 'q';                 /* info query packet */
2681   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2682   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2683   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2684   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2685   *pkt = '\0';
2686   return pkt;
2687 }
2688
2689 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2690
2691 static int
2692 parse_threadlist_response (char *pkt, int result_limit,
2693                            threadref *original_echo, threadref *resultlist,
2694                            int *doneflag)
2695 {
2696   struct remote_state *rs = get_remote_state ();
2697   char *limit;
2698   int count, resultcount, done;
2699
2700   resultcount = 0;
2701   /* Assume the 'q' and 'M chars have been stripped.  */
2702   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2703   /* done parse past here */
2704   pkt = unpack_byte (pkt, &count);      /* count field */
2705   pkt = unpack_nibble (pkt, &done);
2706   /* The first threadid is the argument threadid.  */
2707   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2708   while ((count-- > 0) && (pkt < limit))
2709     {
2710       pkt = unpack_threadid (pkt, resultlist++);
2711       if (resultcount++ >= result_limit)
2712         break;
2713     }
2714   if (doneflag)
2715     *doneflag = done;
2716   return resultcount;
2717 }
2718
2719 /* Fetch the next batch of threads from the remote.  Returns -1 if the
2720    qL packet is not supported, 0 on error and 1 on success.  */
2721
2722 static int
2723 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2724                        int *done, int *result_count, threadref *threadlist)
2725 {
2726   struct remote_state *rs = get_remote_state ();
2727   int result = 1;
2728
2729   /* Trancate result limit to be smaller than the packet size.  */
2730   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2731       >= get_remote_packet_size ())
2732     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2733
2734   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2735   putpkt (rs->buf);
2736   getpkt (&rs->buf, &rs->buf_size, 0);
2737   if (*rs->buf == '\0')
2738     {
2739       /* Packet not supported.  */
2740       return -1;
2741     }
2742
2743   *result_count =
2744     parse_threadlist_response (rs->buf + 2, result_limit,
2745                                &rs->echo_nextthread, threadlist, done);
2746
2747   if (!threadmatch (&rs->echo_nextthread, nextthread))
2748     {
2749       /* FIXME: This is a good reason to drop the packet.  */
2750       /* Possably, there is a duplicate response.  */
2751       /* Possabilities :
2752          retransmit immediatly - race conditions
2753          retransmit after timeout - yes
2754          exit
2755          wait for packet, then exit
2756        */
2757       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2758       return 0;                 /* I choose simply exiting.  */
2759     }
2760   if (*result_count <= 0)
2761     {
2762       if (*done != 1)
2763         {
2764           warning (_("RMT ERROR : failed to get remote thread list."));
2765           result = 0;
2766         }
2767       return result;            /* break; */
2768     }
2769   if (*result_count > result_limit)
2770     {
2771       *result_count = 0;
2772       warning (_("RMT ERROR: threadlist response longer than requested."));
2773       return 0;
2774     }
2775   return result;
2776 }
2777
2778 /* Fetch the list of remote threads, with the qL packet, and call
2779    STEPFUNCTION for each thread found.  Stops iterating and returns 1
2780    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
2781    STEPFUNCTION returns false.  If the packet is not supported,
2782    returns -1.  */
2783
2784 static int
2785 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2786                             int looplimit)
2787 {
2788   struct remote_state *rs = get_remote_state ();
2789   int done, i, result_count;
2790   int startflag = 1;
2791   int result = 1;
2792   int loopcount = 0;
2793
2794   done = 0;
2795   while (!done)
2796     {
2797       if (loopcount++ > looplimit)
2798         {
2799           result = 0;
2800           warning (_("Remote fetch threadlist -infinite loop-."));
2801           break;
2802         }
2803       result = remote_get_threadlist (startflag, &rs->nextthread,
2804                                       MAXTHREADLISTRESULTS,
2805                                       &done, &result_count,
2806                                       rs->resultthreadlist);
2807       if (result <= 0)
2808         break;
2809       /* Clear for later iterations.  */
2810       startflag = 0;
2811       /* Setup to resume next batch of thread references, set nextthread.  */
2812       if (result_count >= 1)
2813         copy_threadref (&rs->nextthread,
2814                         &rs->resultthreadlist[result_count - 1]);
2815       i = 0;
2816       while (result_count--)
2817         {
2818           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2819             {
2820               result = 0;
2821               break;
2822             }
2823         }
2824     }
2825   return result;
2826 }
2827
2828 /* A thread found on the remote target.  */
2829
2830 typedef struct thread_item
2831 {
2832   /* The thread's PTID.  */
2833   ptid_t ptid;
2834
2835   /* The thread's extra info.  May be NULL.  */
2836   char *extra;
2837
2838   /* The thread's name.  May be NULL.  */
2839   char *name;
2840
2841   /* The core the thread was running on.  -1 if not known.  */
2842   int core;
2843 } thread_item_t;
2844 DEF_VEC_O(thread_item_t);
2845
2846 /* Context passed around to the various methods listing remote
2847    threads.  As new threads are found, they're added to the ITEMS
2848    vector.  */
2849
2850 struct threads_listing_context
2851 {
2852   /* The threads found on the remote target.  */
2853   VEC (thread_item_t) *items;
2854 };
2855
2856 /* Discard the contents of the constructed thread listing context.  */
2857
2858 static void
2859 clear_threads_listing_context (void *p)
2860 {
2861   struct threads_listing_context *context
2862     = (struct threads_listing_context *) p;
2863   int i;
2864   struct thread_item *item;
2865
2866   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2867     {
2868       xfree (item->extra);
2869       xfree (item->name);
2870     }
2871
2872   VEC_free (thread_item_t, context->items);
2873 }
2874
2875 /* Remove the thread specified as the related_pid field of WS
2876    from the CONTEXT list.  */
2877
2878 static void
2879 threads_listing_context_remove (struct target_waitstatus *ws,
2880                                 struct threads_listing_context *context)
2881 {
2882   struct thread_item *item;
2883   int i;
2884   ptid_t child_ptid = ws->value.related_pid;
2885
2886   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2887     {
2888       if (ptid_equal (item->ptid, child_ptid))
2889         {
2890           VEC_ordered_remove (thread_item_t, context->items, i);
2891           break;
2892         }
2893     }
2894 }
2895
2896 static int
2897 remote_newthread_step (threadref *ref, void *data)
2898 {
2899   struct threads_listing_context *context
2900     = (struct threads_listing_context *) data;
2901   struct thread_item item;
2902   int pid = ptid_get_pid (inferior_ptid);
2903
2904   item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2905   item.core = -1;
2906   item.extra = NULL;
2907
2908   VEC_safe_push (thread_item_t, context->items, &item);
2909
2910   return 1;                     /* continue iterator */
2911 }
2912
2913 #define CRAZY_MAX_THREADS 1000
2914
2915 static ptid_t
2916 remote_current_thread (ptid_t oldpid)
2917 {
2918   struct remote_state *rs = get_remote_state ();
2919
2920   putpkt ("qC");
2921   getpkt (&rs->buf, &rs->buf_size, 0);
2922   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2923     {
2924       char *obuf;
2925       ptid_t result;
2926
2927       result = read_ptid (&rs->buf[2], &obuf);
2928       if (*obuf != '\0' && remote_debug)
2929         fprintf_unfiltered (gdb_stdlog,
2930                             "warning: garbage in qC reply\n");
2931
2932       return result;
2933     }
2934   else
2935     return oldpid;
2936 }
2937
2938 /* List remote threads using the deprecated qL packet.  */
2939
2940 static int
2941 remote_get_threads_with_ql (struct target_ops *ops,
2942                             struct threads_listing_context *context)
2943 {
2944   if (remote_threadlist_iterator (remote_newthread_step, context,
2945                                   CRAZY_MAX_THREADS) >= 0)
2946     return 1;
2947
2948   return 0;
2949 }
2950
2951 #if defined(HAVE_LIBEXPAT)
2952
2953 static void
2954 start_thread (struct gdb_xml_parser *parser,
2955               const struct gdb_xml_element *element,
2956               void *user_data, VEC(gdb_xml_value_s) *attributes)
2957 {
2958   struct threads_listing_context *data
2959     = (struct threads_listing_context *) user_data;
2960
2961   struct thread_item item;
2962   char *id;
2963   struct gdb_xml_value *attr;
2964
2965   id = (char *) xml_find_attribute (attributes, "id")->value;
2966   item.ptid = read_ptid (id, NULL);
2967
2968   attr = xml_find_attribute (attributes, "core");
2969   if (attr != NULL)
2970     item.core = *(ULONGEST *) attr->value;
2971   else
2972     item.core = -1;
2973
2974   attr = xml_find_attribute (attributes, "name");
2975   item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
2976
2977   item.extra = 0;
2978
2979   VEC_safe_push (thread_item_t, data->items, &item);
2980 }
2981
2982 static void
2983 end_thread (struct gdb_xml_parser *parser,
2984             const struct gdb_xml_element *element,
2985             void *user_data, const char *body_text)
2986 {
2987   struct threads_listing_context *data
2988     = (struct threads_listing_context *) user_data;
2989
2990   if (body_text && *body_text)
2991     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2992 }
2993
2994 const struct gdb_xml_attribute thread_attributes[] = {
2995   { "id", GDB_XML_AF_NONE, NULL, NULL },
2996   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2997   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
2998   { NULL, GDB_XML_AF_NONE, NULL, NULL }
2999 };
3000
3001 const struct gdb_xml_element thread_children[] = {
3002   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3003 };
3004
3005 const struct gdb_xml_element threads_children[] = {
3006   { "thread", thread_attributes, thread_children,
3007     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3008     start_thread, end_thread },
3009   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3010 };
3011
3012 const struct gdb_xml_element threads_elements[] = {
3013   { "threads", NULL, threads_children,
3014     GDB_XML_EF_NONE, NULL, NULL },
3015   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3016 };
3017
3018 #endif
3019
3020 /* List remote threads using qXfer:threads:read.  */
3021
3022 static int
3023 remote_get_threads_with_qxfer (struct target_ops *ops,
3024                                struct threads_listing_context *context)
3025 {
3026 #if defined(HAVE_LIBEXPAT)
3027   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3028     {
3029       char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3030       struct cleanup *back_to = make_cleanup (xfree, xml);
3031
3032       if (xml != NULL && *xml != '\0')
3033         {
3034           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3035                                threads_elements, xml, context);
3036         }
3037
3038       do_cleanups (back_to);
3039       return 1;
3040     }
3041 #endif
3042
3043   return 0;
3044 }
3045
3046 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3047
3048 static int
3049 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3050                                      struct threads_listing_context *context)
3051 {
3052   struct remote_state *rs = get_remote_state ();
3053
3054   if (rs->use_threadinfo_query)
3055     {
3056       char *bufp;
3057
3058       putpkt ("qfThreadInfo");
3059       getpkt (&rs->buf, &rs->buf_size, 0);
3060       bufp = rs->buf;
3061       if (bufp[0] != '\0')              /* q packet recognized */
3062         {
3063           while (*bufp++ == 'm')        /* reply contains one or more TID */
3064             {
3065               do
3066                 {
3067                   struct thread_item item;
3068
3069                   item.ptid = read_ptid (bufp, &bufp);
3070                   item.core = -1;
3071                   item.extra = NULL;
3072
3073                   VEC_safe_push (thread_item_t, context->items, &item);
3074                 }
3075               while (*bufp++ == ',');   /* comma-separated list */
3076               putpkt ("qsThreadInfo");
3077               getpkt (&rs->buf, &rs->buf_size, 0);
3078               bufp = rs->buf;
3079             }
3080           return 1;
3081         }
3082       else
3083         {
3084           /* Packet not recognized.  */
3085           rs->use_threadinfo_query = 0;
3086         }
3087     }
3088
3089   return 0;
3090 }
3091
3092 /* Implement the to_update_thread_list function for the remote
3093    targets.  */
3094
3095 static void
3096 remote_update_thread_list (struct target_ops *ops)
3097 {
3098   struct remote_state *rs = get_remote_state ();
3099   struct threads_listing_context context;
3100   struct cleanup *old_chain;
3101   int got_list = 0;
3102
3103   context.items = NULL;
3104   old_chain = make_cleanup (clear_threads_listing_context, &context);
3105
3106   /* We have a few different mechanisms to fetch the thread list.  Try
3107      them all, starting with the most preferred one first, falling
3108      back to older methods.  */
3109   if (remote_get_threads_with_qxfer (ops, &context)
3110       || remote_get_threads_with_qthreadinfo (ops, &context)
3111       || remote_get_threads_with_ql (ops, &context))
3112     {
3113       int i;
3114       struct thread_item *item;
3115       struct thread_info *tp, *tmp;
3116
3117       got_list = 1;
3118
3119       if (VEC_empty (thread_item_t, context.items)
3120           && remote_thread_always_alive (ops, inferior_ptid))
3121         {
3122           /* Some targets don't really support threads, but still
3123              reply an (empty) thread list in response to the thread
3124              listing packets, instead of replying "packet not
3125              supported".  Exit early so we don't delete the main
3126              thread.  */
3127           do_cleanups (old_chain);
3128           return;
3129         }
3130
3131       /* CONTEXT now holds the current thread list on the remote
3132          target end.  Delete GDB-side threads no longer found on the
3133          target.  */
3134       ALL_THREADS_SAFE (tp, tmp)
3135         {
3136           for (i = 0;
3137                VEC_iterate (thread_item_t, context.items, i, item);
3138                ++i)
3139             {
3140               if (ptid_equal (item->ptid, tp->ptid))
3141                 break;
3142             }
3143
3144           if (i == VEC_length (thread_item_t, context.items))
3145             {
3146               /* Not found.  */
3147               delete_thread (tp->ptid);
3148             }
3149         }
3150
3151       /* Remove any unreported fork child threads from CONTEXT so
3152          that we don't interfere with follow fork, which is where
3153          creation of such threads is handled.  */
3154       remove_new_fork_children (&context);
3155
3156       /* And now add threads we don't know about yet to our list.  */
3157       for (i = 0;
3158            VEC_iterate (thread_item_t, context.items, i, item);
3159            ++i)
3160         {
3161           if (!ptid_equal (item->ptid, null_ptid))
3162             {
3163               struct private_thread_info *info;
3164               /* In non-stop mode, we assume new found threads are
3165                  running until proven otherwise with a stop reply.  In
3166                  all-stop, we can only get here if all threads are
3167                  stopped.  */
3168               int running = non_stop ? 1 : 0;
3169
3170               remote_notice_new_inferior (item->ptid, running);
3171
3172               info = demand_private_info (item->ptid);
3173               info->core = item->core;
3174               info->extra = item->extra;
3175               item->extra = NULL;
3176               info->name = item->name;
3177               item->name = NULL;
3178             }
3179         }
3180     }
3181
3182   if (!got_list)
3183     {
3184       /* If no thread listing method is supported, then query whether
3185          each known thread is alive, one by one, with the T packet.
3186          If the target doesn't support threads at all, then this is a
3187          no-op.  See remote_thread_alive.  */
3188       prune_threads ();
3189     }
3190
3191   do_cleanups (old_chain);
3192 }
3193
3194 /*
3195  * Collect a descriptive string about the given thread.
3196  * The target may say anything it wants to about the thread
3197  * (typically info about its blocked / runnable state, name, etc.).
3198  * This string will appear in the info threads display.
3199  *
3200  * Optional: targets are not required to implement this function.
3201  */
3202
3203 static char *
3204 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3205 {
3206   struct remote_state *rs = get_remote_state ();
3207   int result;
3208   int set;
3209   threadref id;
3210   struct gdb_ext_thread_info threadinfo;
3211   static char display_buf[100]; /* arbitrary...  */
3212   int n = 0;                    /* position in display_buf */
3213
3214   if (rs->remote_desc == 0)             /* paranoia */
3215     internal_error (__FILE__, __LINE__,
3216                     _("remote_threads_extra_info"));
3217
3218   if (ptid_equal (tp->ptid, magic_null_ptid)
3219       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3220     /* This is the main thread which was added by GDB.  The remote
3221        server doesn't know about it.  */
3222     return NULL;
3223
3224   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3225     {
3226       struct thread_info *info = find_thread_ptid (tp->ptid);
3227
3228       if (info && info->priv)
3229         return info->priv->extra;
3230       else
3231         return NULL;
3232     }
3233
3234   if (rs->use_threadextra_query)
3235     {
3236       char *b = rs->buf;
3237       char *endb = rs->buf + get_remote_packet_size ();
3238
3239       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3240       b += strlen (b);
3241       write_ptid (b, endb, tp->ptid);
3242
3243       putpkt (rs->buf);
3244       getpkt (&rs->buf, &rs->buf_size, 0);
3245       if (rs->buf[0] != 0)
3246         {
3247           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3248           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3249           display_buf [result] = '\0';
3250           return display_buf;
3251         }
3252     }
3253
3254   /* If the above query fails, fall back to the old method.  */
3255   rs->use_threadextra_query = 0;
3256   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3257     | TAG_MOREDISPLAY | TAG_DISPLAY;
3258   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3259   if (remote_get_threadinfo (&id, set, &threadinfo))
3260     if (threadinfo.active)
3261       {
3262         if (*threadinfo.shortname)
3263           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3264                           " Name: %s,", threadinfo.shortname);
3265         if (*threadinfo.display)
3266           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3267                           " State: %s,", threadinfo.display);
3268         if (*threadinfo.more_display)
3269           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3270                           " Priority: %s", threadinfo.more_display);
3271
3272         if (n > 0)
3273           {
3274             /* For purely cosmetic reasons, clear up trailing commas.  */
3275             if (',' == display_buf[n-1])
3276               display_buf[n-1] = ' ';
3277             return display_buf;
3278           }
3279       }
3280   return NULL;
3281 }
3282 \f
3283
3284 static int
3285 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3286                                     struct static_tracepoint_marker *marker)
3287 {
3288   struct remote_state *rs = get_remote_state ();
3289   char *p = rs->buf;
3290
3291   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3292   p += strlen (p);
3293   p += hexnumstr (p, addr);
3294   putpkt (rs->buf);
3295   getpkt (&rs->buf, &rs->buf_size, 0);
3296   p = rs->buf;
3297
3298   if (*p == 'E')
3299     error (_("Remote failure reply: %s"), p);
3300
3301   if (*p++ == 'm')
3302     {
3303       parse_static_tracepoint_marker_definition (p, &p, marker);
3304       return 1;
3305     }
3306
3307   return 0;
3308 }
3309
3310 static VEC(static_tracepoint_marker_p) *
3311 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3312                                            const char *strid)
3313 {
3314   struct remote_state *rs = get_remote_state ();
3315   VEC(static_tracepoint_marker_p) *markers = NULL;
3316   struct static_tracepoint_marker *marker = NULL;
3317   struct cleanup *old_chain;
3318   char *p;
3319
3320   /* Ask for a first packet of static tracepoint marker
3321      definition.  */
3322   putpkt ("qTfSTM");
3323   getpkt (&rs->buf, &rs->buf_size, 0);
3324   p = rs->buf;
3325   if (*p == 'E')
3326     error (_("Remote failure reply: %s"), p);
3327
3328   old_chain = make_cleanup (free_current_marker, &marker);
3329
3330   while (*p++ == 'm')
3331     {
3332       if (marker == NULL)
3333         marker = XCNEW (struct static_tracepoint_marker);
3334
3335       do
3336         {
3337           parse_static_tracepoint_marker_definition (p, &p, marker);
3338
3339           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3340             {
3341               VEC_safe_push (static_tracepoint_marker_p,
3342                              markers, marker);
3343               marker = NULL;
3344             }
3345           else
3346             {
3347               release_static_tracepoint_marker (marker);
3348               memset (marker, 0, sizeof (*marker));
3349             }
3350         }
3351       while (*p++ == ',');      /* comma-separated list */
3352       /* Ask for another packet of static tracepoint definition.  */
3353       putpkt ("qTsSTM");
3354       getpkt (&rs->buf, &rs->buf_size, 0);
3355       p = rs->buf;
3356     }
3357
3358   do_cleanups (old_chain);
3359   return markers;
3360 }
3361
3362 \f
3363 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3364
3365 static ptid_t
3366 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3367 {
3368   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3369 }
3370 \f
3371
3372 /* Restart the remote side; this is an extended protocol operation.  */
3373
3374 static void
3375 extended_remote_restart (void)
3376 {
3377   struct remote_state *rs = get_remote_state ();
3378
3379   /* Send the restart command; for reasons I don't understand the
3380      remote side really expects a number after the "R".  */
3381   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3382   putpkt (rs->buf);
3383
3384   remote_fileio_reset ();
3385 }
3386 \f
3387 /* Clean up connection to a remote debugger.  */
3388
3389 static void
3390 remote_close (struct target_ops *self)
3391 {
3392   struct remote_state *rs = get_remote_state ();
3393
3394   if (rs->remote_desc == NULL)
3395     return; /* already closed */
3396
3397   /* Make sure we leave stdin registered in the event loop, and we
3398      don't leave the async SIGINT signal handler installed.  */
3399   remote_terminal_ours (self);
3400
3401   serial_close (rs->remote_desc);
3402   rs->remote_desc = NULL;
3403
3404   /* We don't have a connection to the remote stub anymore.  Get rid
3405      of all the inferiors and their threads we were controlling.
3406      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3407      will be unable to find the thread corresponding to (pid, 0, 0).  */
3408   inferior_ptid = null_ptid;
3409   discard_all_inferiors ();
3410
3411   /* We are closing the remote target, so we should discard
3412      everything of this target.  */
3413   discard_pending_stop_replies_in_queue (rs);
3414
3415   if (remote_async_inferior_event_token)
3416     delete_async_event_handler (&remote_async_inferior_event_token);
3417
3418   remote_notif_state_xfree (rs->notif_state);
3419
3420   trace_reset_local_state ();
3421 }
3422
3423 /* Query the remote side for the text, data and bss offsets.  */
3424
3425 static void
3426 get_offsets (void)
3427 {
3428   struct remote_state *rs = get_remote_state ();
3429   char *buf;
3430   char *ptr;
3431   int lose, num_segments = 0, do_sections, do_segments;
3432   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3433   struct section_offsets *offs;
3434   struct symfile_segment_data *data;
3435
3436   if (symfile_objfile == NULL)
3437     return;
3438
3439   putpkt ("qOffsets");
3440   getpkt (&rs->buf, &rs->buf_size, 0);
3441   buf = rs->buf;
3442
3443   if (buf[0] == '\000')
3444     return;                     /* Return silently.  Stub doesn't support
3445                                    this command.  */
3446   if (buf[0] == 'E')
3447     {
3448       warning (_("Remote failure reply: %s"), buf);
3449       return;
3450     }
3451
3452   /* Pick up each field in turn.  This used to be done with scanf, but
3453      scanf will make trouble if CORE_ADDR size doesn't match
3454      conversion directives correctly.  The following code will work
3455      with any size of CORE_ADDR.  */
3456   text_addr = data_addr = bss_addr = 0;
3457   ptr = buf;
3458   lose = 0;
3459
3460   if (startswith (ptr, "Text="))
3461     {
3462       ptr += 5;
3463       /* Don't use strtol, could lose on big values.  */
3464       while (*ptr && *ptr != ';')
3465         text_addr = (text_addr << 4) + fromhex (*ptr++);
3466
3467       if (startswith (ptr, ";Data="))
3468         {
3469           ptr += 6;
3470           while (*ptr && *ptr != ';')
3471             data_addr = (data_addr << 4) + fromhex (*ptr++);
3472         }
3473       else
3474         lose = 1;
3475
3476       if (!lose && startswith (ptr, ";Bss="))
3477         {
3478           ptr += 5;
3479           while (*ptr && *ptr != ';')
3480             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3481
3482           if (bss_addr != data_addr)
3483             warning (_("Target reported unsupported offsets: %s"), buf);
3484         }
3485       else
3486         lose = 1;
3487     }
3488   else if (startswith (ptr, "TextSeg="))
3489     {
3490       ptr += 8;
3491       /* Don't use strtol, could lose on big values.  */
3492       while (*ptr && *ptr != ';')
3493         text_addr = (text_addr << 4) + fromhex (*ptr++);
3494       num_segments = 1;
3495
3496       if (startswith (ptr, ";DataSeg="))
3497         {
3498           ptr += 9;
3499           while (*ptr && *ptr != ';')
3500             data_addr = (data_addr << 4) + fromhex (*ptr++);
3501           num_segments++;
3502         }
3503     }
3504   else
3505     lose = 1;
3506
3507   if (lose)
3508     error (_("Malformed response to offset query, %s"), buf);
3509   else if (*ptr != '\0')
3510     warning (_("Target reported unsupported offsets: %s"), buf);
3511
3512   offs = ((struct section_offsets *)
3513           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3514   memcpy (offs, symfile_objfile->section_offsets,
3515           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3516
3517   data = get_symfile_segment_data (symfile_objfile->obfd);
3518   do_segments = (data != NULL);
3519   do_sections = num_segments == 0;
3520
3521   if (num_segments > 0)
3522     {
3523       segments[0] = text_addr;
3524       segments[1] = data_addr;
3525     }
3526   /* If we have two segments, we can still try to relocate everything
3527      by assuming that the .text and .data offsets apply to the whole
3528      text and data segments.  Convert the offsets given in the packet
3529      to base addresses for symfile_map_offsets_to_segments.  */
3530   else if (data && data->num_segments == 2)
3531     {
3532       segments[0] = data->segment_bases[0] + text_addr;
3533       segments[1] = data->segment_bases[1] + data_addr;
3534       num_segments = 2;
3535     }
3536   /* If the object file has only one segment, assume that it is text
3537      rather than data; main programs with no writable data are rare,
3538      but programs with no code are useless.  Of course the code might
3539      have ended up in the data segment... to detect that we would need
3540      the permissions here.  */
3541   else if (data && data->num_segments == 1)
3542     {
3543       segments[0] = data->segment_bases[0] + text_addr;
3544       num_segments = 1;
3545     }
3546   /* There's no way to relocate by segment.  */
3547   else
3548     do_segments = 0;
3549
3550   if (do_segments)
3551     {
3552       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3553                                                  offs, num_segments, segments);
3554
3555       if (ret == 0 && !do_sections)
3556         error (_("Can not handle qOffsets TextSeg "
3557                  "response with this symbol file"));
3558
3559       if (ret > 0)
3560         do_sections = 0;
3561     }
3562
3563   if (data)
3564     free_symfile_segment_data (data);
3565
3566   if (do_sections)
3567     {
3568       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3569
3570       /* This is a temporary kludge to force data and bss to use the
3571          same offsets because that's what nlmconv does now.  The real
3572          solution requires changes to the stub and remote.c that I
3573          don't have time to do right now.  */
3574
3575       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3576       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3577     }
3578
3579   objfile_relocate (symfile_objfile, offs);
3580 }
3581
3582 /* Send interrupt_sequence to remote target.  */
3583 static void
3584 send_interrupt_sequence (void)
3585 {
3586   struct remote_state *rs = get_remote_state ();
3587
3588   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3589     remote_serial_write ("\x03", 1);
3590   else if (interrupt_sequence_mode == interrupt_sequence_break)
3591     serial_send_break (rs->remote_desc);
3592   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3593     {
3594       serial_send_break (rs->remote_desc);
3595       remote_serial_write ("g", 1);
3596     }
3597   else
3598     internal_error (__FILE__, __LINE__,
3599                     _("Invalid value for interrupt_sequence_mode: %s."),
3600                     interrupt_sequence_mode);
3601 }
3602
3603
3604 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3605    and extract the PTID.  Returns NULL_PTID if not found.  */
3606
3607 static ptid_t
3608 stop_reply_extract_thread (char *stop_reply)
3609 {
3610   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3611     {
3612       char *p;
3613
3614       /* Txx r:val ; r:val (...)  */
3615       p = &stop_reply[3];
3616
3617       /* Look for "register" named "thread".  */
3618       while (*p != '\0')
3619         {
3620           char *p1;
3621
3622           p1 = strchr (p, ':');
3623           if (p1 == NULL)
3624             return null_ptid;
3625
3626           if (strncmp (p, "thread", p1 - p) == 0)
3627             return read_ptid (++p1, &p);
3628
3629           p1 = strchr (p, ';');
3630           if (p1 == NULL)
3631             return null_ptid;
3632           p1++;
3633
3634           p = p1;
3635         }
3636     }
3637
3638   return null_ptid;
3639 }
3640
3641 /* Determine the remote side's current thread.  If we have a stop
3642    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3643    "thread" register we can extract the current thread from.  If not,
3644    ask the remote which is the current thread with qC.  The former
3645    method avoids a roundtrip.  */
3646
3647 static ptid_t
3648 get_current_thread (char *wait_status)
3649 {
3650   ptid_t ptid = null_ptid;
3651
3652   /* Note we don't use remote_parse_stop_reply as that makes use of
3653      the target architecture, which we haven't yet fully determined at
3654      this point.  */
3655   if (wait_status != NULL)
3656     ptid = stop_reply_extract_thread (wait_status);
3657   if (ptid_equal (ptid, null_ptid))
3658     ptid = remote_current_thread (inferior_ptid);
3659
3660   return ptid;
3661 }
3662
3663 /* Query the remote target for which is the current thread/process,
3664    add it to our tables, and update INFERIOR_PTID.  The caller is
3665    responsible for setting the state such that the remote end is ready
3666    to return the current thread.
3667
3668    This function is called after handling the '?' or 'vRun' packets,
3669    whose response is a stop reply from which we can also try
3670    extracting the thread.  If the target doesn't support the explicit
3671    qC query, we infer the current thread from that stop reply, passed
3672    in in WAIT_STATUS, which may be NULL.  */
3673
3674 static void
3675 add_current_inferior_and_thread (char *wait_status)
3676 {
3677   struct remote_state *rs = get_remote_state ();
3678   int fake_pid_p = 0;
3679   ptid_t ptid;
3680
3681   inferior_ptid = null_ptid;
3682
3683   /* Now, if we have thread information, update inferior_ptid.  */
3684   ptid = get_current_thread (wait_status);
3685
3686   if (!ptid_equal (ptid, null_ptid))
3687     {
3688       if (!remote_multi_process_p (rs))
3689         fake_pid_p = 1;
3690
3691       inferior_ptid = ptid;
3692     }
3693   else
3694     {
3695       /* Without this, some commands which require an active target
3696          (such as kill) won't work.  This variable serves (at least)
3697          double duty as both the pid of the target process (if it has
3698          such), and as a flag indicating that a target is active.  */
3699       inferior_ptid = magic_null_ptid;
3700       fake_pid_p = 1;
3701     }
3702
3703   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3704
3705   /* Add the main thread.  */
3706   add_thread_silent (inferior_ptid);
3707 }
3708
3709 /* Process all initial stop replies the remote side sent in response
3710    to the ? packet.  These indicate threads that were already stopped
3711    on initial connection.  We mark these threads as stopped and print
3712    their current frame before giving the user the prompt.  */
3713
3714 static void
3715 process_initial_stop_replies (void)
3716 {
3717   int pending_stop_replies = stop_reply_queue_length ();
3718
3719   /* Consume the initial pending events.  */
3720   while (pending_stop_replies-- > 0)
3721     {
3722       ptid_t waiton_ptid = minus_one_ptid;
3723       ptid_t event_ptid;
3724       struct target_waitstatus ws;
3725       int ignore_event = 0;
3726
3727       memset (&ws, 0, sizeof (ws));
3728       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3729       if (remote_debug)
3730         print_target_wait_results (waiton_ptid, event_ptid, &ws);
3731
3732       switch (ws.kind)
3733         {
3734         case TARGET_WAITKIND_IGNORE:
3735         case TARGET_WAITKIND_NO_RESUMED:
3736         case TARGET_WAITKIND_SIGNALLED:
3737         case TARGET_WAITKIND_EXITED:
3738           /* We shouldn't see these, but if we do, just ignore.  */
3739           if (remote_debug)
3740             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3741           ignore_event = 1;
3742           break;
3743
3744         case TARGET_WAITKIND_EXECD:
3745           xfree (ws.value.execd_pathname);
3746           break;
3747         default:
3748           break;
3749         }
3750
3751       if (ignore_event)
3752         continue;
3753
3754       switch_to_thread (event_ptid);
3755       set_executing (event_ptid, 0);
3756       set_running (event_ptid, 0);
3757
3758       stop_pc = get_frame_pc (get_current_frame ());
3759       set_current_sal_from_frame (get_current_frame ());
3760
3761       if (ws.kind == TARGET_WAITKIND_STOPPED)
3762         {
3763           enum gdb_signal sig = ws.value.sig;
3764
3765           /* Stubs traditionally report SIGTRAP as initial signal,
3766              instead of signal 0.  Suppress it.  */
3767           if (sig == GDB_SIGNAL_TRAP)
3768             sig = GDB_SIGNAL_0;
3769           inferior_thread ()->suspend.stop_signal = sig;
3770
3771           if (signal_print_state (sig))
3772             observer_notify_signal_received (sig);
3773         }
3774
3775       print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
3776       observer_notify_normal_stop (NULL, 1);
3777     }
3778 }
3779
3780 static void
3781 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3782 {
3783   struct remote_state *rs = get_remote_state ();
3784   struct packet_config *noack_config;
3785   char *wait_status = NULL;
3786
3787   immediate_quit++;             /* Allow user to interrupt it.  */
3788   QUIT;
3789
3790   if (interrupt_on_connect)
3791     send_interrupt_sequence ();
3792
3793   /* Ack any packet which the remote side has already sent.  */
3794   serial_write (rs->remote_desc, "+", 1);
3795
3796   /* Signal other parts that we're going through the initial setup,
3797      and so things may not be stable yet.  */
3798   rs->starting_up = 1;
3799
3800   /* The first packet we send to the target is the optional "supported
3801      packets" request.  If the target can answer this, it will tell us
3802      which later probes to skip.  */
3803   remote_query_supported ();
3804
3805   /* If the stub wants to get a QAllow, compose one and send it.  */
3806   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3807     remote_set_permissions (target);
3808
3809   /* Next, we possibly activate noack mode.
3810
3811      If the QStartNoAckMode packet configuration is set to AUTO,
3812      enable noack mode if the stub reported a wish for it with
3813      qSupported.
3814
3815      If set to TRUE, then enable noack mode even if the stub didn't
3816      report it in qSupported.  If the stub doesn't reply OK, the
3817      session ends with an error.
3818
3819      If FALSE, then don't activate noack mode, regardless of what the
3820      stub claimed should be the default with qSupported.  */
3821
3822   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3823   if (packet_config_support (noack_config) != PACKET_DISABLE)
3824     {
3825       putpkt ("QStartNoAckMode");
3826       getpkt (&rs->buf, &rs->buf_size, 0);
3827       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3828         rs->noack_mode = 1;
3829     }
3830
3831   if (extended_p)
3832     {
3833       /* Tell the remote that we are using the extended protocol.  */
3834       putpkt ("!");
3835       getpkt (&rs->buf, &rs->buf_size, 0);
3836     }
3837
3838   /* Let the target know which signals it is allowed to pass down to
3839      the program.  */
3840   update_signals_program_target ();
3841
3842   /* Next, if the target can specify a description, read it.  We do
3843      this before anything involving memory or registers.  */
3844   target_find_description ();
3845
3846   /* Next, now that we know something about the target, update the
3847      address spaces in the program spaces.  */
3848   update_address_spaces ();
3849
3850   /* On OSs where the list of libraries is global to all
3851      processes, we fetch them early.  */
3852   if (gdbarch_has_global_solist (target_gdbarch ()))
3853     solib_add (NULL, from_tty, target, auto_solib_add);
3854
3855   if (non_stop)
3856     {
3857       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3858         error (_("Non-stop mode requested, but remote "
3859                  "does not support non-stop"));
3860
3861       putpkt ("QNonStop:1");
3862       getpkt (&rs->buf, &rs->buf_size, 0);
3863
3864       if (strcmp (rs->buf, "OK") != 0)
3865         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3866
3867       /* Find about threads and processes the stub is already
3868          controlling.  We default to adding them in the running state.
3869          The '?' query below will then tell us about which threads are
3870          stopped.  */
3871       remote_update_thread_list (target);
3872     }
3873   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3874     {
3875       /* Don't assume that the stub can operate in all-stop mode.
3876          Request it explicitly.  */
3877       putpkt ("QNonStop:0");
3878       getpkt (&rs->buf, &rs->buf_size, 0);
3879
3880       if (strcmp (rs->buf, "OK") != 0)
3881         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3882     }
3883
3884   /* Upload TSVs regardless of whether the target is running or not.  The
3885      remote stub, such as GDBserver, may have some predefined or builtin
3886      TSVs, even if the target is not running.  */
3887   if (remote_get_trace_status (target, current_trace_status ()) != -1)
3888     {
3889       struct uploaded_tsv *uploaded_tsvs = NULL;
3890
3891       remote_upload_trace_state_variables (target, &uploaded_tsvs);
3892       merge_uploaded_trace_state_variables (&uploaded_tsvs);
3893     }
3894
3895   /* Check whether the target is running now.  */
3896   putpkt ("?");
3897   getpkt (&rs->buf, &rs->buf_size, 0);
3898
3899   if (!non_stop)
3900     {
3901       ptid_t ptid;
3902       int fake_pid_p = 0;
3903       struct inferior *inf;
3904
3905       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3906         {
3907           if (!extended_p)
3908             error (_("The target is not running (try extended-remote?)"));
3909
3910           /* We're connected, but not running.  Drop out before we
3911              call start_remote.  */
3912           rs->starting_up = 0;
3913           return;
3914         }
3915       else
3916         {
3917           /* Save the reply for later.  */
3918           wait_status = (char *) alloca (strlen (rs->buf) + 1);
3919           strcpy (wait_status, rs->buf);
3920         }
3921
3922       /* Fetch thread list.  */
3923       target_update_thread_list ();
3924
3925       /* Let the stub know that we want it to return the thread.  */
3926       set_continue_thread (minus_one_ptid);
3927
3928       if (thread_count () == 0)
3929         {
3930           /* Target has no concept of threads at all.  GDB treats
3931              non-threaded target as single-threaded; add a main
3932              thread.  */
3933           add_current_inferior_and_thread (wait_status);
3934         }
3935       else
3936         {
3937           /* We have thread information; select the thread the target
3938              says should be current.  If we're reconnecting to a
3939              multi-threaded program, this will ideally be the thread
3940              that last reported an event before GDB disconnected.  */
3941           inferior_ptid = get_current_thread (wait_status);
3942           if (ptid_equal (inferior_ptid, null_ptid))
3943             {
3944               /* Odd... The target was able to list threads, but not
3945                  tell us which thread was current (no "thread"
3946                  register in T stop reply?).  Just pick the first
3947                  thread in the thread list then.  */
3948               
3949               if (remote_debug)
3950                 fprintf_unfiltered (gdb_stdlog,
3951                                     "warning: couldn't determine remote "
3952                                     "current thread; picking first in list.\n");
3953
3954               inferior_ptid = thread_list->ptid;
3955             }
3956         }
3957
3958       /* init_wait_for_inferior should be called before get_offsets in order
3959          to manage `inserted' flag in bp loc in a correct state.
3960          breakpoint_init_inferior, called from init_wait_for_inferior, set
3961          `inserted' flag to 0, while before breakpoint_re_set, called from
3962          start_remote, set `inserted' flag to 1.  In the initialization of
3963          inferior, breakpoint_init_inferior should be called first, and then
3964          breakpoint_re_set can be called.  If this order is broken, state of
3965          `inserted' flag is wrong, and cause some problems on breakpoint
3966          manipulation.  */
3967       init_wait_for_inferior ();
3968
3969       get_offsets ();           /* Get text, data & bss offsets.  */
3970
3971       /* If we could not find a description using qXfer, and we know
3972          how to do it some other way, try again.  This is not
3973          supported for non-stop; it could be, but it is tricky if
3974          there are no stopped threads when we connect.  */
3975       if (remote_read_description_p (target)
3976           && gdbarch_target_desc (target_gdbarch ()) == NULL)
3977         {
3978           target_clear_description ();
3979           target_find_description ();
3980         }
3981
3982       /* Use the previously fetched status.  */
3983       gdb_assert (wait_status != NULL);
3984       strcpy (rs->buf, wait_status);
3985       rs->cached_wait_status = 1;
3986
3987       immediate_quit--;
3988       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
3989     }
3990   else
3991     {
3992       ptid_t current_ptid;
3993
3994       /* Clear WFI global state.  Do this before finding about new
3995          threads and inferiors, and setting the current inferior.
3996          Otherwise we would clear the proceed status of the current
3997          inferior when we want its stop_soon state to be preserved
3998          (see notice_new_inferior).  */
3999       init_wait_for_inferior ();
4000
4001       /* In non-stop, we will either get an "OK", meaning that there
4002          are no stopped threads at this time; or, a regular stop
4003          reply.  In the latter case, there may be more than one thread
4004          stopped --- we pull them all out using the vStopped
4005          mechanism.  */
4006       if (strcmp (rs->buf, "OK") != 0)
4007         {
4008           struct notif_client *notif = &notif_client_stop;
4009
4010           /* remote_notif_get_pending_replies acks this one, and gets
4011              the rest out.  */
4012           rs->notif_state->pending_event[notif_client_stop.id]
4013             = remote_notif_parse (notif, rs->buf);
4014           remote_notif_get_pending_events (notif);
4015         }
4016
4017       if (thread_count () == 0)
4018         {
4019           if (!extended_p)
4020             error (_("The target is not running (try extended-remote?)"));
4021
4022           /* We're connected, but not running.  Drop out before we
4023              call start_remote.  */
4024           rs->starting_up = 0;
4025           return;
4026         }
4027
4028       /* Let the stub know that we want it to return the thread.  */
4029
4030       /* Force the stub to choose a thread.  */
4031       set_general_thread (null_ptid);
4032
4033       /* Query it.  */
4034       current_ptid = remote_current_thread (minus_one_ptid);
4035       if (ptid_equal (inferior_ptid, minus_one_ptid))
4036         error (_("remote didn't report the current thread in non-stop mode"));
4037
4038       inferior_ptid = current_ptid;
4039       get_offsets ();           /* Get text, data & bss offsets.  */
4040
4041       /* In non-stop mode, any cached wait status will be stored in
4042          the stop reply queue.  */
4043       gdb_assert (wait_status == NULL);
4044
4045       /* Report all signals during attach/startup.  */
4046       remote_pass_signals (target, 0, NULL);
4047
4048       /* If there are already stopped threads, mark them stopped and
4049          report their stops before giving the prompt to the user.  */
4050       process_initial_stop_replies ();
4051
4052       switch_to_thread (current_ptid);
4053
4054       if (target_can_async_p ())
4055         target_async (1);
4056     }
4057
4058   /* If we connected to a live target, do some additional setup.  */
4059   if (target_has_execution)
4060     {
4061       if (symfile_objfile)      /* No use without a symbol-file.  */
4062         remote_check_symbols ();
4063     }
4064
4065   /* Possibly the target has been engaged in a trace run started
4066      previously; find out where things are at.  */
4067   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4068     {
4069       struct uploaded_tp *uploaded_tps = NULL;
4070
4071       if (current_trace_status ()->running)
4072         printf_filtered (_("Trace is already running on the target.\n"));
4073
4074       remote_upload_tracepoints (target, &uploaded_tps);
4075
4076       merge_uploaded_tracepoints (&uploaded_tps);
4077     }
4078
4079   /* The thread and inferior lists are now synchronized with the
4080      target, our symbols have been relocated, and we're merged the
4081      target's tracepoints with ours.  We're done with basic start
4082      up.  */
4083   rs->starting_up = 0;
4084
4085   /* Maybe breakpoints are global and need to be inserted now.  */
4086   if (breakpoints_should_be_inserted_now ())
4087     insert_breakpoints ();
4088 }
4089
4090 /* Open a connection to a remote debugger.
4091    NAME is the filename used for communication.  */
4092
4093 static void
4094 remote_open (const char *name, int from_tty)
4095 {
4096   remote_open_1 (name, from_tty, &remote_ops, 0);
4097 }
4098
4099 /* Open a connection to a remote debugger using the extended
4100    remote gdb protocol.  NAME is the filename used for communication.  */
4101
4102 static void
4103 extended_remote_open (const char *name, int from_tty)
4104 {
4105   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4106 }
4107
4108 /* Reset all packets back to "unknown support".  Called when opening a
4109    new connection to a remote target.  */
4110
4111 static void
4112 reset_all_packet_configs_support (void)
4113 {
4114   int i;
4115
4116   for (i = 0; i < PACKET_MAX; i++)
4117     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4118 }
4119
4120 /* Initialize all packet configs.  */
4121
4122 static void
4123 init_all_packet_configs (void)
4124 {
4125   int i;
4126
4127   for (i = 0; i < PACKET_MAX; i++)
4128     {
4129       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4130       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4131     }
4132 }
4133
4134 /* Symbol look-up.  */
4135
4136 static void
4137 remote_check_symbols (void)
4138 {
4139   struct remote_state *rs = get_remote_state ();
4140   char *msg, *reply, *tmp;
4141   struct bound_minimal_symbol sym;
4142   int end;
4143   struct cleanup *old_chain;
4144
4145   /* The remote side has no concept of inferiors that aren't running
4146      yet, it only knows about running processes.  If we're connected
4147      but our current inferior is not running, we should not invite the
4148      remote target to request symbol lookups related to its
4149      (unrelated) current process.  */
4150   if (!target_has_execution)
4151     return;
4152
4153   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4154     return;
4155
4156   /* Make sure the remote is pointing at the right process.  Note
4157      there's no way to select "no process".  */
4158   set_general_process ();
4159
4160   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4161      because we need both at the same time.  */
4162   msg = (char *) xmalloc (get_remote_packet_size ());
4163   old_chain = make_cleanup (xfree, msg);
4164
4165   /* Invite target to request symbol lookups.  */
4166
4167   putpkt ("qSymbol::");
4168   getpkt (&rs->buf, &rs->buf_size, 0);
4169   packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4170   reply = rs->buf;
4171
4172   while (startswith (reply, "qSymbol:"))
4173     {
4174       struct bound_minimal_symbol sym;
4175
4176       tmp = &reply[8];
4177       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4178       msg[end] = '\0';
4179       sym = lookup_minimal_symbol (msg, NULL, NULL);
4180       if (sym.minsym == NULL)
4181         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4182       else
4183         {
4184           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4185           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4186
4187           /* If this is a function address, return the start of code
4188              instead of any data function descriptor.  */
4189           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4190                                                          sym_addr,
4191                                                          &current_target);
4192
4193           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4194                      phex_nz (sym_addr, addr_size), &reply[8]);
4195         }
4196   
4197       putpkt (msg);
4198       getpkt (&rs->buf, &rs->buf_size, 0);
4199       reply = rs->buf;
4200     }
4201
4202   do_cleanups (old_chain);
4203 }
4204
4205 static struct serial *
4206 remote_serial_open (const char *name)
4207 {
4208   static int udp_warning = 0;
4209
4210   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4211      of in ser-tcp.c, because it is the remote protocol assuming that the
4212      serial connection is reliable and not the serial connection promising
4213      to be.  */
4214   if (!udp_warning && startswith (name, "udp:"))
4215     {
4216       warning (_("The remote protocol may be unreliable over UDP.\n"
4217                  "Some events may be lost, rendering further debugging "
4218                  "impossible."));
4219       udp_warning = 1;
4220     }
4221
4222   return serial_open (name);
4223 }
4224
4225 /* Inform the target of our permission settings.  The permission flags
4226    work without this, but if the target knows the settings, it can do
4227    a couple things.  First, it can add its own check, to catch cases
4228    that somehow manage to get by the permissions checks in target
4229    methods.  Second, if the target is wired to disallow particular
4230    settings (for instance, a system in the field that is not set up to
4231    be able to stop at a breakpoint), it can object to any unavailable
4232    permissions.  */
4233
4234 void
4235 remote_set_permissions (struct target_ops *self)
4236 {
4237   struct remote_state *rs = get_remote_state ();
4238
4239   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4240              "WriteReg:%x;WriteMem:%x;"
4241              "InsertBreak:%x;InsertTrace:%x;"
4242              "InsertFastTrace:%x;Stop:%x",
4243              may_write_registers, may_write_memory,
4244              may_insert_breakpoints, may_insert_tracepoints,
4245              may_insert_fast_tracepoints, may_stop);
4246   putpkt (rs->buf);
4247   getpkt (&rs->buf, &rs->buf_size, 0);
4248
4249   /* If the target didn't like the packet, warn the user.  Do not try
4250      to undo the user's settings, that would just be maddening.  */
4251   if (strcmp (rs->buf, "OK") != 0)
4252     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4253 }
4254
4255 /* This type describes each known response to the qSupported
4256    packet.  */
4257 struct protocol_feature
4258 {
4259   /* The name of this protocol feature.  */
4260   const char *name;
4261
4262   /* The default for this protocol feature.  */
4263   enum packet_support default_support;
4264
4265   /* The function to call when this feature is reported, or after
4266      qSupported processing if the feature is not supported.
4267      The first argument points to this structure.  The second
4268      argument indicates whether the packet requested support be
4269      enabled, disabled, or probed (or the default, if this function
4270      is being called at the end of processing and this feature was
4271      not reported).  The third argument may be NULL; if not NULL, it
4272      is a NUL-terminated string taken from the packet following
4273      this feature's name and an equals sign.  */
4274   void (*func) (const struct protocol_feature *, enum packet_support,
4275                 const char *);
4276
4277   /* The corresponding packet for this feature.  Only used if
4278      FUNC is remote_supported_packet.  */
4279   int packet;
4280 };
4281
4282 static void
4283 remote_supported_packet (const struct protocol_feature *feature,
4284                          enum packet_support support,
4285                          const char *argument)
4286 {
4287   if (argument)
4288     {
4289       warning (_("Remote qSupported response supplied an unexpected value for"
4290                  " \"%s\"."), feature->name);
4291       return;
4292     }
4293
4294   remote_protocol_packets[feature->packet].support = support;
4295 }
4296
4297 static void
4298 remote_packet_size (const struct protocol_feature *feature,
4299                     enum packet_support support, const char *value)
4300 {
4301   struct remote_state *rs = get_remote_state ();
4302
4303   int packet_size;
4304   char *value_end;
4305
4306   if (support != PACKET_ENABLE)
4307     return;
4308
4309   if (value == NULL || *value == '\0')
4310     {
4311       warning (_("Remote target reported \"%s\" without a size."),
4312                feature->name);
4313       return;
4314     }
4315
4316   errno = 0;
4317   packet_size = strtol (value, &value_end, 16);
4318   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4319     {
4320       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4321                feature->name, value);
4322       return;
4323     }
4324
4325   /* Record the new maximum packet size.  */
4326   rs->explicit_packet_size = packet_size;
4327 }
4328
4329 static const struct protocol_feature remote_protocol_features[] = {
4330   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4331   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4332     PACKET_qXfer_auxv },
4333   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4334     PACKET_qXfer_exec_file },
4335   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4336     PACKET_qXfer_features },
4337   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4338     PACKET_qXfer_libraries },
4339   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4340     PACKET_qXfer_libraries_svr4 },
4341   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4342     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4343   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4344     PACKET_qXfer_memory_map },
4345   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4346     PACKET_qXfer_spu_read },
4347   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4348     PACKET_qXfer_spu_write },
4349   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4350     PACKET_qXfer_osdata },
4351   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4352     PACKET_qXfer_threads },
4353   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4354     PACKET_qXfer_traceframe_info },
4355   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4356     PACKET_QPassSignals },
4357   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4358     PACKET_QProgramSignals },
4359   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4360     PACKET_QStartNoAckMode },
4361   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4362     PACKET_multiprocess_feature },
4363   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4364   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4365     PACKET_qXfer_siginfo_read },
4366   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4367     PACKET_qXfer_siginfo_write },
4368   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4369     PACKET_ConditionalTracepoints },
4370   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4371     PACKET_ConditionalBreakpoints },
4372   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4373     PACKET_BreakpointCommands },
4374   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4375     PACKET_FastTracepoints },
4376   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4377     PACKET_StaticTracepoints },
4378   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4379    PACKET_InstallInTrace},
4380   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4381     PACKET_DisconnectedTracing_feature },
4382   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4383     PACKET_bc },
4384   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4385     PACKET_bs },
4386   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4387     PACKET_TracepointSource },
4388   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4389     PACKET_QAllow },
4390   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4391     PACKET_EnableDisableTracepoints_feature },
4392   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4393     PACKET_qXfer_fdpic },
4394   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4395     PACKET_qXfer_uib },
4396   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4397     PACKET_QDisableRandomization },
4398   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4399   { "QTBuffer:size", PACKET_DISABLE,
4400     remote_supported_packet, PACKET_QTBuffer_size},
4401   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4402   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4403   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4404   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4405   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4406     PACKET_qXfer_btrace },
4407   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4408     PACKET_qXfer_btrace_conf },
4409   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4410     PACKET_Qbtrace_conf_bts_size },
4411   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4412   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4413   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4414     PACKET_fork_event_feature },
4415   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4416     PACKET_vfork_event_feature },
4417   { "exec-events", PACKET_DISABLE, remote_supported_packet,
4418     PACKET_exec_event_feature },
4419   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4420     PACKET_Qbtrace_conf_pt_size },
4421   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported }
4422 };
4423
4424 static char *remote_support_xml;
4425
4426 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4427
4428 void
4429 register_remote_support_xml (const char *xml)
4430 {
4431 #if defined(HAVE_LIBEXPAT)
4432   if (remote_support_xml == NULL)
4433     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4434   else
4435     {
4436       char *copy = xstrdup (remote_support_xml + 13);
4437       char *p = strtok (copy, ",");
4438
4439       do
4440         {
4441           if (strcmp (p, xml) == 0)
4442             {
4443               /* already there */
4444               xfree (copy);
4445               return;
4446             }
4447         }
4448       while ((p = strtok (NULL, ",")) != NULL);
4449       xfree (copy);
4450
4451       remote_support_xml = reconcat (remote_support_xml,
4452                                      remote_support_xml, ",", xml,
4453                                      (char *) NULL);
4454     }
4455 #endif
4456 }
4457
4458 static char *
4459 remote_query_supported_append (char *msg, const char *append)
4460 {
4461   if (msg)
4462     return reconcat (msg, msg, ";", append, (char *) NULL);
4463   else
4464     return xstrdup (append);
4465 }
4466
4467 static void
4468 remote_query_supported (void)
4469 {
4470   struct remote_state *rs = get_remote_state ();
4471   char *next;
4472   int i;
4473   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4474
4475   /* The packet support flags are handled differently for this packet
4476      than for most others.  We treat an error, a disabled packet, and
4477      an empty response identically: any features which must be reported
4478      to be used will be automatically disabled.  An empty buffer
4479      accomplishes this, since that is also the representation for a list
4480      containing no features.  */
4481
4482   rs->buf[0] = 0;
4483   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4484     {
4485       char *q = NULL;
4486       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4487
4488       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4489         q = remote_query_supported_append (q, "multiprocess+");
4490
4491       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4492         q = remote_query_supported_append (q, "swbreak+");
4493       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4494         q = remote_query_supported_append (q, "hwbreak+");
4495
4496       q = remote_query_supported_append (q, "qRelocInsn+");
4497
4498       if (rs->extended)
4499         {
4500           if (packet_set_cmd_state (PACKET_fork_event_feature)
4501               != AUTO_BOOLEAN_FALSE)
4502             q = remote_query_supported_append (q, "fork-events+");
4503           if (packet_set_cmd_state (PACKET_vfork_event_feature)
4504               != AUTO_BOOLEAN_FALSE)
4505             q = remote_query_supported_append (q, "vfork-events+");
4506           if (packet_set_cmd_state (PACKET_exec_event_feature)
4507               != AUTO_BOOLEAN_FALSE)
4508             q = remote_query_supported_append (q, "exec-events+");
4509         }
4510
4511       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4512         q = remote_query_supported_append (q, "vContSupported+");
4513
4514       /* Keep this one last to work around a gdbserver <= 7.10 bug in
4515          the qSupported:xmlRegisters=i386 handling.  */
4516       if (remote_support_xml != NULL)
4517         q = remote_query_supported_append (q, remote_support_xml);
4518
4519       q = reconcat (q, "qSupported:", q, (char *) NULL);
4520       putpkt (q);
4521
4522       do_cleanups (old_chain);
4523
4524       getpkt (&rs->buf, &rs->buf_size, 0);
4525
4526       /* If an error occured, warn, but do not return - just reset the
4527          buffer to empty and go on to disable features.  */
4528       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4529           == PACKET_ERROR)
4530         {
4531           warning (_("Remote failure reply: %s"), rs->buf);
4532           rs->buf[0] = 0;
4533         }
4534     }
4535
4536   memset (seen, 0, sizeof (seen));
4537
4538   next = rs->buf;
4539   while (*next)
4540     {
4541       enum packet_support is_supported;
4542       char *p, *end, *name_end, *value;
4543
4544       /* First separate out this item from the rest of the packet.  If
4545          there's another item after this, we overwrite the separator
4546          (terminated strings are much easier to work with).  */
4547       p = next;
4548       end = strchr (p, ';');
4549       if (end == NULL)
4550         {
4551           end = p + strlen (p);
4552           next = end;
4553         }
4554       else
4555         {
4556           *end = '\0';
4557           next = end + 1;
4558
4559           if (end == p)
4560             {
4561               warning (_("empty item in \"qSupported\" response"));
4562               continue;
4563             }
4564         }
4565
4566       name_end = strchr (p, '=');
4567       if (name_end)
4568         {
4569           /* This is a name=value entry.  */
4570           is_supported = PACKET_ENABLE;
4571           value = name_end + 1;
4572           *name_end = '\0';
4573         }
4574       else
4575         {
4576           value = NULL;
4577           switch (end[-1])
4578             {
4579             case '+':
4580               is_supported = PACKET_ENABLE;
4581               break;
4582
4583             case '-':
4584               is_supported = PACKET_DISABLE;
4585               break;
4586
4587             case '?':
4588               is_supported = PACKET_SUPPORT_UNKNOWN;
4589               break;
4590
4591             default:
4592               warning (_("unrecognized item \"%s\" "
4593                          "in \"qSupported\" response"), p);
4594               continue;
4595             }
4596           end[-1] = '\0';
4597         }
4598
4599       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4600         if (strcmp (remote_protocol_features[i].name, p) == 0)
4601           {
4602             const struct protocol_feature *feature;
4603
4604             seen[i] = 1;
4605             feature = &remote_protocol_features[i];
4606             feature->func (feature, is_supported, value);
4607             break;
4608           }
4609     }
4610
4611   /* If we increased the packet size, make sure to increase the global
4612      buffer size also.  We delay this until after parsing the entire
4613      qSupported packet, because this is the same buffer we were
4614      parsing.  */
4615   if (rs->buf_size < rs->explicit_packet_size)
4616     {
4617       rs->buf_size = rs->explicit_packet_size;
4618       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4619     }
4620
4621   /* Handle the defaults for unmentioned features.  */
4622   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4623     if (!seen[i])
4624       {
4625         const struct protocol_feature *feature;
4626
4627         feature = &remote_protocol_features[i];
4628         feature->func (feature, feature->default_support, NULL);
4629       }
4630 }
4631
4632 /* Remove any of the remote.c targets from target stack.  Upper targets depend
4633    on it so remove them first.  */
4634
4635 static void
4636 remote_unpush_target (void)
4637 {
4638   pop_all_targets_at_and_above (process_stratum);
4639 }
4640
4641 static void
4642 remote_open_1 (const char *name, int from_tty,
4643                struct target_ops *target, int extended_p)
4644 {
4645   struct remote_state *rs = get_remote_state ();
4646
4647   if (name == 0)
4648     error (_("To open a remote debug connection, you need to specify what\n"
4649            "serial device is attached to the remote system\n"
4650            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4651
4652   /* See FIXME above.  */
4653   if (!target_async_permitted)
4654     wait_forever_enabled_p = 1;
4655
4656   /* If we're connected to a running target, target_preopen will kill it.
4657      Ask this question first, before target_preopen has a chance to kill
4658      anything.  */
4659   if (rs->remote_desc != NULL && !have_inferiors ())
4660     {
4661       if (from_tty
4662           && !query (_("Already connected to a remote target.  Disconnect? ")))
4663         error (_("Still connected."));
4664     }
4665
4666   /* Here the possibly existing remote target gets unpushed.  */
4667   target_preopen (from_tty);
4668
4669   /* Make sure we send the passed signals list the next time we resume.  */
4670   xfree (rs->last_pass_packet);
4671   rs->last_pass_packet = NULL;
4672
4673   /* Make sure we send the program signals list the next time we
4674      resume.  */
4675   xfree (rs->last_program_signals_packet);
4676   rs->last_program_signals_packet = NULL;
4677
4678   remote_fileio_reset ();
4679   reopen_exec_file ();
4680   reread_symbols ();
4681
4682   rs->remote_desc = remote_serial_open (name);
4683   if (!rs->remote_desc)
4684     perror_with_name (name);
4685
4686   if (baud_rate != -1)
4687     {
4688       if (serial_setbaudrate (rs->remote_desc, baud_rate))
4689         {
4690           /* The requested speed could not be set.  Error out to
4691              top level after closing remote_desc.  Take care to
4692              set remote_desc to NULL to avoid closing remote_desc
4693              more than once.  */
4694           serial_close (rs->remote_desc);
4695           rs->remote_desc = NULL;
4696           perror_with_name (name);
4697         }
4698     }
4699
4700   serial_setparity (rs->remote_desc, serial_parity);
4701   serial_raw (rs->remote_desc);
4702
4703   /* If there is something sitting in the buffer we might take it as a
4704      response to a command, which would be bad.  */
4705   serial_flush_input (rs->remote_desc);
4706
4707   if (from_tty)
4708     {
4709       puts_filtered ("Remote debugging using ");
4710       puts_filtered (name);
4711       puts_filtered ("\n");
4712     }
4713   push_target (target);         /* Switch to using remote target now.  */
4714
4715   /* Register extra event sources in the event loop.  */
4716   remote_async_inferior_event_token
4717     = create_async_event_handler (remote_async_inferior_event_handler,
4718                                   NULL);
4719   rs->notif_state = remote_notif_state_allocate ();
4720
4721   /* Reset the target state; these things will be queried either by
4722      remote_query_supported or as they are needed.  */
4723   reset_all_packet_configs_support ();
4724   rs->cached_wait_status = 0;
4725   rs->explicit_packet_size = 0;
4726   rs->noack_mode = 0;
4727   rs->extended = extended_p;
4728   rs->waiting_for_stop_reply = 0;
4729   rs->ctrlc_pending_p = 0;
4730
4731   rs->general_thread = not_sent_ptid;
4732   rs->continue_thread = not_sent_ptid;
4733   rs->remote_traceframe_number = -1;
4734
4735   /* Probe for ability to use "ThreadInfo" query, as required.  */
4736   rs->use_threadinfo_query = 1;
4737   rs->use_threadextra_query = 1;
4738
4739   readahead_cache_invalidate ();
4740
4741   if (target_async_permitted)
4742     {
4743       /* With this target we start out by owning the terminal.  */
4744       remote_async_terminal_ours_p = 1;
4745
4746       /* FIXME: cagney/1999-09-23: During the initial connection it is
4747          assumed that the target is already ready and able to respond to
4748          requests.  Unfortunately remote_start_remote() eventually calls
4749          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
4750          around this.  Eventually a mechanism that allows
4751          wait_for_inferior() to expect/get timeouts will be
4752          implemented.  */
4753       wait_forever_enabled_p = 0;
4754     }
4755
4756   /* First delete any symbols previously loaded from shared libraries.  */
4757   no_shared_libraries (NULL, 0);
4758
4759   /* Start afresh.  */
4760   init_thread_list ();
4761
4762   /* Start the remote connection.  If error() or QUIT, discard this
4763      target (we'd otherwise be in an inconsistent state) and then
4764      propogate the error on up the exception chain.  This ensures that
4765      the caller doesn't stumble along blindly assuming that the
4766      function succeeded.  The CLI doesn't have this problem but other
4767      UI's, such as MI do.
4768
4769      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4770      this function should return an error indication letting the
4771      caller restore the previous state.  Unfortunately the command
4772      ``target remote'' is directly wired to this function making that
4773      impossible.  On a positive note, the CLI side of this problem has
4774      been fixed - the function set_cmd_context() makes it possible for
4775      all the ``target ....'' commands to share a common callback
4776      function.  See cli-dump.c.  */
4777   {
4778
4779     TRY
4780       {
4781         remote_start_remote (from_tty, target, extended_p);
4782       }
4783     CATCH (ex, RETURN_MASK_ALL)
4784       {
4785         /* Pop the partially set up target - unless something else did
4786            already before throwing the exception.  */
4787         if (rs->remote_desc != NULL)
4788           remote_unpush_target ();
4789         if (target_async_permitted)
4790           wait_forever_enabled_p = 1;
4791         throw_exception (ex);
4792       }
4793     END_CATCH
4794   }
4795
4796   remote_btrace_reset ();
4797
4798   if (target_async_permitted)
4799     wait_forever_enabled_p = 1;
4800 }
4801
4802 /* Detach the specified process.  */
4803
4804 static void
4805 remote_detach_pid (int pid)
4806 {
4807   struct remote_state *rs = get_remote_state ();
4808
4809   if (remote_multi_process_p (rs))
4810     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4811   else
4812     strcpy (rs->buf, "D");
4813
4814   putpkt (rs->buf);
4815   getpkt (&rs->buf, &rs->buf_size, 0);
4816
4817   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4818     ;
4819   else if (rs->buf[0] == '\0')
4820     error (_("Remote doesn't know how to detach"));
4821   else
4822     error (_("Can't detach process."));
4823 }
4824
4825 /* This detaches a program to which we previously attached, using
4826    inferior_ptid to identify the process.  After this is done, GDB
4827    can be used to debug some other program.  We better not have left
4828    any breakpoints in the target program or it'll die when it hits
4829    one.  */
4830
4831 static void
4832 remote_detach_1 (const char *args, int from_tty)
4833 {
4834   int pid = ptid_get_pid (inferior_ptid);
4835   struct remote_state *rs = get_remote_state ();
4836   struct thread_info *tp = find_thread_ptid (inferior_ptid);
4837   int is_fork_parent;
4838
4839   if (args)
4840     error (_("Argument given to \"detach\" when remotely debugging."));
4841
4842   if (!target_has_execution)
4843     error (_("No process to detach from."));
4844
4845   if (from_tty)
4846     {
4847       char *exec_file = get_exec_file (0);
4848       if (exec_file == NULL)
4849         exec_file = "";
4850       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4851                          target_pid_to_str (pid_to_ptid (pid)));
4852       gdb_flush (gdb_stdout);
4853     }
4854
4855   /* Tell the remote target to detach.  */
4856   remote_detach_pid (pid);
4857
4858   if (from_tty && !rs->extended)
4859     puts_filtered (_("Ending remote debugging.\n"));
4860
4861   /* Check to see if we are detaching a fork parent.  Note that if we
4862      are detaching a fork child, tp == NULL.  */
4863   is_fork_parent = (tp != NULL
4864                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4865
4866   /* If doing detach-on-fork, we don't mourn, because that will delete
4867      breakpoints that should be available for the followed inferior.  */
4868   if (!is_fork_parent)
4869     target_mourn_inferior ();
4870   else
4871     {
4872       inferior_ptid = null_ptid;
4873       detach_inferior (pid);
4874     }
4875 }
4876
4877 static void
4878 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4879 {
4880   remote_detach_1 (args, from_tty);
4881 }
4882
4883 static void
4884 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4885 {
4886   remote_detach_1 (args, from_tty);
4887 }
4888
4889 /* Target follow-fork function for remote targets.  On entry, and
4890    at return, the current inferior is the fork parent.
4891
4892    Note that although this is currently only used for extended-remote,
4893    it is named remote_follow_fork in anticipation of using it for the
4894    remote target as well.  */
4895
4896 static int
4897 remote_follow_fork (struct target_ops *ops, int follow_child,
4898                     int detach_fork)
4899 {
4900   struct remote_state *rs = get_remote_state ();
4901   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
4902
4903   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4904       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
4905     {
4906       /* When following the parent and detaching the child, we detach
4907          the child here.  For the case of following the child and
4908          detaching the parent, the detach is done in the target-
4909          independent follow fork code in infrun.c.  We can't use
4910          target_detach when detaching an unfollowed child because
4911          the client side doesn't know anything about the child.  */
4912       if (detach_fork && !follow_child)
4913         {
4914           /* Detach the fork child.  */
4915           ptid_t child_ptid;
4916           pid_t child_pid;
4917
4918           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4919           child_pid = ptid_get_pid (child_ptid);
4920
4921           remote_detach_pid (child_pid);
4922           detach_inferior (child_pid);
4923         }
4924     }
4925   return 0;
4926 }
4927
4928 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
4929    in the program space of the new inferior.  On entry and at return the
4930    current inferior is the exec'ing inferior.  INF is the new exec'd
4931    inferior, which may be the same as the exec'ing inferior unless
4932    follow-exec-mode is "new".  */
4933
4934 static void
4935 remote_follow_exec (struct target_ops *ops,
4936                     struct inferior *inf, char *execd_pathname)
4937 {
4938   /* We know that this is a target file name, so if it has the "target:"
4939      prefix we strip it off before saving it in the program space.  */
4940   if (is_target_filename (execd_pathname))
4941     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
4942
4943   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
4944 }
4945
4946 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
4947
4948 static void
4949 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4950 {
4951   if (args)
4952     error (_("Argument given to \"disconnect\" when remotely debugging."));
4953
4954   /* Make sure we unpush even the extended remote targets; mourn
4955      won't do it.  So call remote_mourn directly instead of
4956      target_mourn_inferior.  */
4957   remote_mourn (target);
4958
4959   if (from_tty)
4960     puts_filtered ("Ending remote debugging.\n");
4961 }
4962
4963 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
4964    be chatty about it.  */
4965
4966 static void
4967 extended_remote_attach (struct target_ops *target, const char *args,
4968                         int from_tty)
4969 {
4970   struct remote_state *rs = get_remote_state ();
4971   int pid;
4972   char *wait_status = NULL;
4973
4974   pid = parse_pid_to_attach (args);
4975
4976   /* Remote PID can be freely equal to getpid, do not check it here the same
4977      way as in other targets.  */
4978
4979   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4980     error (_("This target does not support attaching to a process"));
4981
4982   if (from_tty)
4983     {
4984       char *exec_file = get_exec_file (0);
4985
4986       if (exec_file)
4987         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4988                            target_pid_to_str (pid_to_ptid (pid)));
4989       else
4990         printf_unfiltered (_("Attaching to %s\n"),
4991                            target_pid_to_str (pid_to_ptid (pid)));
4992
4993       gdb_flush (gdb_stdout);
4994     }
4995
4996   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4997   putpkt (rs->buf);
4998   getpkt (&rs->buf, &rs->buf_size, 0);
4999
5000   switch (packet_ok (rs->buf,
5001                      &remote_protocol_packets[PACKET_vAttach]))
5002     {
5003     case PACKET_OK:
5004       if (!non_stop)
5005         {
5006           /* Save the reply for later.  */
5007           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5008           strcpy (wait_status, rs->buf);
5009         }
5010       else if (strcmp (rs->buf, "OK") != 0)
5011         error (_("Attaching to %s failed with: %s"),
5012                target_pid_to_str (pid_to_ptid (pid)),
5013                rs->buf);
5014       break;
5015     case PACKET_UNKNOWN:
5016       error (_("This target does not support attaching to a process"));
5017     default:
5018       error (_("Attaching to %s failed"),
5019              target_pid_to_str (pid_to_ptid (pid)));
5020     }
5021
5022   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5023
5024   inferior_ptid = pid_to_ptid (pid);
5025
5026   if (non_stop)
5027     {
5028       struct thread_info *thread;
5029
5030       /* Get list of threads.  */
5031       remote_update_thread_list (target);
5032
5033       thread = first_thread_of_process (pid);
5034       if (thread)
5035         inferior_ptid = thread->ptid;
5036       else
5037         inferior_ptid = pid_to_ptid (pid);
5038
5039       /* Invalidate our notion of the remote current thread.  */
5040       record_currthread (rs, minus_one_ptid);
5041     }
5042   else
5043     {
5044       /* Now, if we have thread information, update inferior_ptid.  */
5045       inferior_ptid = remote_current_thread (inferior_ptid);
5046
5047       /* Add the main thread to the thread list.  */
5048       add_thread_silent (inferior_ptid);
5049     }
5050
5051   /* Next, if the target can specify a description, read it.  We do
5052      this before anything involving memory or registers.  */
5053   target_find_description ();
5054
5055   if (!non_stop)
5056     {
5057       /* Use the previously fetched status.  */
5058       gdb_assert (wait_status != NULL);
5059
5060       if (target_can_async_p ())
5061         {
5062           struct notif_event *reply
5063             =  remote_notif_parse (&notif_client_stop, wait_status);
5064
5065           push_stop_reply ((struct stop_reply *) reply);
5066
5067           target_async (1);
5068         }
5069       else
5070         {
5071           gdb_assert (wait_status != NULL);
5072           strcpy (rs->buf, wait_status);
5073           rs->cached_wait_status = 1;
5074         }
5075     }
5076   else
5077     gdb_assert (wait_status == NULL);
5078 }
5079
5080 /* Implementation of the to_post_attach method.  */
5081
5082 static void
5083 extended_remote_post_attach (struct target_ops *ops, int pid)
5084 {
5085   /* In certain cases GDB might not have had the chance to start
5086      symbol lookup up until now.  This could happen if the debugged
5087      binary is not using shared libraries, the vsyscall page is not
5088      present (on Linux) and the binary itself hadn't changed since the
5089      debugging process was started.  */
5090   if (symfile_objfile != NULL)
5091     remote_check_symbols();
5092 }
5093
5094 \f
5095 /* Check for the availability of vCont.  This function should also check
5096    the response.  */
5097
5098 static void
5099 remote_vcont_probe (struct remote_state *rs)
5100 {
5101   char *buf;
5102
5103   strcpy (rs->buf, "vCont?");
5104   putpkt (rs->buf);
5105   getpkt (&rs->buf, &rs->buf_size, 0);
5106   buf = rs->buf;
5107
5108   /* Make sure that the features we assume are supported.  */
5109   if (startswith (buf, "vCont"))
5110     {
5111       char *p = &buf[5];
5112       int support_c, support_C;
5113
5114       rs->supports_vCont.s = 0;
5115       rs->supports_vCont.S = 0;
5116       support_c = 0;
5117       support_C = 0;
5118       rs->supports_vCont.t = 0;
5119       rs->supports_vCont.r = 0;
5120       while (p && *p == ';')
5121         {
5122           p++;
5123           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5124             rs->supports_vCont.s = 1;
5125           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5126             rs->supports_vCont.S = 1;
5127           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5128             support_c = 1;
5129           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5130             support_C = 1;
5131           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5132             rs->supports_vCont.t = 1;
5133           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5134             rs->supports_vCont.r = 1;
5135
5136           p = strchr (p, ';');
5137         }
5138
5139       /* If c, and C are not all supported, we can't use vCont.  Clearing
5140          BUF will make packet_ok disable the packet.  */
5141       if (!support_c || !support_C)
5142         buf[0] = 0;
5143     }
5144
5145   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5146 }
5147
5148 /* Helper function for building "vCont" resumptions.  Write a
5149    resumption to P.  ENDP points to one-passed-the-end of the buffer
5150    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5151    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5152    resumed thread should be single-stepped and/or signalled.  If PTID
5153    equals minus_one_ptid, then all threads are resumed; if PTID
5154    represents a process, then all threads of the process are resumed;
5155    the thread to be stepped and/or signalled is given in the global
5156    INFERIOR_PTID.  */
5157
5158 static char *
5159 append_resumption (char *p, char *endp,
5160                    ptid_t ptid, int step, enum gdb_signal siggnal)
5161 {
5162   struct remote_state *rs = get_remote_state ();
5163
5164   if (step && siggnal != GDB_SIGNAL_0)
5165     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5166   else if (step
5167            /* GDB is willing to range step.  */
5168            && use_range_stepping
5169            /* Target supports range stepping.  */
5170            && rs->supports_vCont.r
5171            /* We don't currently support range stepping multiple
5172               threads with a wildcard (though the protocol allows it,
5173               so stubs shouldn't make an active effort to forbid
5174               it).  */
5175            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5176     {
5177       struct thread_info *tp;
5178
5179       if (ptid_equal (ptid, minus_one_ptid))
5180         {
5181           /* If we don't know about the target thread's tid, then
5182              we're resuming magic_null_ptid (see caller).  */
5183           tp = find_thread_ptid (magic_null_ptid);
5184         }
5185       else
5186         tp = find_thread_ptid (ptid);
5187       gdb_assert (tp != NULL);
5188
5189       if (tp->control.may_range_step)
5190         {
5191           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5192
5193           p += xsnprintf (p, endp - p, ";r%s,%s",
5194                           phex_nz (tp->control.step_range_start,
5195                                    addr_size),
5196                           phex_nz (tp->control.step_range_end,
5197                                    addr_size));
5198         }
5199       else
5200         p += xsnprintf (p, endp - p, ";s");
5201     }
5202   else if (step)
5203     p += xsnprintf (p, endp - p, ";s");
5204   else if (siggnal != GDB_SIGNAL_0)
5205     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5206   else
5207     p += xsnprintf (p, endp - p, ";c");
5208
5209   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5210     {
5211       ptid_t nptid;
5212
5213       /* All (-1) threads of process.  */
5214       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5215
5216       p += xsnprintf (p, endp - p, ":");
5217       p = write_ptid (p, endp, nptid);
5218     }
5219   else if (!ptid_equal (ptid, minus_one_ptid))
5220     {
5221       p += xsnprintf (p, endp - p, ":");
5222       p = write_ptid (p, endp, ptid);
5223     }
5224
5225   return p;
5226 }
5227
5228 /* Append a vCont continue-with-signal action for threads that have a
5229    non-zero stop signal.  */
5230
5231 static char *
5232 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5233 {
5234   struct thread_info *thread;
5235
5236   ALL_NON_EXITED_THREADS (thread)
5237     if (ptid_match (thread->ptid, ptid)
5238         && !ptid_equal (inferior_ptid, thread->ptid)
5239         && thread->suspend.stop_signal != GDB_SIGNAL_0)
5240       {
5241         p = append_resumption (p, endp, thread->ptid,
5242                                0, thread->suspend.stop_signal);
5243         thread->suspend.stop_signal = GDB_SIGNAL_0;
5244       }
5245
5246   return p;
5247 }
5248
5249 /* Resume the remote inferior by using a "vCont" packet.  The thread
5250    to be resumed is PTID; STEP and SIGGNAL indicate whether the
5251    resumed thread should be single-stepped and/or signalled.  If PTID
5252    equals minus_one_ptid, then all threads are resumed; the thread to
5253    be stepped and/or signalled is given in the global INFERIOR_PTID.
5254    This function returns non-zero iff it resumes the inferior.
5255
5256    This function issues a strict subset of all possible vCont commands at the
5257    moment.  */
5258
5259 static int
5260 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5261 {
5262   struct remote_state *rs = get_remote_state ();
5263   char *p;
5264   char *endp;
5265
5266   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5267     remote_vcont_probe (rs);
5268
5269   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5270     return 0;
5271
5272   p = rs->buf;
5273   endp = rs->buf + get_remote_packet_size ();
5274
5275   /* If we could generate a wider range of packets, we'd have to worry
5276      about overflowing BUF.  Should there be a generic
5277      "multi-part-packet" packet?  */
5278
5279   p += xsnprintf (p, endp - p, "vCont");
5280
5281   if (ptid_equal (ptid, magic_null_ptid))
5282     {
5283       /* MAGIC_NULL_PTID means that we don't have any active threads,
5284          so we don't have any TID numbers the inferior will
5285          understand.  Make sure to only send forms that do not specify
5286          a TID.  */
5287       append_resumption (p, endp, minus_one_ptid, step, siggnal);
5288     }
5289   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5290     {
5291       /* Resume all threads (of all processes, or of a single
5292          process), with preference for INFERIOR_PTID.  This assumes
5293          inferior_ptid belongs to the set of all threads we are about
5294          to resume.  */
5295       if (step || siggnal != GDB_SIGNAL_0)
5296         {
5297           /* Step inferior_ptid, with or without signal.  */
5298           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5299         }
5300
5301       /* Also pass down any pending signaled resumption for other
5302          threads not the current.  */
5303       p = append_pending_thread_resumptions (p, endp, ptid);
5304
5305       /* And continue others without a signal.  */
5306       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5307     }
5308   else
5309     {
5310       /* Scheduler locking; resume only PTID.  */
5311       append_resumption (p, endp, ptid, step, siggnal);
5312     }
5313
5314   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5315   putpkt (rs->buf);
5316
5317   if (non_stop)
5318     {
5319       /* In non-stop, the stub replies to vCont with "OK".  The stop
5320          reply will be reported asynchronously by means of a `%Stop'
5321          notification.  */
5322       getpkt (&rs->buf, &rs->buf_size, 0);
5323       if (strcmp (rs->buf, "OK") != 0)
5324         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5325     }
5326
5327   return 1;
5328 }
5329
5330 /* Tell the remote machine to resume.  */
5331
5332 static void
5333 remote_resume (struct target_ops *ops,
5334                ptid_t ptid, int step, enum gdb_signal siggnal)
5335 {
5336   struct remote_state *rs = get_remote_state ();
5337   char *buf;
5338
5339   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5340      (explained in remote-notif.c:handle_notification) so
5341      remote_notif_process is not called.  We need find a place where
5342      it is safe to start a 'vNotif' sequence.  It is good to do it
5343      before resuming inferior, because inferior was stopped and no RSP
5344      traffic at that moment.  */
5345   if (!non_stop)
5346     remote_notif_process (rs->notif_state, &notif_client_stop);
5347
5348   rs->last_sent_signal = siggnal;
5349   rs->last_sent_step = step;
5350
5351   /* The vCont packet doesn't need to specify threads via Hc.  */
5352   /* No reverse support (yet) for vCont.  */
5353   if (execution_direction != EXEC_REVERSE)
5354     if (remote_vcont_resume (ptid, step, siggnal))
5355       goto done;
5356
5357   /* All other supported resume packets do use Hc, so set the continue
5358      thread.  */
5359   if (ptid_equal (ptid, minus_one_ptid))
5360     set_continue_thread (any_thread_ptid);
5361   else
5362     set_continue_thread (ptid);
5363
5364   buf = rs->buf;
5365   if (execution_direction == EXEC_REVERSE)
5366     {
5367       /* We don't pass signals to the target in reverse exec mode.  */
5368       if (info_verbose && siggnal != GDB_SIGNAL_0)
5369         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5370                  siggnal);
5371
5372       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5373         error (_("Remote reverse-step not supported."));
5374       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5375         error (_("Remote reverse-continue not supported."));
5376
5377       strcpy (buf, step ? "bs" : "bc");
5378     }
5379   else if (siggnal != GDB_SIGNAL_0)
5380     {
5381       buf[0] = step ? 'S' : 'C';
5382       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5383       buf[2] = tohex (((int) siggnal) & 0xf);
5384       buf[3] = '\0';
5385     }
5386   else
5387     strcpy (buf, step ? "s" : "c");
5388
5389   putpkt (buf);
5390
5391  done:
5392   /* We are about to start executing the inferior, let's register it
5393      with the event loop.  NOTE: this is the one place where all the
5394      execution commands end up.  We could alternatively do this in each
5395      of the execution commands in infcmd.c.  */
5396   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5397      into infcmd.c in order to allow inferior function calls to work
5398      NOT asynchronously.  */
5399   if (target_can_async_p ())
5400     target_async (1);
5401
5402   /* We've just told the target to resume.  The remote server will
5403      wait for the inferior to stop, and then send a stop reply.  In
5404      the mean time, we can't start another command/query ourselves
5405      because the stub wouldn't be ready to process it.  This applies
5406      only to the base all-stop protocol, however.  In non-stop (which
5407      only supports vCont), the stub replies with an "OK", and is
5408      immediate able to process further serial input.  */
5409   if (!non_stop)
5410     rs->waiting_for_stop_reply = 1;
5411 }
5412 \f
5413
5414 /* Set up the signal handler for SIGINT, while the target is
5415    executing, ovewriting the 'regular' SIGINT signal handler.  */
5416 static void
5417 async_initialize_sigint_signal_handler (void)
5418 {
5419   signal (SIGINT, async_handle_remote_sigint);
5420 }
5421
5422 /* Signal handler for SIGINT, while the target is executing.  */
5423 static void
5424 async_handle_remote_sigint (int sig)
5425 {
5426   signal (sig, async_handle_remote_sigint_twice);
5427   /* Note we need to go through gdb_call_async_signal_handler in order
5428      to wake up the event loop on Windows.  */
5429   gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5430 }
5431
5432 /* Signal handler for SIGINT, installed after SIGINT has already been
5433    sent once.  It will take effect the second time that the user sends
5434    a ^C.  */
5435 static void
5436 async_handle_remote_sigint_twice (int sig)
5437 {
5438   signal (sig, async_handle_remote_sigint);
5439   /* See note in async_handle_remote_sigint.  */
5440   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5441 }
5442
5443 /* Implementation of to_check_pending_interrupt.  */
5444
5445 static void
5446 remote_check_pending_interrupt (struct target_ops *self)
5447 {
5448   struct async_signal_handler *token = async_sigint_remote_twice_token;
5449
5450   if (async_signal_handler_is_marked (token))
5451     {
5452       clear_async_signal_handler (token);
5453       call_async_signal_handler (token);
5454     }
5455 }
5456
5457 /* Perform the real interruption of the target execution, in response
5458    to a ^C.  */
5459 static void
5460 async_remote_interrupt (gdb_client_data arg)
5461 {
5462   if (remote_debug)
5463     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5464
5465   target_stop (inferior_ptid);
5466 }
5467
5468 /* Perform interrupt, if the first attempt did not succeed.  Just give
5469    up on the target alltogether.  */
5470 static void
5471 async_remote_interrupt_twice (gdb_client_data arg)
5472 {
5473   if (remote_debug)
5474     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5475
5476   interrupt_query ();
5477 }
5478
5479 /* Reinstall the usual SIGINT handlers, after the target has
5480    stopped.  */
5481 static void
5482 async_cleanup_sigint_signal_handler (void *dummy)
5483 {
5484   signal (SIGINT, handle_sigint);
5485 }
5486
5487 /* Send ^C to target to halt it.  Target will respond, and send us a
5488    packet.  */
5489 static void (*ofunc) (int);
5490
5491 /* The command line interface's interrupt routine.  This function is installed
5492    as a signal handler for SIGINT.  The first time a user requests an
5493    interrupt, we call remote_interrupt to send a break or ^C.  If there is no
5494    response from the target (it didn't stop when the user requested it),
5495    we ask the user if he'd like to detach from the target.  */
5496
5497 static void
5498 sync_remote_interrupt (int signo)
5499 {
5500   /* If this doesn't work, try more severe steps.  */
5501   signal (signo, sync_remote_interrupt_twice);
5502
5503   gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5504 }
5505
5506 /* The user typed ^C twice.  */
5507
5508 static void
5509 sync_remote_interrupt_twice (int signo)
5510 {
5511   signal (signo, ofunc);
5512   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5513   signal (signo, sync_remote_interrupt);
5514 }
5515
5516 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
5517    thread, all threads of a remote process, or all threads of all
5518    processes.  */
5519
5520 static void
5521 remote_stop_ns (ptid_t ptid)
5522 {
5523   struct remote_state *rs = get_remote_state ();
5524   char *p = rs->buf;
5525   char *endp = rs->buf + get_remote_packet_size ();
5526
5527   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5528     remote_vcont_probe (rs);
5529
5530   if (!rs->supports_vCont.t)
5531     error (_("Remote server does not support stopping threads"));
5532
5533   if (ptid_equal (ptid, minus_one_ptid)
5534       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5535     p += xsnprintf (p, endp - p, "vCont;t");
5536   else
5537     {
5538       ptid_t nptid;
5539
5540       p += xsnprintf (p, endp - p, "vCont;t:");
5541
5542       if (ptid_is_pid (ptid))
5543           /* All (-1) threads of process.  */
5544         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5545       else
5546         {
5547           /* Small optimization: if we already have a stop reply for
5548              this thread, no use in telling the stub we want this
5549              stopped.  */
5550           if (peek_stop_reply (ptid))
5551             return;
5552
5553           nptid = ptid;
5554         }
5555
5556       write_ptid (p, endp, nptid);
5557     }
5558
5559   /* In non-stop, we get an immediate OK reply.  The stop reply will
5560      come in asynchronously by notification.  */
5561   putpkt (rs->buf);
5562   getpkt (&rs->buf, &rs->buf_size, 0);
5563   if (strcmp (rs->buf, "OK") != 0)
5564     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5565 }
5566
5567 /* All-stop version of target_interrupt.  Sends a break or a ^C to
5568    interrupt the remote target.  It is undefined which thread of which
5569    process reports the interrupt.  */
5570
5571 static void
5572 remote_interrupt_as (ptid_t ptid)
5573 {
5574   struct remote_state *rs = get_remote_state ();
5575
5576   rs->ctrlc_pending_p = 1;
5577
5578   /* If the inferior is stopped already, but the core didn't know
5579      about it yet, just ignore the request.  The cached wait status
5580      will be collected in remote_wait.  */
5581   if (rs->cached_wait_status)
5582     return;
5583
5584   /* Send interrupt_sequence to remote target.  */
5585   send_interrupt_sequence ();
5586 }
5587
5588 /* Implement the to_stop function for the remote targets.  */
5589
5590 static void
5591 remote_stop (struct target_ops *self, ptid_t ptid)
5592 {
5593   if (remote_debug)
5594     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5595
5596   if (non_stop)
5597     remote_stop_ns (ptid);
5598   else
5599     {
5600       /* We don't currently have a way to transparently pause the
5601          remote target in all-stop mode.  Interrupt it instead.  */
5602       remote_interrupt_as (ptid);
5603     }
5604 }
5605
5606 /* Implement the to_interrupt function for the remote targets.  */
5607
5608 static void
5609 remote_interrupt (struct target_ops *self, ptid_t ptid)
5610 {
5611   if (remote_debug)
5612     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5613
5614   if (non_stop)
5615     {
5616       /* We don't currently have a way to ^C the remote target in
5617          non-stop mode.  Stop it (with no signal) instead.  */
5618       remote_stop_ns (ptid);
5619     }
5620   else
5621     remote_interrupt_as (ptid);
5622 }
5623
5624 /* Ask the user what to do when an interrupt is received.  */
5625
5626 static void
5627 interrupt_query (void)
5628 {
5629   struct remote_state *rs = get_remote_state ();
5630   struct cleanup *old_chain;
5631
5632   old_chain = make_cleanup_restore_target_terminal ();
5633   target_terminal_ours ();
5634
5635   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5636     {
5637       if (query (_("The target is not responding to interrupt requests.\n"
5638                    "Stop debugging it? ")))
5639         {
5640           remote_unpush_target ();
5641           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5642         }
5643     }
5644   else
5645     {
5646       if (query (_("Interrupted while waiting for the program.\n"
5647                    "Give up waiting? ")))
5648         quit ();
5649     }
5650
5651   do_cleanups (old_chain);
5652 }
5653
5654 /* Enable/disable target terminal ownership.  Most targets can use
5655    terminal groups to control terminal ownership.  Remote targets are
5656    different in that explicit transfer of ownership to/from GDB/target
5657    is required.  */
5658
5659 static void
5660 remote_terminal_inferior (struct target_ops *self)
5661 {
5662   if (!target_async_permitted)
5663     /* Nothing to do.  */
5664     return;
5665
5666   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5667      idempotent.  The event-loop GDB talking to an asynchronous target
5668      with a synchronous command calls this function from both
5669      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
5670      transfer the terminal to the target when it shouldn't this guard
5671      can go away.  */
5672   if (!remote_async_terminal_ours_p)
5673     return;
5674   delete_file_handler (input_fd);
5675   remote_async_terminal_ours_p = 0;
5676   async_initialize_sigint_signal_handler ();
5677   /* NOTE: At this point we could also register our selves as the
5678      recipient of all input.  Any characters typed could then be
5679      passed on down to the target.  */
5680 }
5681
5682 static void
5683 remote_terminal_ours (struct target_ops *self)
5684 {
5685   if (!target_async_permitted)
5686     /* Nothing to do.  */
5687     return;
5688
5689   /* See FIXME in remote_terminal_inferior.  */
5690   if (remote_async_terminal_ours_p)
5691     return;
5692   async_cleanup_sigint_signal_handler (NULL);
5693   add_file_handler (input_fd, stdin_event_handler, 0);
5694   remote_async_terminal_ours_p = 1;
5695 }
5696
5697 static void
5698 remote_console_output (char *msg)
5699 {
5700   char *p;
5701
5702   for (p = msg; p[0] && p[1]; p += 2)
5703     {
5704       char tb[2];
5705       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5706
5707       tb[0] = c;
5708       tb[1] = 0;
5709       fputs_unfiltered (tb, gdb_stdtarg);
5710     }
5711   gdb_flush (gdb_stdtarg);
5712 }
5713
5714 typedef struct cached_reg
5715 {
5716   int num;
5717   gdb_byte data[MAX_REGISTER_SIZE];
5718 } cached_reg_t;
5719
5720 DEF_VEC_O(cached_reg_t);
5721
5722 typedef struct stop_reply
5723 {
5724   struct notif_event base;
5725
5726   /* The identifier of the thread about this event  */
5727   ptid_t ptid;
5728
5729   /* The remote state this event is associated with.  When the remote
5730      connection, represented by a remote_state object, is closed,
5731      all the associated stop_reply events should be released.  */
5732   struct remote_state *rs;
5733
5734   struct target_waitstatus ws;
5735
5736   /* Expedited registers.  This makes remote debugging a bit more
5737      efficient for those targets that provide critical registers as
5738      part of their normal status mechanism (as another roundtrip to
5739      fetch them is avoided).  */
5740   VEC(cached_reg_t) *regcache;
5741
5742   enum target_stop_reason stop_reason;
5743
5744   CORE_ADDR watch_data_address;
5745
5746   int core;
5747 } *stop_reply_p;
5748
5749 DECLARE_QUEUE_P (stop_reply_p);
5750 DEFINE_QUEUE_P (stop_reply_p);
5751 /* The list of already fetched and acknowledged stop events.  This
5752    queue is used for notification Stop, and other notifications
5753    don't need queue for their events, because the notification events
5754    of Stop can't be consumed immediately, so that events should be
5755    queued first, and be consumed by remote_wait_{ns,as} one per
5756    time.  Other notifications can consume their events immediately,
5757    so queue is not needed for them.  */
5758 static QUEUE (stop_reply_p) *stop_reply_queue;
5759
5760 static void
5761 stop_reply_xfree (struct stop_reply *r)
5762 {
5763   notif_event_xfree ((struct notif_event *) r);
5764 }
5765
5766 /* Return the length of the stop reply queue.  */
5767
5768 static int
5769 stop_reply_queue_length (void)
5770 {
5771   return QUEUE_length (stop_reply_p, stop_reply_queue);
5772 }
5773
5774 static void
5775 remote_notif_stop_parse (struct notif_client *self, char *buf,
5776                          struct notif_event *event)
5777 {
5778   remote_parse_stop_reply (buf, (struct stop_reply *) event);
5779 }
5780
5781 static void
5782 remote_notif_stop_ack (struct notif_client *self, char *buf,
5783                        struct notif_event *event)
5784 {
5785   struct stop_reply *stop_reply = (struct stop_reply *) event;
5786
5787   /* acknowledge */
5788   putpkt ((char *) self->ack_command);
5789
5790   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5791       /* We got an unknown stop reply.  */
5792       error (_("Unknown stop reply"));
5793
5794   push_stop_reply (stop_reply);
5795 }
5796
5797 static int
5798 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5799 {
5800   /* We can't get pending events in remote_notif_process for
5801      notification stop, and we have to do this in remote_wait_ns
5802      instead.  If we fetch all queued events from stub, remote stub
5803      may exit and we have no chance to process them back in
5804      remote_wait_ns.  */
5805   mark_async_event_handler (remote_async_inferior_event_token);
5806   return 0;
5807 }
5808
5809 static void
5810 stop_reply_dtr (struct notif_event *event)
5811 {
5812   struct stop_reply *r = (struct stop_reply *) event;
5813
5814   VEC_free (cached_reg_t, r->regcache);
5815 }
5816
5817 static struct notif_event *
5818 remote_notif_stop_alloc_reply (void)
5819 {
5820   /* We cast to a pointer to the "base class".  */
5821   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
5822
5823   r->dtr = stop_reply_dtr;
5824
5825   return r;
5826 }
5827
5828 /* A client of notification Stop.  */
5829
5830 struct notif_client notif_client_stop =
5831 {
5832   "Stop",
5833   "vStopped",
5834   remote_notif_stop_parse,
5835   remote_notif_stop_ack,
5836   remote_notif_stop_can_get_pending_events,
5837   remote_notif_stop_alloc_reply,
5838   REMOTE_NOTIF_STOP,
5839 };
5840
5841 /* A parameter to pass data in and out.  */
5842
5843 struct queue_iter_param
5844 {
5845   void *input;
5846   struct stop_reply *output;
5847 };
5848
5849 /* Determine if THREAD is a pending fork parent thread.  ARG contains
5850    the pid of the process that owns the threads we want to check, or
5851    -1 if we want to check all threads.  */
5852
5853 static int
5854 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5855                         ptid_t thread_ptid)
5856 {
5857   if (ws->kind == TARGET_WAITKIND_FORKED
5858       || ws->kind == TARGET_WAITKIND_VFORKED)
5859     {
5860       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5861         return 1;
5862     }
5863
5864   return 0;
5865 }
5866
5867 /* Check whether EVENT is a fork event, and if it is, remove the
5868    fork child from the context list passed in DATA.  */
5869
5870 static int
5871 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5872                               QUEUE_ITER (stop_reply_p) *iter,
5873                               stop_reply_p event,
5874                               void *data)
5875 {
5876   struct queue_iter_param *param = (struct queue_iter_param *) data;
5877   struct threads_listing_context *context
5878     = (struct threads_listing_context *) param->input;
5879
5880   if (event->ws.kind == TARGET_WAITKIND_FORKED
5881       || event->ws.kind == TARGET_WAITKIND_VFORKED)
5882     {
5883       threads_listing_context_remove (&event->ws, context);
5884     }
5885
5886   return 1;
5887 }
5888
5889 /* If CONTEXT contains any fork child threads that have not been
5890    reported yet, remove them from the CONTEXT list.  If such a
5891    thread exists it is because we are stopped at a fork catchpoint
5892    and have not yet called follow_fork, which will set up the
5893    host-side data structures for the new process.  */
5894
5895 static void
5896 remove_new_fork_children (struct threads_listing_context *context)
5897 {
5898   struct thread_info * thread;
5899   int pid = -1;
5900   struct notif_client *notif = &notif_client_stop;
5901   struct queue_iter_param param;
5902
5903   /* For any threads stopped at a fork event, remove the corresponding
5904      fork child threads from the CONTEXT list.  */
5905   ALL_NON_EXITED_THREADS (thread)
5906     {
5907       struct target_waitstatus *ws = &thread->pending_follow;
5908
5909       if (is_pending_fork_parent (ws, pid, thread->ptid))
5910         {
5911           threads_listing_context_remove (ws, context);
5912         }
5913     }
5914
5915   /* Check for any pending fork events (not reported or processed yet)
5916      in process PID and remove those fork child threads from the
5917      CONTEXT list as well.  */
5918   remote_notif_get_pending_events (notif);
5919   param.input = context;
5920   param.output = NULL;
5921   QUEUE_iterate (stop_reply_p, stop_reply_queue,
5922                  remove_child_of_pending_fork, &param);
5923 }
5924
5925 /* Remove stop replies in the queue if its pid is equal to the given
5926    inferior's pid.  */
5927
5928 static int
5929 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5930                                 QUEUE_ITER (stop_reply_p) *iter,
5931                                 stop_reply_p event,
5932                                 void *data)
5933 {
5934   struct queue_iter_param *param = (struct queue_iter_param *) data;
5935   struct inferior *inf = (struct inferior *) param->input;
5936
5937   if (ptid_get_pid (event->ptid) == inf->pid)
5938     {
5939       stop_reply_xfree (event);
5940       QUEUE_remove_elem (stop_reply_p, q, iter);
5941     }
5942
5943   return 1;
5944 }
5945
5946 /* Discard all pending stop replies of inferior INF.  */
5947
5948 static void
5949 discard_pending_stop_replies (struct inferior *inf)
5950 {
5951   int i;
5952   struct queue_iter_param param;
5953   struct stop_reply *reply;
5954   struct remote_state *rs = get_remote_state ();
5955   struct remote_notif_state *rns = rs->notif_state;
5956
5957   /* This function can be notified when an inferior exists.  When the
5958      target is not remote, the notification state is NULL.  */
5959   if (rs->remote_desc == NULL)
5960     return;
5961
5962   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5963
5964   /* Discard the in-flight notification.  */
5965   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5966     {
5967       stop_reply_xfree (reply);
5968       rns->pending_event[notif_client_stop.id] = NULL;
5969     }
5970
5971   param.input = inf;
5972   param.output = NULL;
5973   /* Discard the stop replies we have already pulled with
5974      vStopped.  */
5975   QUEUE_iterate (stop_reply_p, stop_reply_queue,
5976                  remove_stop_reply_for_inferior, &param);
5977 }
5978
5979 /* If its remote state is equal to the given remote state,
5980    remove EVENT from the stop reply queue.  */
5981
5982 static int
5983 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5984                                    QUEUE_ITER (stop_reply_p) *iter,
5985                                    stop_reply_p event,
5986                                    void *data)
5987 {
5988   struct queue_iter_param *param = (struct queue_iter_param *) data;
5989   struct remote_state *rs = (struct remote_state *) param->input;
5990
5991   if (event->rs == rs)
5992     {
5993       stop_reply_xfree (event);
5994       QUEUE_remove_elem (stop_reply_p, q, iter);
5995     }
5996
5997   return 1;
5998 }
5999
6000 /* Discard the stop replies for RS in stop_reply_queue.  */
6001
6002 static void
6003 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6004 {
6005   struct queue_iter_param param;
6006
6007   param.input = rs;
6008   param.output = NULL;
6009   /* Discard the stop replies we have already pulled with
6010      vStopped.  */
6011   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6012                  remove_stop_reply_of_remote_state, &param);
6013 }
6014
6015 /* A parameter to pass data in and out.  */
6016
6017 static int
6018 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6019                                    QUEUE_ITER (stop_reply_p) *iter,
6020                                    stop_reply_p event,
6021                                    void *data)
6022 {
6023   struct queue_iter_param *param = (struct queue_iter_param *) data;
6024   ptid_t *ptid = (ptid_t *) param->input;
6025
6026   if (ptid_match (event->ptid, *ptid))
6027     {
6028       param->output = event;
6029       QUEUE_remove_elem (stop_reply_p, q, iter);
6030       return 0;
6031     }
6032
6033   return 1;
6034 }
6035
6036 /* Remove the first reply in 'stop_reply_queue' which matches
6037    PTID.  */
6038
6039 static struct stop_reply *
6040 remote_notif_remove_queued_reply (ptid_t ptid)
6041 {
6042   struct queue_iter_param param;
6043
6044   param.input = &ptid;
6045   param.output = NULL;
6046
6047   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6048                  remote_notif_remove_once_on_match, &param);
6049   if (notif_debug)
6050     fprintf_unfiltered (gdb_stdlog,
6051                         "notif: discard queued event: 'Stop' in %s\n",
6052                         target_pid_to_str (ptid));
6053
6054   return param.output;
6055 }
6056
6057 /* Look for a queued stop reply belonging to PTID.  If one is found,
6058    remove it from the queue, and return it.  Returns NULL if none is
6059    found.  If there are still queued events left to process, tell the
6060    event loop to get back to target_wait soon.  */
6061
6062 static struct stop_reply *
6063 queued_stop_reply (ptid_t ptid)
6064 {
6065   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6066
6067   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6068     /* There's still at least an event left.  */
6069     mark_async_event_handler (remote_async_inferior_event_token);
6070
6071   return r;
6072 }
6073
6074 /* Push a fully parsed stop reply in the stop reply queue.  Since we
6075    know that we now have at least one queued event left to pass to the
6076    core side, tell the event loop to get back to target_wait soon.  */
6077
6078 static void
6079 push_stop_reply (struct stop_reply *new_event)
6080 {
6081   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6082
6083   if (notif_debug)
6084     fprintf_unfiltered (gdb_stdlog,
6085                         "notif: push 'Stop' %s to queue %d\n",
6086                         target_pid_to_str (new_event->ptid),
6087                         QUEUE_length (stop_reply_p,
6088                                       stop_reply_queue));
6089
6090   mark_async_event_handler (remote_async_inferior_event_token);
6091 }
6092
6093 static int
6094 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6095                               QUEUE_ITER (stop_reply_p) *iter,
6096                               struct stop_reply *event,
6097                               void *data)
6098 {
6099   ptid_t *ptid = (ptid_t *) data;
6100
6101   return !(ptid_equal (*ptid, event->ptid)
6102            && event->ws.kind == TARGET_WAITKIND_STOPPED);
6103 }
6104
6105 /* Returns true if we have a stop reply for PTID.  */
6106
6107 static int
6108 peek_stop_reply (ptid_t ptid)
6109 {
6110   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6111                          stop_reply_match_ptid_and_ws, &ptid);
6112 }
6113
6114 /* Skip PACKET until the next semi-colon (or end of string).  */
6115
6116 static char *
6117 skip_to_semicolon (char *p)
6118 {
6119   while (*p != '\0' && *p != ';')
6120     p++;
6121   return p;
6122 }
6123
6124 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
6125    starting with P and ending with PEND matches PREFIX.  */
6126
6127 static int
6128 strprefix (const char *p, const char *pend, const char *prefix)
6129 {
6130   for ( ; p < pend; p++, prefix++)
6131     if (*p != *prefix)
6132       return 0;
6133   return *prefix == '\0';
6134 }
6135
6136 /* Parse the stop reply in BUF.  Either the function succeeds, and the
6137    result is stored in EVENT, or throws an error.  */
6138
6139 static void
6140 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6141 {
6142   struct remote_arch_state *rsa = get_remote_arch_state ();
6143   ULONGEST addr;
6144   char *p;
6145   int skipregs = 0;
6146
6147   event->ptid = null_ptid;
6148   event->rs = get_remote_state ();
6149   event->ws.kind = TARGET_WAITKIND_IGNORE;
6150   event->ws.value.integer = 0;
6151   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6152   event->regcache = NULL;
6153   event->core = -1;
6154
6155   switch (buf[0])
6156     {
6157     case 'T':           /* Status with PC, SP, FP, ...  */
6158       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
6159       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
6160             ss = signal number
6161             n... = register number
6162             r... = register contents
6163       */
6164
6165       p = &buf[3];      /* after Txx */
6166       while (*p)
6167         {
6168           char *p1;
6169           int fieldsize;
6170
6171           p1 = strchr (p, ':');
6172           if (p1 == NULL)
6173             error (_("Malformed packet(a) (missing colon): %s\n\
6174 Packet: '%s'\n"),
6175                    p, buf);
6176           if (p == p1)
6177             error (_("Malformed packet(a) (missing register number): %s\n\
6178 Packet: '%s'\n"),
6179                    p, buf);
6180
6181           /* Some "registers" are actually extended stop information.
6182              Note if you're adding a new entry here: GDB 7.9 and
6183              earlier assume that all register "numbers" that start
6184              with an hex digit are real register numbers.  Make sure
6185              the server only sends such a packet if it knows the
6186              client understands it.  */
6187
6188           if (strprefix (p, p1, "thread"))
6189             event->ptid = read_ptid (++p1, &p);
6190           else if (strprefix (p, p1, "watch")
6191                    || strprefix (p, p1, "rwatch")
6192                    || strprefix (p, p1, "awatch"))
6193             {
6194               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6195               p = unpack_varlen_hex (++p1, &addr);
6196               event->watch_data_address = (CORE_ADDR) addr;
6197             }
6198           else if (strprefix (p, p1, "swbreak"))
6199             {
6200               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6201
6202               /* Make sure the stub doesn't forget to indicate support
6203                  with qSupported.  */
6204               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6205                 error (_("Unexpected swbreak stop reason"));
6206
6207               /* The value part is documented as "must be empty",
6208                  though we ignore it, in case we ever decide to make
6209                  use of it in a backward compatible way.  */
6210               p = skip_to_semicolon (p1 + 1);
6211             }
6212           else if (strprefix (p, p1, "hwbreak"))
6213             {
6214               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6215
6216               /* Make sure the stub doesn't forget to indicate support
6217                  with qSupported.  */
6218               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6219                 error (_("Unexpected hwbreak stop reason"));
6220
6221               /* See above.  */
6222               p = skip_to_semicolon (p1 + 1);
6223             }
6224           else if (strprefix (p, p1, "library"))
6225             {
6226               event->ws.kind = TARGET_WAITKIND_LOADED;
6227               p = skip_to_semicolon (p1 + 1);
6228             }
6229           else if (strprefix (p, p1, "replaylog"))
6230             {
6231               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6232               /* p1 will indicate "begin" or "end", but it makes
6233                  no difference for now, so ignore it.  */
6234               p = skip_to_semicolon (p1 + 1);
6235             }
6236           else if (strprefix (p, p1, "core"))
6237             {
6238               ULONGEST c;
6239
6240               p = unpack_varlen_hex (++p1, &c);
6241               event->core = c;
6242             }
6243           else if (strprefix (p, p1, "fork"))
6244             {
6245               event->ws.value.related_pid = read_ptid (++p1, &p);
6246               event->ws.kind = TARGET_WAITKIND_FORKED;
6247             }
6248           else if (strprefix (p, p1, "vfork"))
6249             {
6250               event->ws.value.related_pid = read_ptid (++p1, &p);
6251               event->ws.kind = TARGET_WAITKIND_VFORKED;
6252             }
6253           else if (strprefix (p, p1, "vforkdone"))
6254             {
6255               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6256               p = skip_to_semicolon (p1 + 1);
6257             }
6258           else if (strprefix (p, p1, "exec"))
6259             {
6260               ULONGEST ignored;
6261               char pathname[PATH_MAX];
6262               int pathlen;
6263
6264               /* Determine the length of the execd pathname.  */
6265               p = unpack_varlen_hex (++p1, &ignored);
6266               pathlen = (p - p1) / 2;
6267
6268               /* Save the pathname for event reporting and for
6269                  the next run command.  */
6270               hex2bin (p1, (gdb_byte *) pathname, pathlen);
6271               pathname[pathlen] = '\0';
6272
6273               /* This is freed during event handling.  */
6274               event->ws.value.execd_pathname = xstrdup (pathname);
6275               event->ws.kind = TARGET_WAITKIND_EXECD;
6276
6277               /* Skip the registers included in this packet, since
6278                  they may be for an architecture different from the
6279                  one used by the original program.  */
6280               skipregs = 1;
6281             }
6282           else
6283             {
6284               ULONGEST pnum;
6285               char *p_temp;
6286
6287               if (skipregs)
6288                 {
6289                   p = skip_to_semicolon (p1 + 1);
6290                   p++;
6291                   continue;
6292                 }
6293
6294               /* Maybe a real ``P'' register number.  */
6295               p_temp = unpack_varlen_hex (p, &pnum);
6296               /* If the first invalid character is the colon, we got a
6297                  register number.  Otherwise, it's an unknown stop
6298                  reason.  */
6299               if (p_temp == p1)
6300                 {
6301                   struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6302                   cached_reg_t cached_reg;
6303
6304                   if (reg == NULL)
6305                     error (_("Remote sent bad register number %s: %s\n\
6306 Packet: '%s'\n"),
6307                            hex_string (pnum), p, buf);
6308
6309                   cached_reg.num = reg->regnum;
6310
6311                   p = p1 + 1;
6312                   fieldsize = hex2bin (p, cached_reg.data,
6313                                        register_size (target_gdbarch (),
6314                                                       reg->regnum));
6315                   p += 2 * fieldsize;
6316                   if (fieldsize < register_size (target_gdbarch (),
6317                                                  reg->regnum))
6318                     warning (_("Remote reply is too short: %s"), buf);
6319
6320                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6321                 }
6322               else
6323                 {
6324                   /* Not a number.  Silently skip unknown optional
6325                      info.  */
6326                   p = skip_to_semicolon (p1 + 1);
6327                 }
6328             }
6329
6330           if (*p != ';')
6331             error (_("Remote register badly formatted: %s\nhere: %s"),
6332                    buf, p);
6333           ++p;
6334         }
6335
6336       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6337         break;
6338
6339       /* fall through */
6340     case 'S':           /* Old style status, just signal only.  */
6341       {
6342         int sig;
6343
6344         event->ws.kind = TARGET_WAITKIND_STOPPED;
6345         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6346         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6347           event->ws.value.sig = (enum gdb_signal) sig;
6348         else
6349           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6350       }
6351       break;
6352     case 'W':           /* Target exited.  */
6353     case 'X':
6354       {
6355         char *p;
6356         int pid;
6357         ULONGEST value;
6358
6359         /* GDB used to accept only 2 hex chars here.  Stubs should
6360            only send more if they detect GDB supports multi-process
6361            support.  */
6362         p = unpack_varlen_hex (&buf[1], &value);
6363
6364         if (buf[0] == 'W')
6365           {
6366             /* The remote process exited.  */
6367             event->ws.kind = TARGET_WAITKIND_EXITED;
6368             event->ws.value.integer = value;
6369           }
6370         else
6371           {
6372             /* The remote process exited with a signal.  */
6373             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6374             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6375               event->ws.value.sig = (enum gdb_signal) value;
6376             else
6377               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6378           }
6379
6380         /* If no process is specified, assume inferior_ptid.  */
6381         pid = ptid_get_pid (inferior_ptid);
6382         if (*p == '\0')
6383           ;
6384         else if (*p == ';')
6385           {
6386             p++;
6387
6388             if (*p == '\0')
6389               ;
6390             else if (startswith (p, "process:"))
6391               {
6392                 ULONGEST upid;
6393
6394                 p += sizeof ("process:") - 1;
6395                 unpack_varlen_hex (p, &upid);
6396                 pid = upid;
6397               }
6398             else
6399               error (_("unknown stop reply packet: %s"), buf);
6400           }
6401         else
6402           error (_("unknown stop reply packet: %s"), buf);
6403         event->ptid = pid_to_ptid (pid);
6404       }
6405       break;
6406     }
6407
6408   if (non_stop && ptid_equal (event->ptid, null_ptid))
6409     error (_("No process or thread specified in stop reply: %s"), buf);
6410 }
6411
6412 /* When the stub wants to tell GDB about a new notification reply, it
6413    sends a notification (%Stop, for example).  Those can come it at
6414    any time, hence, we have to make sure that any pending
6415    putpkt/getpkt sequence we're making is finished, before querying
6416    the stub for more events with the corresponding ack command
6417    (vStopped, for example).  E.g., if we started a vStopped sequence
6418    immediately upon receiving the notification, something like this
6419    could happen:
6420
6421     1.1) --> Hg 1
6422     1.2) <-- OK
6423     1.3) --> g
6424     1.4) <-- %Stop
6425     1.5) --> vStopped
6426     1.6) <-- (registers reply to step #1.3)
6427
6428    Obviously, the reply in step #1.6 would be unexpected to a vStopped
6429    query.
6430
6431    To solve this, whenever we parse a %Stop notification successfully,
6432    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6433    doing whatever we were doing:
6434
6435     2.1) --> Hg 1
6436     2.2) <-- OK
6437     2.3) --> g
6438     2.4) <-- %Stop
6439       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6440     2.5) <-- (registers reply to step #2.3)
6441
6442    Eventualy after step #2.5, we return to the event loop, which
6443    notices there's an event on the
6444    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6445    associated callback --- the function below.  At this point, we're
6446    always safe to start a vStopped sequence. :
6447
6448     2.6) --> vStopped
6449     2.7) <-- T05 thread:2
6450     2.8) --> vStopped
6451     2.9) --> OK
6452 */
6453
6454 void
6455 remote_notif_get_pending_events (struct notif_client *nc)
6456 {
6457   struct remote_state *rs = get_remote_state ();
6458
6459   if (rs->notif_state->pending_event[nc->id] != NULL)
6460     {
6461       if (notif_debug)
6462         fprintf_unfiltered (gdb_stdlog,
6463                             "notif: process: '%s' ack pending event\n",
6464                             nc->name);
6465
6466       /* acknowledge */
6467       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6468       rs->notif_state->pending_event[nc->id] = NULL;
6469
6470       while (1)
6471         {
6472           getpkt (&rs->buf, &rs->buf_size, 0);
6473           if (strcmp (rs->buf, "OK") == 0)
6474             break;
6475           else
6476             remote_notif_ack (nc, rs->buf);
6477         }
6478     }
6479   else
6480     {
6481       if (notif_debug)
6482         fprintf_unfiltered (gdb_stdlog,
6483                             "notif: process: '%s' no pending reply\n",
6484                             nc->name);
6485     }
6486 }
6487
6488 /* Called when it is decided that STOP_REPLY holds the info of the
6489    event that is to be returned to the core.  This function always
6490    destroys STOP_REPLY.  */
6491
6492 static ptid_t
6493 process_stop_reply (struct stop_reply *stop_reply,
6494                     struct target_waitstatus *status)
6495 {
6496   ptid_t ptid;
6497
6498   *status = stop_reply->ws;
6499   ptid = stop_reply->ptid;
6500
6501   /* If no thread/process was reported by the stub, assume the current
6502      inferior.  */
6503   if (ptid_equal (ptid, null_ptid))
6504     ptid = inferior_ptid;
6505
6506   if (status->kind != TARGET_WAITKIND_EXITED
6507       && status->kind != TARGET_WAITKIND_SIGNALLED)
6508     {
6509       struct remote_state *rs = get_remote_state ();
6510
6511       /* Expedited registers.  */
6512       if (stop_reply->regcache)
6513         {
6514           struct regcache *regcache
6515             = get_thread_arch_regcache (ptid, target_gdbarch ());
6516           cached_reg_t *reg;
6517           int ix;
6518
6519           for (ix = 0;
6520                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6521                ix++)
6522             regcache_raw_supply (regcache, reg->num, reg->data);
6523           VEC_free (cached_reg_t, stop_reply->regcache);
6524         }
6525
6526       rs->stop_reason = stop_reply->stop_reason;
6527       rs->remote_watch_data_address = stop_reply->watch_data_address;
6528
6529       remote_notice_new_inferior (ptid, 0);
6530       demand_private_info (ptid)->core = stop_reply->core;
6531     }
6532
6533   stop_reply_xfree (stop_reply);
6534   return ptid;
6535 }
6536
6537 /* The non-stop mode version of target_wait.  */
6538
6539 static ptid_t
6540 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6541 {
6542   struct remote_state *rs = get_remote_state ();
6543   struct stop_reply *stop_reply;
6544   int ret;
6545   int is_notif = 0;
6546
6547   /* If in non-stop mode, get out of getpkt even if a
6548      notification is received.  */
6549
6550   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6551                               0 /* forever */, &is_notif);
6552   while (1)
6553     {
6554       if (ret != -1 && !is_notif)
6555         switch (rs->buf[0])
6556           {
6557           case 'E':             /* Error of some sort.  */
6558             /* We're out of sync with the target now.  Did it continue
6559                or not?  We can't tell which thread it was in non-stop,
6560                so just ignore this.  */
6561             warning (_("Remote failure reply: %s"), rs->buf);
6562             break;
6563           case 'O':             /* Console output.  */
6564             remote_console_output (rs->buf + 1);
6565             break;
6566           default:
6567             warning (_("Invalid remote reply: %s"), rs->buf);
6568             break;
6569           }
6570
6571       /* Acknowledge a pending stop reply that may have arrived in the
6572          mean time.  */
6573       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6574         remote_notif_get_pending_events (&notif_client_stop);
6575
6576       /* If indeed we noticed a stop reply, we're done.  */
6577       stop_reply = queued_stop_reply (ptid);
6578       if (stop_reply != NULL)
6579         return process_stop_reply (stop_reply, status);
6580
6581       /* Still no event.  If we're just polling for an event, then
6582          return to the event loop.  */
6583       if (options & TARGET_WNOHANG)
6584         {
6585           status->kind = TARGET_WAITKIND_IGNORE;
6586           return minus_one_ptid;
6587         }
6588
6589       /* Otherwise do a blocking wait.  */
6590       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6591                                   1 /* forever */, &is_notif);
6592     }
6593 }
6594
6595 /* Wait until the remote machine stops, then return, storing status in
6596    STATUS just as `wait' would.  */
6597
6598 static ptid_t
6599 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6600 {
6601   struct remote_state *rs = get_remote_state ();
6602   ptid_t event_ptid = null_ptid;
6603   char *buf;
6604   struct stop_reply *stop_reply;
6605
6606  again:
6607
6608   status->kind = TARGET_WAITKIND_IGNORE;
6609   status->value.integer = 0;
6610
6611   stop_reply = queued_stop_reply (ptid);
6612   if (stop_reply != NULL)
6613     return process_stop_reply (stop_reply, status);
6614
6615   if (rs->cached_wait_status)
6616     /* Use the cached wait status, but only once.  */
6617     rs->cached_wait_status = 0;
6618   else
6619     {
6620       int ret;
6621       int is_notif;
6622       int forever = ((options & TARGET_WNOHANG) == 0
6623                      && wait_forever_enabled_p);
6624
6625       if (!rs->waiting_for_stop_reply)
6626         {
6627           status->kind = TARGET_WAITKIND_NO_RESUMED;
6628           return minus_one_ptid;
6629         }
6630
6631       if (!target_is_async_p ())
6632         {
6633           ofunc = signal (SIGINT, sync_remote_interrupt);
6634           /* If the user hit C-c before this packet, or between packets,
6635              pretend that it was hit right here.  */
6636           if (check_quit_flag ())
6637             {
6638               clear_quit_flag ();
6639               sync_remote_interrupt (SIGINT);
6640             }
6641         }
6642
6643       /* FIXME: cagney/1999-09-27: If we're in async mode we should
6644          _never_ wait for ever -> test on target_is_async_p().
6645          However, before we do that we need to ensure that the caller
6646          knows how to take the target into/out of async mode.  */
6647       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6648                                   forever, &is_notif);
6649
6650       if (!target_is_async_p ())
6651         signal (SIGINT, ofunc);
6652
6653       /* GDB gets a notification.  Return to core as this event is
6654          not interesting.  */
6655       if (ret != -1 && is_notif)
6656         return minus_one_ptid;
6657
6658       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6659         return minus_one_ptid;
6660     }
6661
6662   buf = rs->buf;
6663
6664   rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6665
6666   /* Assume that the target has acknowledged Ctrl-C unless we receive
6667      an 'F' or 'O' packet.  */
6668   if (buf[0] != 'F' && buf[0] != 'O')
6669     rs->ctrlc_pending_p = 0;
6670
6671   switch (buf[0])
6672     {
6673     case 'E':           /* Error of some sort.  */
6674       /* We're out of sync with the target now.  Did it continue or
6675          not?  Not is more likely, so report a stop.  */
6676       rs->waiting_for_stop_reply = 0;
6677
6678       warning (_("Remote failure reply: %s"), buf);
6679       status->kind = TARGET_WAITKIND_STOPPED;
6680       status->value.sig = GDB_SIGNAL_0;
6681       break;
6682     case 'F':           /* File-I/O request.  */
6683       remote_fileio_request (buf, rs->ctrlc_pending_p);
6684       rs->ctrlc_pending_p = 0;
6685       break;
6686     case 'T': case 'S': case 'X': case 'W':
6687       {
6688         struct stop_reply *stop_reply;
6689
6690         /* There is a stop reply to handle.  */
6691         rs->waiting_for_stop_reply = 0;
6692
6693         stop_reply
6694           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6695                                                       rs->buf);
6696
6697         event_ptid = process_stop_reply (stop_reply, status);
6698         break;
6699       }
6700     case 'O':           /* Console output.  */
6701       remote_console_output (buf + 1);
6702       break;
6703     case '\0':
6704       if (rs->last_sent_signal != GDB_SIGNAL_0)
6705         {
6706           /* Zero length reply means that we tried 'S' or 'C' and the
6707              remote system doesn't support it.  */
6708           target_terminal_ours_for_output ();
6709           printf_filtered
6710             ("Can't send signals to this remote system.  %s not sent.\n",
6711              gdb_signal_to_name (rs->last_sent_signal));
6712           rs->last_sent_signal = GDB_SIGNAL_0;
6713           target_terminal_inferior ();
6714
6715           strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6716           putpkt ((char *) buf);
6717           break;
6718         }
6719       /* else fallthrough */
6720     default:
6721       warning (_("Invalid remote reply: %s"), buf);
6722       break;
6723     }
6724
6725   if (status->kind == TARGET_WAITKIND_IGNORE)
6726     {
6727       /* Nothing interesting happened.  If we're doing a non-blocking
6728          poll, we're done.  Otherwise, go back to waiting.  */
6729       if (options & TARGET_WNOHANG)
6730         return minus_one_ptid;
6731       else
6732         goto again;
6733     }
6734   else if (status->kind != TARGET_WAITKIND_EXITED
6735            && status->kind != TARGET_WAITKIND_SIGNALLED)
6736     {
6737       if (!ptid_equal (event_ptid, null_ptid))
6738         record_currthread (rs, event_ptid);
6739       else
6740         event_ptid = inferior_ptid;
6741     }
6742   else
6743     /* A process exit.  Invalidate our notion of current thread.  */
6744     record_currthread (rs, minus_one_ptid);
6745
6746   return event_ptid;
6747 }
6748
6749 /* Wait until the remote machine stops, then return, storing status in
6750    STATUS just as `wait' would.  */
6751
6752 static ptid_t
6753 remote_wait (struct target_ops *ops,
6754              ptid_t ptid, struct target_waitstatus *status, int options)
6755 {
6756   ptid_t event_ptid;
6757
6758   if (non_stop)
6759     event_ptid = remote_wait_ns (ptid, status, options);
6760   else
6761     event_ptid = remote_wait_as (ptid, status, options);
6762
6763   if (target_is_async_p ())
6764     {
6765       /* If there are are events left in the queue tell the event loop
6766          to return here.  */
6767       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6768         mark_async_event_handler (remote_async_inferior_event_token);
6769     }
6770
6771   return event_ptid;
6772 }
6773
6774 /* Fetch a single register using a 'p' packet.  */
6775
6776 static int
6777 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6778 {
6779   struct remote_state *rs = get_remote_state ();
6780   char *buf, *p;
6781   char regp[MAX_REGISTER_SIZE];
6782   int i;
6783
6784   if (packet_support (PACKET_p) == PACKET_DISABLE)
6785     return 0;
6786
6787   if (reg->pnum == -1)
6788     return 0;
6789
6790   p = rs->buf;
6791   *p++ = 'p';
6792   p += hexnumstr (p, reg->pnum);
6793   *p++ = '\0';
6794   putpkt (rs->buf);
6795   getpkt (&rs->buf, &rs->buf_size, 0);
6796
6797   buf = rs->buf;
6798
6799   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6800     {
6801     case PACKET_OK:
6802       break;
6803     case PACKET_UNKNOWN:
6804       return 0;
6805     case PACKET_ERROR:
6806       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6807              gdbarch_register_name (get_regcache_arch (regcache), 
6808                                     reg->regnum), 
6809              buf);
6810     }
6811
6812   /* If this register is unfetchable, tell the regcache.  */
6813   if (buf[0] == 'x')
6814     {
6815       regcache_raw_supply (regcache, reg->regnum, NULL);
6816       return 1;
6817     }
6818
6819   /* Otherwise, parse and supply the value.  */
6820   p = buf;
6821   i = 0;
6822   while (p[0] != 0)
6823     {
6824       if (p[1] == 0)
6825         error (_("fetch_register_using_p: early buf termination"));
6826
6827       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6828       p += 2;
6829     }
6830   regcache_raw_supply (regcache, reg->regnum, regp);
6831   return 1;
6832 }
6833
6834 /* Fetch the registers included in the target's 'g' packet.  */
6835
6836 static int
6837 send_g_packet (void)
6838 {
6839   struct remote_state *rs = get_remote_state ();
6840   int buf_len;
6841
6842   xsnprintf (rs->buf, get_remote_packet_size (), "g");
6843   remote_send (&rs->buf, &rs->buf_size);
6844
6845   /* We can get out of synch in various cases.  If the first character
6846      in the buffer is not a hex character, assume that has happened
6847      and try to fetch another packet to read.  */
6848   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6849          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6850          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6851          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
6852     {
6853       if (remote_debug)
6854         fprintf_unfiltered (gdb_stdlog,
6855                             "Bad register packet; fetching a new packet\n");
6856       getpkt (&rs->buf, &rs->buf_size, 0);
6857     }
6858
6859   buf_len = strlen (rs->buf);
6860
6861   /* Sanity check the received packet.  */
6862   if (buf_len % 2 != 0)
6863     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6864
6865   return buf_len / 2;
6866 }
6867
6868 static void
6869 process_g_packet (struct regcache *regcache)
6870 {
6871   struct gdbarch *gdbarch = get_regcache_arch (regcache);
6872   struct remote_state *rs = get_remote_state ();
6873   struct remote_arch_state *rsa = get_remote_arch_state ();
6874   int i, buf_len;
6875   char *p;
6876   char *regs;
6877
6878   buf_len = strlen (rs->buf);
6879
6880   /* Further sanity checks, with knowledge of the architecture.  */
6881   if (buf_len > 2 * rsa->sizeof_g_packet)
6882     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6883
6884   /* Save the size of the packet sent to us by the target.  It is used
6885      as a heuristic when determining the max size of packets that the
6886      target can safely receive.  */
6887   if (rsa->actual_register_packet_size == 0)
6888     rsa->actual_register_packet_size = buf_len;
6889
6890   /* If this is smaller than we guessed the 'g' packet would be,
6891      update our records.  A 'g' reply that doesn't include a register's
6892      value implies either that the register is not available, or that
6893      the 'p' packet must be used.  */
6894   if (buf_len < 2 * rsa->sizeof_g_packet)
6895     {
6896       rsa->sizeof_g_packet = buf_len / 2;
6897
6898       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6899         {
6900           if (rsa->regs[i].pnum == -1)
6901             continue;
6902
6903           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6904             rsa->regs[i].in_g_packet = 0;
6905           else
6906             rsa->regs[i].in_g_packet = 1;
6907         }
6908     }
6909
6910   regs = (char *) alloca (rsa->sizeof_g_packet);
6911
6912   /* Unimplemented registers read as all bits zero.  */
6913   memset (regs, 0, rsa->sizeof_g_packet);
6914
6915   /* Reply describes registers byte by byte, each byte encoded as two
6916      hex characters.  Suck them all up, then supply them to the
6917      register cacheing/storage mechanism.  */
6918
6919   p = rs->buf;
6920   for (i = 0; i < rsa->sizeof_g_packet; i++)
6921     {
6922       if (p[0] == 0 || p[1] == 0)
6923         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
6924         internal_error (__FILE__, __LINE__,
6925                         _("unexpected end of 'g' packet reply"));
6926
6927       if (p[0] == 'x' && p[1] == 'x')
6928         regs[i] = 0;            /* 'x' */
6929       else
6930         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6931       p += 2;
6932     }
6933
6934   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6935     {
6936       struct packet_reg *r = &rsa->regs[i];
6937
6938       if (r->in_g_packet)
6939         {
6940           if (r->offset * 2 >= strlen (rs->buf))
6941             /* This shouldn't happen - we adjusted in_g_packet above.  */
6942             internal_error (__FILE__, __LINE__,
6943                             _("unexpected end of 'g' packet reply"));
6944           else if (rs->buf[r->offset * 2] == 'x')
6945             {
6946               gdb_assert (r->offset * 2 < strlen (rs->buf));
6947               /* The register isn't available, mark it as such (at
6948                  the same time setting the value to zero).  */
6949               regcache_raw_supply (regcache, r->regnum, NULL);
6950             }
6951           else
6952             regcache_raw_supply (regcache, r->regnum,
6953                                  regs + r->offset);
6954         }
6955     }
6956 }
6957
6958 static void
6959 fetch_registers_using_g (struct regcache *regcache)
6960 {
6961   send_g_packet ();
6962   process_g_packet (regcache);
6963 }
6964
6965 /* Make the remote selected traceframe match GDB's selected
6966    traceframe.  */
6967
6968 static void
6969 set_remote_traceframe (void)
6970 {
6971   int newnum;
6972   struct remote_state *rs = get_remote_state ();
6973
6974   if (rs->remote_traceframe_number == get_traceframe_number ())
6975     return;
6976
6977   /* Avoid recursion, remote_trace_find calls us again.  */
6978   rs->remote_traceframe_number = get_traceframe_number ();
6979
6980   newnum = target_trace_find (tfind_number,
6981                               get_traceframe_number (), 0, 0, NULL);
6982
6983   /* Should not happen.  If it does, all bets are off.  */
6984   if (newnum != get_traceframe_number ())
6985     warning (_("could not set remote traceframe"));
6986 }
6987
6988 static void
6989 remote_fetch_registers (struct target_ops *ops,
6990                         struct regcache *regcache, int regnum)
6991 {
6992   struct remote_arch_state *rsa = get_remote_arch_state ();
6993   int i;
6994
6995   set_remote_traceframe ();
6996   set_general_thread (inferior_ptid);
6997
6998   if (regnum >= 0)
6999     {
7000       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7001
7002       gdb_assert (reg != NULL);
7003
7004       /* If this register might be in the 'g' packet, try that first -
7005          we are likely to read more than one register.  If this is the
7006          first 'g' packet, we might be overly optimistic about its
7007          contents, so fall back to 'p'.  */
7008       if (reg->in_g_packet)
7009         {
7010           fetch_registers_using_g (regcache);
7011           if (reg->in_g_packet)
7012             return;
7013         }
7014
7015       if (fetch_register_using_p (regcache, reg))
7016         return;
7017
7018       /* This register is not available.  */
7019       regcache_raw_supply (regcache, reg->regnum, NULL);
7020
7021       return;
7022     }
7023
7024   fetch_registers_using_g (regcache);
7025
7026   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7027     if (!rsa->regs[i].in_g_packet)
7028       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7029         {
7030           /* This register is not available.  */
7031           regcache_raw_supply (regcache, i, NULL);
7032         }
7033 }
7034
7035 /* Prepare to store registers.  Since we may send them all (using a
7036    'G' request), we have to read out the ones we don't want to change
7037    first.  */
7038
7039 static void
7040 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7041 {
7042   struct remote_arch_state *rsa = get_remote_arch_state ();
7043   int i;
7044   gdb_byte buf[MAX_REGISTER_SIZE];
7045
7046   /* Make sure the entire registers array is valid.  */
7047   switch (packet_support (PACKET_P))
7048     {
7049     case PACKET_DISABLE:
7050     case PACKET_SUPPORT_UNKNOWN:
7051       /* Make sure all the necessary registers are cached.  */
7052       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7053         if (rsa->regs[i].in_g_packet)
7054           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7055       break;
7056     case PACKET_ENABLE:
7057       break;
7058     }
7059 }
7060
7061 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
7062    packet was not recognized.  */
7063
7064 static int
7065 store_register_using_P (const struct regcache *regcache, 
7066                         struct packet_reg *reg)
7067 {
7068   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7069   struct remote_state *rs = get_remote_state ();
7070   /* Try storing a single register.  */
7071   char *buf = rs->buf;
7072   gdb_byte regp[MAX_REGISTER_SIZE];
7073   char *p;
7074
7075   if (packet_support (PACKET_P) == PACKET_DISABLE)
7076     return 0;
7077
7078   if (reg->pnum == -1)
7079     return 0;
7080
7081   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7082   p = buf + strlen (buf);
7083   regcache_raw_collect (regcache, reg->regnum, regp);
7084   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7085   putpkt (rs->buf);
7086   getpkt (&rs->buf, &rs->buf_size, 0);
7087
7088   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7089     {
7090     case PACKET_OK:
7091       return 1;
7092     case PACKET_ERROR:
7093       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7094              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7095     case PACKET_UNKNOWN:
7096       return 0;
7097     default:
7098       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7099     }
7100 }
7101
7102 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7103    contents of the register cache buffer.  FIXME: ignores errors.  */
7104
7105 static void
7106 store_registers_using_G (const struct regcache *regcache)
7107 {
7108   struct remote_state *rs = get_remote_state ();
7109   struct remote_arch_state *rsa = get_remote_arch_state ();
7110   gdb_byte *regs;
7111   char *p;
7112
7113   /* Extract all the registers in the regcache copying them into a
7114      local buffer.  */
7115   {
7116     int i;
7117
7118     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7119     memset (regs, 0, rsa->sizeof_g_packet);
7120     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7121       {
7122         struct packet_reg *r = &rsa->regs[i];
7123
7124         if (r->in_g_packet)
7125           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7126       }
7127   }
7128
7129   /* Command describes registers byte by byte,
7130      each byte encoded as two hex characters.  */
7131   p = rs->buf;
7132   *p++ = 'G';
7133   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7134      updated.  */
7135   bin2hex (regs, p, rsa->sizeof_g_packet);
7136   putpkt (rs->buf);
7137   getpkt (&rs->buf, &rs->buf_size, 0);
7138   if (packet_check_result (rs->buf) == PACKET_ERROR)
7139     error (_("Could not write registers; remote failure reply '%s'"), 
7140            rs->buf);
7141 }
7142
7143 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7144    of the register cache buffer.  FIXME: ignores errors.  */
7145
7146 static void
7147 remote_store_registers (struct target_ops *ops,
7148                         struct regcache *regcache, int regnum)
7149 {
7150   struct remote_arch_state *rsa = get_remote_arch_state ();
7151   int i;
7152
7153   set_remote_traceframe ();
7154   set_general_thread (inferior_ptid);
7155
7156   if (regnum >= 0)
7157     {
7158       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7159
7160       gdb_assert (reg != NULL);
7161
7162       /* Always prefer to store registers using the 'P' packet if
7163          possible; we often change only a small number of registers.
7164          Sometimes we change a larger number; we'd need help from a
7165          higher layer to know to use 'G'.  */
7166       if (store_register_using_P (regcache, reg))
7167         return;
7168
7169       /* For now, don't complain if we have no way to write the
7170          register.  GDB loses track of unavailable registers too
7171          easily.  Some day, this may be an error.  We don't have
7172          any way to read the register, either...  */
7173       if (!reg->in_g_packet)
7174         return;
7175
7176       store_registers_using_G (regcache);
7177       return;
7178     }
7179
7180   store_registers_using_G (regcache);
7181
7182   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7183     if (!rsa->regs[i].in_g_packet)
7184       if (!store_register_using_P (regcache, &rsa->regs[i]))
7185         /* See above for why we do not issue an error here.  */
7186         continue;
7187 }
7188 \f
7189
7190 /* Return the number of hex digits in num.  */
7191
7192 static int
7193 hexnumlen (ULONGEST num)
7194 {
7195   int i;
7196
7197   for (i = 0; num != 0; i++)
7198     num >>= 4;
7199
7200   return max (i, 1);
7201 }
7202
7203 /* Set BUF to the minimum number of hex digits representing NUM.  */
7204
7205 static int
7206 hexnumstr (char *buf, ULONGEST num)
7207 {
7208   int len = hexnumlen (num);
7209
7210   return hexnumnstr (buf, num, len);
7211 }
7212
7213
7214 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
7215
7216 static int
7217 hexnumnstr (char *buf, ULONGEST num, int width)
7218 {
7219   int i;
7220
7221   buf[width] = '\0';
7222
7223   for (i = width - 1; i >= 0; i--)
7224     {
7225       buf[i] = "0123456789abcdef"[(num & 0xf)];
7226       num >>= 4;
7227     }
7228
7229   return width;
7230 }
7231
7232 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
7233
7234 static CORE_ADDR
7235 remote_address_masked (CORE_ADDR addr)
7236 {
7237   unsigned int address_size = remote_address_size;
7238
7239   /* If "remoteaddresssize" was not set, default to target address size.  */
7240   if (!address_size)
7241     address_size = gdbarch_addr_bit (target_gdbarch ());
7242
7243   if (address_size > 0
7244       && address_size < (sizeof (ULONGEST) * 8))
7245     {
7246       /* Only create a mask when that mask can safely be constructed
7247          in a ULONGEST variable.  */
7248       ULONGEST mask = 1;
7249
7250       mask = (mask << address_size) - 1;
7251       addr &= mask;
7252     }
7253   return addr;
7254 }
7255
7256 /* Determine whether the remote target supports binary downloading.
7257    This is accomplished by sending a no-op memory write of zero length
7258    to the target at the specified address. It does not suffice to send
7259    the whole packet, since many stubs strip the eighth bit and
7260    subsequently compute a wrong checksum, which causes real havoc with
7261    remote_write_bytes.
7262
7263    NOTE: This can still lose if the serial line is not eight-bit
7264    clean.  In cases like this, the user should clear "remote
7265    X-packet".  */
7266
7267 static void
7268 check_binary_download (CORE_ADDR addr)
7269 {
7270   struct remote_state *rs = get_remote_state ();
7271
7272   switch (packet_support (PACKET_X))
7273     {
7274     case PACKET_DISABLE:
7275       break;
7276     case PACKET_ENABLE:
7277       break;
7278     case PACKET_SUPPORT_UNKNOWN:
7279       {
7280         char *p;
7281
7282         p = rs->buf;
7283         *p++ = 'X';
7284         p += hexnumstr (p, (ULONGEST) addr);
7285         *p++ = ',';
7286         p += hexnumstr (p, (ULONGEST) 0);
7287         *p++ = ':';
7288         *p = '\0';
7289
7290         putpkt_binary (rs->buf, (int) (p - rs->buf));
7291         getpkt (&rs->buf, &rs->buf_size, 0);
7292
7293         if (rs->buf[0] == '\0')
7294           {
7295             if (remote_debug)
7296               fprintf_unfiltered (gdb_stdlog,
7297                                   "binary downloading NOT "
7298                                   "supported by target\n");
7299             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7300           }
7301         else
7302           {
7303             if (remote_debug)
7304               fprintf_unfiltered (gdb_stdlog,
7305                                   "binary downloading supported by target\n");
7306             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7307           }
7308         break;
7309       }
7310     }
7311 }
7312
7313 /* Helper function to resize the payload in order to try to get a good
7314    alignment.  We try to write an amount of data such that the next write will
7315    start on an address aligned on REMOTE_ALIGN_WRITES.  */
7316
7317 static int
7318 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7319 {
7320   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7321 }
7322
7323 /* Write memory data directly to the remote machine.
7324    This does not inform the data cache; the data cache uses this.
7325    HEADER is the starting part of the packet.
7326    MEMADDR is the address in the remote memory space.
7327    MYADDR is the address of the buffer in our space.
7328    LEN_UNITS is the number of addressable units to write.
7329    UNIT_SIZE is the length in bytes of an addressable unit.
7330    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7331    should send data as binary ('X'), or hex-encoded ('M').
7332
7333    The function creates packet of the form
7334        <HEADER><ADDRESS>,<LENGTH>:<DATA>
7335
7336    where encoding of <DATA> is terminated by PACKET_FORMAT.
7337
7338    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7339    are omitted.
7340
7341    Return the transferred status, error or OK (an
7342    'enum target_xfer_status' value).  Save the number of addressable units
7343    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
7344
7345    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7346    exchange between gdb and the stub could look like (?? in place of the
7347    checksum):
7348
7349    -> $m1000,4#??
7350    <- aaaabbbbccccdddd
7351
7352    -> $M1000,3:eeeeffffeeee#??
7353    <- OK
7354
7355    -> $m1000,4#??
7356    <- eeeeffffeeeedddd  */
7357
7358 static enum target_xfer_status
7359 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7360                         const gdb_byte *myaddr, ULONGEST len_units,
7361                         int unit_size, ULONGEST *xfered_len_units,
7362                         char packet_format, int use_length)
7363 {
7364   struct remote_state *rs = get_remote_state ();
7365   char *p;
7366   char *plen = NULL;
7367   int plenlen = 0;
7368   int todo_units;
7369   int units_written;
7370   int payload_capacity_bytes;
7371   int payload_length_bytes;
7372
7373   if (packet_format != 'X' && packet_format != 'M')
7374     internal_error (__FILE__, __LINE__,
7375                     _("remote_write_bytes_aux: bad packet format"));
7376
7377   if (len_units == 0)
7378     return TARGET_XFER_EOF;
7379
7380   payload_capacity_bytes = get_memory_write_packet_size ();
7381
7382   /* The packet buffer will be large enough for the payload;
7383      get_memory_packet_size ensures this.  */
7384   rs->buf[0] = '\0';
7385
7386   /* Compute the size of the actual payload by subtracting out the
7387      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
7388
7389   payload_capacity_bytes -= strlen ("$,:#NN");
7390   if (!use_length)
7391     /* The comma won't be used.  */
7392     payload_capacity_bytes += 1;
7393   payload_capacity_bytes -= strlen (header);
7394   payload_capacity_bytes -= hexnumlen (memaddr);
7395
7396   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
7397
7398   strcat (rs->buf, header);
7399   p = rs->buf + strlen (header);
7400
7401   /* Compute a best guess of the number of bytes actually transfered.  */
7402   if (packet_format == 'X')
7403     {
7404       /* Best guess at number of bytes that will fit.  */
7405       todo_units = min (len_units, payload_capacity_bytes / unit_size);
7406       if (use_length)
7407         payload_capacity_bytes -= hexnumlen (todo_units);
7408       todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7409     }
7410   else
7411     {
7412       /* Number of bytes that will fit.  */
7413       todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7414       if (use_length)
7415         payload_capacity_bytes -= hexnumlen (todo_units);
7416       todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7417     }
7418
7419   if (todo_units <= 0)
7420     internal_error (__FILE__, __LINE__,
7421                     _("minimum packet size too small to write data"));
7422
7423   /* If we already need another packet, then try to align the end
7424      of this packet to a useful boundary.  */
7425   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7426     todo_units = align_for_efficient_write (todo_units, memaddr);
7427
7428   /* Append "<memaddr>".  */
7429   memaddr = remote_address_masked (memaddr);
7430   p += hexnumstr (p, (ULONGEST) memaddr);
7431
7432   if (use_length)
7433     {
7434       /* Append ",".  */
7435       *p++ = ',';
7436
7437       /* Append the length and retain its location and size.  It may need to be
7438          adjusted once the packet body has been created.  */
7439       plen = p;
7440       plenlen = hexnumstr (p, (ULONGEST) todo_units);
7441       p += plenlen;
7442     }
7443
7444   /* Append ":".  */
7445   *p++ = ':';
7446   *p = '\0';
7447
7448   /* Append the packet body.  */
7449   if (packet_format == 'X')
7450     {
7451       /* Binary mode.  Send target system values byte by byte, in
7452          increasing byte addresses.  Only escape certain critical
7453          characters.  */
7454       payload_length_bytes =
7455           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7456                                 &units_written, payload_capacity_bytes);
7457
7458       /* If not all TODO units fit, then we'll need another packet.  Make
7459          a second try to keep the end of the packet aligned.  Don't do
7460          this if the packet is tiny.  */
7461       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7462         {
7463           int new_todo_units;
7464
7465           new_todo_units = align_for_efficient_write (units_written, memaddr);
7466
7467           if (new_todo_units != units_written)
7468             payload_length_bytes =
7469                 remote_escape_output (myaddr, new_todo_units, unit_size,
7470                                       (gdb_byte *) p, &units_written,
7471                                       payload_capacity_bytes);
7472         }
7473
7474       p += payload_length_bytes;
7475       if (use_length && units_written < todo_units)
7476         {
7477           /* Escape chars have filled up the buffer prematurely,
7478              and we have actually sent fewer units than planned.
7479              Fix-up the length field of the packet.  Use the same
7480              number of characters as before.  */
7481           plen += hexnumnstr (plen, (ULONGEST) units_written,
7482                               plenlen);
7483           *plen = ':';  /* overwrite \0 from hexnumnstr() */
7484         }
7485     }
7486   else
7487     {
7488       /* Normal mode: Send target system values byte by byte, in
7489          increasing byte addresses.  Each byte is encoded as a two hex
7490          value.  */
7491       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7492       units_written = todo_units;
7493     }
7494
7495   putpkt_binary (rs->buf, (int) (p - rs->buf));
7496   getpkt (&rs->buf, &rs->buf_size, 0);
7497
7498   if (rs->buf[0] == 'E')
7499     return TARGET_XFER_E_IO;
7500
7501   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7502      send fewer units than we'd planned.  */
7503   *xfered_len_units = (ULONGEST) units_written;
7504   return TARGET_XFER_OK;
7505 }
7506
7507 /* Write memory data directly to the remote machine.
7508    This does not inform the data cache; the data cache uses this.
7509    MEMADDR is the address in the remote memory space.
7510    MYADDR is the address of the buffer in our space.
7511    LEN is the number of bytes.
7512
7513    Return the transferred status, error or OK (an
7514    'enum target_xfer_status' value).  Save the number of bytes
7515    transferred in *XFERED_LEN.  Only transfer a single packet.  */
7516
7517 static enum target_xfer_status
7518 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7519                     int unit_size, ULONGEST *xfered_len)
7520 {
7521   char *packet_format = 0;
7522
7523   /* Check whether the target supports binary download.  */
7524   check_binary_download (memaddr);
7525
7526   switch (packet_support (PACKET_X))
7527     {
7528     case PACKET_ENABLE:
7529       packet_format = "X";
7530       break;
7531     case PACKET_DISABLE:
7532       packet_format = "M";
7533       break;
7534     case PACKET_SUPPORT_UNKNOWN:
7535       internal_error (__FILE__, __LINE__,
7536                       _("remote_write_bytes: bad internal state"));
7537     default:
7538       internal_error (__FILE__, __LINE__, _("bad switch"));
7539     }
7540
7541   return remote_write_bytes_aux (packet_format,
7542                                  memaddr, myaddr, len, unit_size, xfered_len,
7543                                  packet_format[0], 1);
7544 }
7545
7546 /* Read memory data directly from the remote machine.
7547    This does not use the data cache; the data cache uses this.
7548    MEMADDR is the address in the remote memory space.
7549    MYADDR is the address of the buffer in our space.
7550    LEN_UNITS is the number of addressable memory units to read..
7551    UNIT_SIZE is the length in bytes of an addressable unit.
7552
7553    Return the transferred status, error or OK (an
7554    'enum target_xfer_status' value).  Save the number of bytes
7555    transferred in *XFERED_LEN_UNITS.
7556
7557    See the comment of remote_write_bytes_aux for an example of
7558    memory read/write exchange between gdb and the stub.  */
7559
7560 static enum target_xfer_status
7561 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7562                      int unit_size, ULONGEST *xfered_len_units)
7563 {
7564   struct remote_state *rs = get_remote_state ();
7565   int buf_size_bytes;           /* Max size of packet output buffer.  */
7566   char *p;
7567   int todo_units;
7568   int decoded_bytes;
7569
7570   buf_size_bytes = get_memory_read_packet_size ();
7571   /* The packet buffer will be large enough for the payload;
7572      get_memory_packet_size ensures this.  */
7573
7574   /* Number of units that will fit.  */
7575   todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7576
7577   /* Construct "m"<memaddr>","<len>".  */
7578   memaddr = remote_address_masked (memaddr);
7579   p = rs->buf;
7580   *p++ = 'm';
7581   p += hexnumstr (p, (ULONGEST) memaddr);
7582   *p++ = ',';
7583   p += hexnumstr (p, (ULONGEST) todo_units);
7584   *p = '\0';
7585   putpkt (rs->buf);
7586   getpkt (&rs->buf, &rs->buf_size, 0);
7587   if (rs->buf[0] == 'E'
7588       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7589       && rs->buf[3] == '\0')
7590     return TARGET_XFER_E_IO;
7591   /* Reply describes memory byte by byte, each byte encoded as two hex
7592      characters.  */
7593   p = rs->buf;
7594   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7595   /* Return what we have.  Let higher layers handle partial reads.  */
7596   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7597   return TARGET_XFER_OK;
7598 }
7599
7600 /* Using the set of read-only target sections of remote, read live
7601    read-only memory.
7602
7603    For interface/parameters/return description see target.h,
7604    to_xfer_partial.  */
7605
7606 static enum target_xfer_status
7607 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7608                                    ULONGEST memaddr, ULONGEST len,
7609                                    int unit_size, ULONGEST *xfered_len)
7610 {
7611   struct target_section *secp;
7612   struct target_section_table *table;
7613
7614   secp = target_section_by_addr (ops, memaddr);
7615   if (secp != NULL
7616       && (bfd_get_section_flags (secp->the_bfd_section->owner,
7617                                  secp->the_bfd_section)
7618           & SEC_READONLY))
7619     {
7620       struct target_section *p;
7621       ULONGEST memend = memaddr + len;
7622
7623       table = target_get_section_table (ops);
7624
7625       for (p = table->sections; p < table->sections_end; p++)
7626         {
7627           if (memaddr >= p->addr)
7628             {
7629               if (memend <= p->endaddr)
7630                 {
7631                   /* Entire transfer is within this section.  */
7632                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7633                                               xfered_len);
7634                 }
7635               else if (memaddr >= p->endaddr)
7636                 {
7637                   /* This section ends before the transfer starts.  */
7638                   continue;
7639                 }
7640               else
7641                 {
7642                   /* This section overlaps the transfer.  Just do half.  */
7643                   len = p->endaddr - memaddr;
7644                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7645                                               xfered_len);
7646                 }
7647             }
7648         }
7649     }
7650
7651   return TARGET_XFER_EOF;
7652 }
7653
7654 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7655    first if the requested memory is unavailable in traceframe.
7656    Otherwise, fall back to remote_read_bytes_1.  */
7657
7658 static enum target_xfer_status
7659 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7660                    gdb_byte *myaddr, ULONGEST len, int unit_size,
7661                    ULONGEST *xfered_len)
7662 {
7663   if (len == 0)
7664     return TARGET_XFER_EOF;
7665
7666   if (get_traceframe_number () != -1)
7667     {
7668       VEC(mem_range_s) *available;
7669
7670       /* If we fail to get the set of available memory, then the
7671          target does not support querying traceframe info, and so we
7672          attempt reading from the traceframe anyway (assuming the
7673          target implements the old QTro packet then).  */
7674       if (traceframe_available_memory (&available, memaddr, len))
7675         {
7676           struct cleanup *old_chain;
7677
7678           old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7679
7680           if (VEC_empty (mem_range_s, available)
7681               || VEC_index (mem_range_s, available, 0)->start != memaddr)
7682             {
7683               enum target_xfer_status res;
7684
7685               /* Don't read into the traceframe's available
7686                  memory.  */
7687               if (!VEC_empty (mem_range_s, available))
7688                 {
7689                   LONGEST oldlen = len;
7690
7691                   len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7692                   gdb_assert (len <= oldlen);
7693                 }
7694
7695               do_cleanups (old_chain);
7696
7697               /* This goes through the topmost target again.  */
7698               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7699                                                        len, unit_size, xfered_len);
7700               if (res == TARGET_XFER_OK)
7701                 return TARGET_XFER_OK;
7702               else
7703                 {
7704                   /* No use trying further, we know some memory starting
7705                      at MEMADDR isn't available.  */
7706                   *xfered_len = len;
7707                   return TARGET_XFER_UNAVAILABLE;
7708                 }
7709             }
7710
7711           /* Don't try to read more than how much is available, in
7712              case the target implements the deprecated QTro packet to
7713              cater for older GDBs (the target's knowledge of read-only
7714              sections may be outdated by now).  */
7715           len = VEC_index (mem_range_s, available, 0)->length;
7716
7717           do_cleanups (old_chain);
7718         }
7719     }
7720
7721   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7722 }
7723
7724 \f
7725
7726 /* Sends a packet with content determined by the printf format string
7727    FORMAT and the remaining arguments, then gets the reply.  Returns
7728    whether the packet was a success, a failure, or unknown.  */
7729
7730 static enum packet_result remote_send_printf (const char *format, ...)
7731   ATTRIBUTE_PRINTF (1, 2);
7732
7733 static enum packet_result
7734 remote_send_printf (const char *format, ...)
7735 {
7736   struct remote_state *rs = get_remote_state ();
7737   int max_size = get_remote_packet_size ();
7738   va_list ap;
7739
7740   va_start (ap, format);
7741
7742   rs->buf[0] = '\0';
7743   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7744     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7745
7746   if (putpkt (rs->buf) < 0)
7747     error (_("Communication problem with target."));
7748
7749   rs->buf[0] = '\0';
7750   getpkt (&rs->buf, &rs->buf_size, 0);
7751
7752   return packet_check_result (rs->buf);
7753 }
7754
7755 static void
7756 restore_remote_timeout (void *p)
7757 {
7758   int value = *(int *)p;
7759
7760   remote_timeout = value;
7761 }
7762
7763 /* Flash writing can take quite some time.  We'll set
7764    effectively infinite timeout for flash operations.
7765    In future, we'll need to decide on a better approach.  */
7766 static const int remote_flash_timeout = 1000;
7767
7768 static void
7769 remote_flash_erase (struct target_ops *ops,
7770                     ULONGEST address, LONGEST length)
7771 {
7772   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7773   int saved_remote_timeout = remote_timeout;
7774   enum packet_result ret;
7775   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7776                                           &saved_remote_timeout);
7777
7778   remote_timeout = remote_flash_timeout;
7779
7780   ret = remote_send_printf ("vFlashErase:%s,%s",
7781                             phex (address, addr_size),
7782                             phex (length, 4));
7783   switch (ret)
7784     {
7785     case PACKET_UNKNOWN:
7786       error (_("Remote target does not support flash erase"));
7787     case PACKET_ERROR:
7788       error (_("Error erasing flash with vFlashErase packet"));
7789     default:
7790       break;
7791     }
7792
7793   do_cleanups (back_to);
7794 }
7795
7796 static enum target_xfer_status
7797 remote_flash_write (struct target_ops *ops, ULONGEST address,
7798                     ULONGEST length, ULONGEST *xfered_len,
7799                     const gdb_byte *data)
7800 {
7801   int saved_remote_timeout = remote_timeout;
7802   enum target_xfer_status ret;
7803   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7804                                           &saved_remote_timeout);
7805
7806   remote_timeout = remote_flash_timeout;
7807   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
7808                                 xfered_len,'X', 0);
7809   do_cleanups (back_to);
7810
7811   return ret;
7812 }
7813
7814 static void
7815 remote_flash_done (struct target_ops *ops)
7816 {
7817   int saved_remote_timeout = remote_timeout;
7818   int ret;
7819   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7820                                           &saved_remote_timeout);
7821
7822   remote_timeout = remote_flash_timeout;
7823   ret = remote_send_printf ("vFlashDone");
7824   do_cleanups (back_to);
7825
7826   switch (ret)
7827     {
7828     case PACKET_UNKNOWN:
7829       error (_("Remote target does not support vFlashDone"));
7830     case PACKET_ERROR:
7831       error (_("Error finishing flash operation"));
7832     default:
7833       break;
7834     }
7835 }
7836
7837 static void
7838 remote_files_info (struct target_ops *ignore)
7839 {
7840   puts_filtered ("Debugging a target over a serial line.\n");
7841 }
7842 \f
7843 /* Stuff for dealing with the packets which are part of this protocol.
7844    See comment at top of file for details.  */
7845
7846 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7847    error to higher layers.  Called when a serial error is detected.
7848    The exception message is STRING, followed by a colon and a blank,
7849    the system error message for errno at function entry and final dot
7850    for output compatibility with throw_perror_with_name.  */
7851
7852 static void
7853 unpush_and_perror (const char *string)
7854 {
7855   int saved_errno = errno;
7856
7857   remote_unpush_target ();
7858   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7859                safe_strerror (saved_errno));
7860 }
7861
7862 /* Read a single character from the remote end.  */
7863
7864 static int
7865 readchar (int timeout)
7866 {
7867   int ch;
7868   struct remote_state *rs = get_remote_state ();
7869
7870   ch = serial_readchar (rs->remote_desc, timeout);
7871
7872   if (ch >= 0)
7873     return ch;
7874
7875   switch ((enum serial_rc) ch)
7876     {
7877     case SERIAL_EOF:
7878       remote_unpush_target ();
7879       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7880       /* no return */
7881     case SERIAL_ERROR:
7882       unpush_and_perror (_("Remote communication error.  "
7883                            "Target disconnected."));
7884       /* no return */
7885     case SERIAL_TIMEOUT:
7886       break;
7887     }
7888   return ch;
7889 }
7890
7891 /* Wrapper for serial_write that closes the target and throws if
7892    writing fails.  */
7893
7894 static void
7895 remote_serial_write (const char *str, int len)
7896 {
7897   struct remote_state *rs = get_remote_state ();
7898
7899   if (serial_write (rs->remote_desc, str, len))
7900     {
7901       unpush_and_perror (_("Remote communication error.  "
7902                            "Target disconnected."));
7903     }
7904 }
7905
7906 /* Send the command in *BUF to the remote machine, and read the reply
7907    into *BUF.  Report an error if we get an error reply.  Resize
7908    *BUF using xrealloc if necessary to hold the result, and update
7909    *SIZEOF_BUF.  */
7910
7911 static void
7912 remote_send (char **buf,
7913              long *sizeof_buf)
7914 {
7915   putpkt (*buf);
7916   getpkt (buf, sizeof_buf, 0);
7917
7918   if ((*buf)[0] == 'E')
7919     error (_("Remote failure reply: %s"), *buf);
7920 }
7921
7922 /* Return a pointer to an xmalloc'ed string representing an escaped
7923    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
7924    etc.  The caller is responsible for releasing the returned
7925    memory.  */
7926
7927 static char *
7928 escape_buffer (const char *buf, int n)
7929 {
7930   struct cleanup *old_chain;
7931   struct ui_file *stb;
7932   char *str;
7933
7934   stb = mem_fileopen ();
7935   old_chain = make_cleanup_ui_file_delete (stb);
7936
7937   fputstrn_unfiltered (buf, n, '\\', stb);
7938   str = ui_file_xstrdup (stb, NULL);
7939   do_cleanups (old_chain);
7940   return str;
7941 }
7942
7943 /* Display a null-terminated packet on stdout, for debugging, using C
7944    string notation.  */
7945
7946 static void
7947 print_packet (const char *buf)
7948 {
7949   puts_filtered ("\"");
7950   fputstr_filtered (buf, '"', gdb_stdout);
7951   puts_filtered ("\"");
7952 }
7953
7954 int
7955 putpkt (const char *buf)
7956 {
7957   return putpkt_binary (buf, strlen (buf));
7958 }
7959
7960 /* Send a packet to the remote machine, with error checking.  The data
7961    of the packet is in BUF.  The string in BUF can be at most
7962    get_remote_packet_size () - 5 to account for the $, # and checksum,
7963    and for a possible /0 if we are debugging (remote_debug) and want
7964    to print the sent packet as a string.  */
7965
7966 static int
7967 putpkt_binary (const char *buf, int cnt)
7968 {
7969   struct remote_state *rs = get_remote_state ();
7970   int i;
7971   unsigned char csum = 0;
7972   char *buf2 = (char *) xmalloc (cnt + 6);
7973   struct cleanup *old_chain = make_cleanup (xfree, buf2);
7974
7975   int ch;
7976   int tcount = 0;
7977   char *p;
7978   char *message;
7979
7980   /* Catch cases like trying to read memory or listing threads while
7981      we're waiting for a stop reply.  The remote server wouldn't be
7982      ready to handle this request, so we'd hang and timeout.  We don't
7983      have to worry about this in synchronous mode, because in that
7984      case it's not possible to issue a command while the target is
7985      running.  This is not a problem in non-stop mode, because in that
7986      case, the stub is always ready to process serial input.  */
7987   if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7988     {
7989       error (_("Cannot execute this command while the target is running.\n"
7990                "Use the \"interrupt\" command to stop the target\n"
7991                "and then try again."));
7992     }
7993
7994   /* We're sending out a new packet.  Make sure we don't look at a
7995      stale cached response.  */
7996   rs->cached_wait_status = 0;
7997
7998   /* Copy the packet into buffer BUF2, encapsulating it
7999      and giving it a checksum.  */
8000
8001   p = buf2;
8002   *p++ = '$';
8003
8004   for (i = 0; i < cnt; i++)
8005     {
8006       csum += buf[i];
8007       *p++ = buf[i];
8008     }
8009   *p++ = '#';
8010   *p++ = tohex ((csum >> 4) & 0xf);
8011   *p++ = tohex (csum & 0xf);
8012
8013   /* Send it over and over until we get a positive ack.  */
8014
8015   while (1)
8016     {
8017       int started_error_output = 0;
8018
8019       if (remote_debug)
8020         {
8021           struct cleanup *old_chain;
8022           char *str;
8023
8024           *p = '\0';
8025           str = escape_buffer (buf2, p - buf2);
8026           old_chain = make_cleanup (xfree, str);
8027           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8028           gdb_flush (gdb_stdlog);
8029           do_cleanups (old_chain);
8030         }
8031       remote_serial_write (buf2, p - buf2);
8032
8033       /* If this is a no acks version of the remote protocol, send the
8034          packet and move on.  */
8035       if (rs->noack_mode)
8036         break;
8037
8038       /* Read until either a timeout occurs (-2) or '+' is read.
8039          Handle any notification that arrives in the mean time.  */
8040       while (1)
8041         {
8042           ch = readchar (remote_timeout);
8043
8044           if (remote_debug)
8045             {
8046               switch (ch)
8047                 {
8048                 case '+':
8049                 case '-':
8050                 case SERIAL_TIMEOUT:
8051                 case '$':
8052                 case '%':
8053                   if (started_error_output)
8054                     {
8055                       putchar_unfiltered ('\n');
8056                       started_error_output = 0;
8057                     }
8058                 }
8059             }
8060
8061           switch (ch)
8062             {
8063             case '+':
8064               if (remote_debug)
8065                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8066               do_cleanups (old_chain);
8067               return 1;
8068             case '-':
8069               if (remote_debug)
8070                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8071               /* FALLTHROUGH */
8072             case SERIAL_TIMEOUT:
8073               tcount++;
8074               if (tcount > 3)
8075                 {
8076                   do_cleanups (old_chain);
8077                   return 0;
8078                 }
8079               break;            /* Retransmit buffer.  */
8080             case '$':
8081               {
8082                 if (remote_debug)
8083                   fprintf_unfiltered (gdb_stdlog,
8084                                       "Packet instead of Ack, ignoring it\n");
8085                 /* It's probably an old response sent because an ACK
8086                    was lost.  Gobble up the packet and ack it so it
8087                    doesn't get retransmitted when we resend this
8088                    packet.  */
8089                 skip_frame ();
8090                 remote_serial_write ("+", 1);
8091                 continue;       /* Now, go look for +.  */
8092               }
8093
8094             case '%':
8095               {
8096                 int val;
8097
8098                 /* If we got a notification, handle it, and go back to looking
8099                    for an ack.  */
8100                 /* We've found the start of a notification.  Now
8101                    collect the data.  */
8102                 val = read_frame (&rs->buf, &rs->buf_size);
8103                 if (val >= 0)
8104                   {
8105                     if (remote_debug)
8106                       {
8107                         struct cleanup *old_chain;
8108                         char *str;
8109
8110                         str = escape_buffer (rs->buf, val);
8111                         old_chain = make_cleanup (xfree, str);
8112                         fprintf_unfiltered (gdb_stdlog,
8113                                             "  Notification received: %s\n",
8114                                             str);
8115                         do_cleanups (old_chain);
8116                       }
8117                     handle_notification (rs->notif_state, rs->buf);
8118                     /* We're in sync now, rewait for the ack.  */
8119                     tcount = 0;
8120                   }
8121                 else
8122                   {
8123                     if (remote_debug)
8124                       {
8125                         if (!started_error_output)
8126                           {
8127                             started_error_output = 1;
8128                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8129                           }
8130                         fputc_unfiltered (ch & 0177, gdb_stdlog);
8131                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8132                       }
8133                   }
8134                 continue;
8135               }
8136               /* fall-through */
8137             default:
8138               if (remote_debug)
8139                 {
8140                   if (!started_error_output)
8141                     {
8142                       started_error_output = 1;
8143                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8144                     }
8145                   fputc_unfiltered (ch & 0177, gdb_stdlog);
8146                 }
8147               continue;
8148             }
8149           break;                /* Here to retransmit.  */
8150         }
8151
8152 #if 0
8153       /* This is wrong.  If doing a long backtrace, the user should be
8154          able to get out next time we call QUIT, without anything as
8155          violent as interrupt_query.  If we want to provide a way out of
8156          here without getting to the next QUIT, it should be based on
8157          hitting ^C twice as in remote_wait.  */
8158       if (quit_flag)
8159         {
8160           quit_flag = 0;
8161           interrupt_query ();
8162         }
8163 #endif
8164     }
8165
8166   do_cleanups (old_chain);
8167   return 0;
8168 }
8169
8170 /* Come here after finding the start of a frame when we expected an
8171    ack.  Do our best to discard the rest of this packet.  */
8172
8173 static void
8174 skip_frame (void)
8175 {
8176   int c;
8177
8178   while (1)
8179     {
8180       c = readchar (remote_timeout);
8181       switch (c)
8182         {
8183         case SERIAL_TIMEOUT:
8184           /* Nothing we can do.  */
8185           return;
8186         case '#':
8187           /* Discard the two bytes of checksum and stop.  */
8188           c = readchar (remote_timeout);
8189           if (c >= 0)
8190             c = readchar (remote_timeout);
8191
8192           return;
8193         case '*':               /* Run length encoding.  */
8194           /* Discard the repeat count.  */
8195           c = readchar (remote_timeout);
8196           if (c < 0)
8197             return;
8198           break;
8199         default:
8200           /* A regular character.  */
8201           break;
8202         }
8203     }
8204 }
8205
8206 /* Come here after finding the start of the frame.  Collect the rest
8207    into *BUF, verifying the checksum, length, and handling run-length
8208    compression.  NUL terminate the buffer.  If there is not enough room,
8209    expand *BUF using xrealloc.
8210
8211    Returns -1 on error, number of characters in buffer (ignoring the
8212    trailing NULL) on success. (could be extended to return one of the
8213    SERIAL status indications).  */
8214
8215 static long
8216 read_frame (char **buf_p,
8217             long *sizeof_buf)
8218 {
8219   unsigned char csum;
8220   long bc;
8221   int c;
8222   char *buf = *buf_p;
8223   struct remote_state *rs = get_remote_state ();
8224
8225   csum = 0;
8226   bc = 0;
8227
8228   while (1)
8229     {
8230       c = readchar (remote_timeout);
8231       switch (c)
8232         {
8233         case SERIAL_TIMEOUT:
8234           if (remote_debug)
8235             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8236           return -1;
8237         case '$':
8238           if (remote_debug)
8239             fputs_filtered ("Saw new packet start in middle of old one\n",
8240                             gdb_stdlog);
8241           return -1;            /* Start a new packet, count retries.  */
8242         case '#':
8243           {
8244             unsigned char pktcsum;
8245             int check_0 = 0;
8246             int check_1 = 0;
8247
8248             buf[bc] = '\0';
8249
8250             check_0 = readchar (remote_timeout);
8251             if (check_0 >= 0)
8252               check_1 = readchar (remote_timeout);
8253
8254             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8255               {
8256                 if (remote_debug)
8257                   fputs_filtered ("Timeout in checksum, retrying\n",
8258                                   gdb_stdlog);
8259                 return -1;
8260               }
8261             else if (check_0 < 0 || check_1 < 0)
8262               {
8263                 if (remote_debug)
8264                   fputs_filtered ("Communication error in checksum\n",
8265                                   gdb_stdlog);
8266                 return -1;
8267               }
8268
8269             /* Don't recompute the checksum; with no ack packets we
8270                don't have any way to indicate a packet retransmission
8271                is necessary.  */
8272             if (rs->noack_mode)
8273               return bc;
8274
8275             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8276             if (csum == pktcsum)
8277               return bc;
8278
8279             if (remote_debug)
8280               {
8281                 struct cleanup *old_chain;
8282                 char *str;
8283
8284                 str = escape_buffer (buf, bc);
8285                 old_chain = make_cleanup (xfree, str);
8286                 fprintf_unfiltered (gdb_stdlog,
8287                                     "Bad checksum, sentsum=0x%x, "
8288                                     "csum=0x%x, buf=%s\n",
8289                                     pktcsum, csum, str);
8290                 do_cleanups (old_chain);
8291               }
8292             /* Number of characters in buffer ignoring trailing
8293                NULL.  */
8294             return -1;
8295           }
8296         case '*':               /* Run length encoding.  */
8297           {
8298             int repeat;
8299
8300             csum += c;
8301             c = readchar (remote_timeout);
8302             csum += c;
8303             repeat = c - ' ' + 3;       /* Compute repeat count.  */
8304
8305             /* The character before ``*'' is repeated.  */
8306
8307             if (repeat > 0 && repeat <= 255 && bc > 0)
8308               {
8309                 if (bc + repeat - 1 >= *sizeof_buf - 1)
8310                   {
8311                     /* Make some more room in the buffer.  */
8312                     *sizeof_buf += repeat;
8313                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8314                     buf = *buf_p;
8315                   }
8316
8317                 memset (&buf[bc], buf[bc - 1], repeat);
8318                 bc += repeat;
8319                 continue;
8320               }
8321
8322             buf[bc] = '\0';
8323             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8324             return -1;
8325           }
8326         default:
8327           if (bc >= *sizeof_buf - 1)
8328             {
8329               /* Make some more room in the buffer.  */
8330               *sizeof_buf *= 2;
8331               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8332               buf = *buf_p;
8333             }
8334
8335           buf[bc++] = c;
8336           csum += c;
8337           continue;
8338         }
8339     }
8340 }
8341
8342 /* Read a packet from the remote machine, with error checking, and
8343    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8344    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8345    rather than timing out; this is used (in synchronous mode) to wait
8346    for a target that is is executing user code to stop.  */
8347 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8348    don't have to change all the calls to getpkt to deal with the
8349    return value, because at the moment I don't know what the right
8350    thing to do it for those.  */
8351 void
8352 getpkt (char **buf,
8353         long *sizeof_buf,
8354         int forever)
8355 {
8356   int timed_out;
8357
8358   timed_out = getpkt_sane (buf, sizeof_buf, forever);
8359 }
8360
8361
8362 /* Read a packet from the remote machine, with error checking, and
8363    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8364    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8365    rather than timing out; this is used (in synchronous mode) to wait
8366    for a target that is is executing user code to stop.  If FOREVER ==
8367    0, this function is allowed to time out gracefully and return an
8368    indication of this to the caller.  Otherwise return the number of
8369    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
8370    enough reason to return to the caller.  *IS_NOTIF is an output
8371    boolean that indicates whether *BUF holds a notification or not
8372    (a regular packet).  */
8373
8374 static int
8375 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8376                         int expecting_notif, int *is_notif)
8377 {
8378   struct remote_state *rs = get_remote_state ();
8379   int c;
8380   int tries;
8381   int timeout;
8382   int val = -1;
8383
8384   /* We're reading a new response.  Make sure we don't look at a
8385      previously cached response.  */
8386   rs->cached_wait_status = 0;
8387
8388   strcpy (*buf, "timeout");
8389
8390   if (forever)
8391     timeout = watchdog > 0 ? watchdog : -1;
8392   else if (expecting_notif)
8393     timeout = 0; /* There should already be a char in the buffer.  If
8394                     not, bail out.  */
8395   else
8396     timeout = remote_timeout;
8397
8398 #define MAX_TRIES 3
8399
8400   /* Process any number of notifications, and then return when
8401      we get a packet.  */
8402   for (;;)
8403     {
8404       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8405          times.  */
8406       for (tries = 1; tries <= MAX_TRIES; tries++)
8407         {
8408           /* This can loop forever if the remote side sends us
8409              characters continuously, but if it pauses, we'll get
8410              SERIAL_TIMEOUT from readchar because of timeout.  Then
8411              we'll count that as a retry.
8412
8413              Note that even when forever is set, we will only wait
8414              forever prior to the start of a packet.  After that, we
8415              expect characters to arrive at a brisk pace.  They should
8416              show up within remote_timeout intervals.  */
8417           do
8418             c = readchar (timeout);
8419           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8420
8421           if (c == SERIAL_TIMEOUT)
8422             {
8423               if (expecting_notif)
8424                 return -1; /* Don't complain, it's normal to not get
8425                               anything in this case.  */
8426
8427               if (forever)      /* Watchdog went off?  Kill the target.  */
8428                 {
8429                   QUIT;
8430                   remote_unpush_target ();
8431                   throw_error (TARGET_CLOSE_ERROR,
8432                                _("Watchdog timeout has expired.  "
8433                                  "Target detached."));
8434                 }
8435               if (remote_debug)
8436                 fputs_filtered ("Timed out.\n", gdb_stdlog);
8437             }
8438           else
8439             {
8440               /* We've found the start of a packet or notification.
8441                  Now collect the data.  */
8442               val = read_frame (buf, sizeof_buf);
8443               if (val >= 0)
8444                 break;
8445             }
8446
8447           remote_serial_write ("-", 1);
8448         }
8449
8450       if (tries > MAX_TRIES)
8451         {
8452           /* We have tried hard enough, and just can't receive the
8453              packet/notification.  Give up.  */
8454           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8455
8456           /* Skip the ack char if we're in no-ack mode.  */
8457           if (!rs->noack_mode)
8458             remote_serial_write ("+", 1);
8459           return -1;
8460         }
8461
8462       /* If we got an ordinary packet, return that to our caller.  */
8463       if (c == '$')
8464         {
8465           if (remote_debug)
8466             {
8467              struct cleanup *old_chain;
8468              char *str;
8469
8470              str = escape_buffer (*buf, val);
8471              old_chain = make_cleanup (xfree, str);
8472              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8473              do_cleanups (old_chain);
8474             }
8475
8476           /* Skip the ack char if we're in no-ack mode.  */
8477           if (!rs->noack_mode)
8478             remote_serial_write ("+", 1);
8479           if (is_notif != NULL)
8480             *is_notif = 0;
8481           return val;
8482         }
8483
8484        /* If we got a notification, handle it, and go back to looking
8485          for a packet.  */
8486       else
8487         {
8488           gdb_assert (c == '%');
8489
8490           if (remote_debug)
8491             {
8492               struct cleanup *old_chain;
8493               char *str;
8494
8495               str = escape_buffer (*buf, val);
8496               old_chain = make_cleanup (xfree, str);
8497               fprintf_unfiltered (gdb_stdlog,
8498                                   "  Notification received: %s\n",
8499                                   str);
8500               do_cleanups (old_chain);
8501             }
8502           if (is_notif != NULL)
8503             *is_notif = 1;
8504
8505           handle_notification (rs->notif_state, *buf);
8506
8507           /* Notifications require no acknowledgement.  */
8508
8509           if (expecting_notif)
8510             return val;
8511         }
8512     }
8513 }
8514
8515 static int
8516 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8517 {
8518   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8519 }
8520
8521 static int
8522 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8523                       int *is_notif)
8524 {
8525   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8526                                  is_notif);
8527 }
8528
8529 /* Check whether EVENT is a fork event for the process specified
8530    by the pid passed in DATA, and if it is, kill the fork child.  */
8531
8532 static int
8533 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8534                             QUEUE_ITER (stop_reply_p) *iter,
8535                             stop_reply_p event,
8536                             void *data)
8537 {
8538   struct queue_iter_param *param = (struct queue_iter_param *) data;
8539   int parent_pid = *(int *) param->input;
8540
8541   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8542     {
8543       struct remote_state *rs = get_remote_state ();
8544       int child_pid = ptid_get_pid (event->ws.value.related_pid);
8545       int res;
8546
8547       res = remote_vkill (child_pid, rs);
8548       if (res != 0)
8549         error (_("Can't kill fork child process %d"), child_pid);
8550     }
8551
8552   return 1;
8553 }
8554
8555 /* Kill any new fork children of process PID that haven't been
8556    processed by follow_fork.  */
8557
8558 static void
8559 kill_new_fork_children (int pid, struct remote_state *rs)
8560 {
8561   struct thread_info *thread;
8562   struct notif_client *notif = &notif_client_stop;
8563   struct queue_iter_param param;
8564
8565   /* Kill the fork child threads of any threads in process PID
8566      that are stopped at a fork event.  */
8567   ALL_NON_EXITED_THREADS (thread)
8568     {
8569       struct target_waitstatus *ws = &thread->pending_follow;
8570
8571       if (is_pending_fork_parent (ws, pid, thread->ptid))
8572         {
8573           struct remote_state *rs = get_remote_state ();
8574           int child_pid = ptid_get_pid (ws->value.related_pid);
8575           int res;
8576
8577           res = remote_vkill (child_pid, rs);
8578           if (res != 0)
8579             error (_("Can't kill fork child process %d"), child_pid);
8580         }
8581     }
8582
8583   /* Check for any pending fork events (not reported or processed yet)
8584      in process PID and kill those fork child threads as well.  */
8585   remote_notif_get_pending_events (notif);
8586   param.input = &pid;
8587   param.output = NULL;
8588   QUEUE_iterate (stop_reply_p, stop_reply_queue,
8589                  kill_child_of_pending_fork, &param);
8590 }
8591
8592 \f
8593 static void
8594 remote_kill (struct target_ops *ops)
8595 {
8596
8597   /* Catch errors so the user can quit from gdb even when we
8598      aren't on speaking terms with the remote system.  */
8599   TRY
8600     {
8601       putpkt ("k");
8602     }
8603   CATCH (ex, RETURN_MASK_ERROR)
8604     {
8605       if (ex.error == TARGET_CLOSE_ERROR)
8606         {
8607           /* If we got an (EOF) error that caused the target
8608              to go away, then we're done, that's what we wanted.
8609              "k" is susceptible to cause a premature EOF, given
8610              that the remote server isn't actually required to
8611              reply to "k", and it can happen that it doesn't
8612              even get to reply ACK to the "k".  */
8613           return;
8614         }
8615
8616         /* Otherwise, something went wrong.  We didn't actually kill
8617            the target.  Just propagate the exception, and let the
8618            user or higher layers decide what to do.  */
8619         throw_exception (ex);
8620     }
8621   END_CATCH
8622
8623   /* We've killed the remote end, we get to mourn it.  Since this is
8624      target remote, single-process, mourning the inferior also
8625      unpushes remote_ops.  */
8626   target_mourn_inferior ();
8627 }
8628
8629 static int
8630 remote_vkill (int pid, struct remote_state *rs)
8631 {
8632   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8633     return -1;
8634
8635   /* Tell the remote target to detach.  */
8636   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8637   putpkt (rs->buf);
8638   getpkt (&rs->buf, &rs->buf_size, 0);
8639
8640   switch (packet_ok (rs->buf,
8641                      &remote_protocol_packets[PACKET_vKill]))
8642     {
8643     case PACKET_OK:
8644       return 0;
8645     case PACKET_ERROR:
8646       return 1;
8647     case PACKET_UNKNOWN:
8648       return -1;
8649     default:
8650       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8651     }
8652 }
8653
8654 static void
8655 extended_remote_kill (struct target_ops *ops)
8656 {
8657   int res;
8658   int pid = ptid_get_pid (inferior_ptid);
8659   struct remote_state *rs = get_remote_state ();
8660
8661   /* If we're stopped while forking and we haven't followed yet, kill the
8662      child task.  We need to do this before killing the parent task
8663      because if this is a vfork then the parent will be sleeping.  */
8664   kill_new_fork_children (pid, rs);
8665
8666   res = remote_vkill (pid, rs);
8667   if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8668     {
8669       /* Don't try 'k' on a multi-process aware stub -- it has no way
8670          to specify the pid.  */
8671
8672       putpkt ("k");
8673 #if 0
8674       getpkt (&rs->buf, &rs->buf_size, 0);
8675       if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8676         res = 1;
8677 #else
8678       /* Don't wait for it to die.  I'm not really sure it matters whether
8679          we do or not.  For the existing stubs, kill is a noop.  */
8680       res = 0;
8681 #endif
8682     }
8683
8684   if (res != 0)
8685     error (_("Can't kill process"));
8686
8687   target_mourn_inferior ();
8688 }
8689
8690 static void
8691 remote_mourn (struct target_ops *target)
8692 {
8693   unpush_target (target);
8694
8695   /* remote_close takes care of doing most of the clean up.  */
8696   generic_mourn_inferior ();
8697 }
8698
8699 static void
8700 extended_remote_mourn (struct target_ops *target)
8701 {
8702   struct remote_state *rs = get_remote_state ();
8703
8704   /* In case we got here due to an error, but we're going to stay
8705      connected.  */
8706   rs->waiting_for_stop_reply = 0;
8707
8708   /* If the current general thread belonged to the process we just
8709      detached from or has exited, the remote side current general
8710      thread becomes undefined.  Considering a case like this:
8711
8712      - We just got here due to a detach.
8713      - The process that we're detaching from happens to immediately
8714        report a global breakpoint being hit in non-stop mode, in the
8715        same thread we had selected before.
8716      - GDB attaches to this process again.
8717      - This event happens to be the next event we handle.
8718
8719      GDB would consider that the current general thread didn't need to
8720      be set on the stub side (with Hg), since for all it knew,
8721      GENERAL_THREAD hadn't changed.
8722
8723      Notice that although in all-stop mode, the remote server always
8724      sets the current thread to the thread reporting the stop event,
8725      that doesn't happen in non-stop mode; in non-stop, the stub *must
8726      not* change the current thread when reporting a breakpoint hit,
8727      due to the decoupling of event reporting and event handling.
8728
8729      To keep things simple, we always invalidate our notion of the
8730      current thread.  */
8731   record_currthread (rs, minus_one_ptid);
8732
8733   /* Unlike "target remote", we do not want to unpush the target; then
8734      the next time the user says "run", we won't be connected.  */
8735
8736   /* Call common code to mark the inferior as not running.      */
8737   generic_mourn_inferior ();
8738
8739   if (!have_inferiors ())
8740     {
8741       if (!remote_multi_process_p (rs))
8742         {
8743           /* Check whether the target is running now - some remote stubs
8744              automatically restart after kill.  */
8745           putpkt ("?");
8746           getpkt (&rs->buf, &rs->buf_size, 0);
8747
8748           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8749             {
8750               /* Assume that the target has been restarted.  Set
8751                  inferior_ptid so that bits of core GDB realizes
8752                  there's something here, e.g., so that the user can
8753                  say "kill" again.  */
8754               inferior_ptid = magic_null_ptid;
8755             }
8756         }
8757     }
8758 }
8759
8760 static int
8761 extended_remote_supports_disable_randomization (struct target_ops *self)
8762 {
8763   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8764 }
8765
8766 static void
8767 extended_remote_disable_randomization (int val)
8768 {
8769   struct remote_state *rs = get_remote_state ();
8770   char *reply;
8771
8772   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8773              val);
8774   putpkt (rs->buf);
8775   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8776   if (*reply == '\0')
8777     error (_("Target does not support QDisableRandomization."));
8778   if (strcmp (reply, "OK") != 0)
8779     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8780 }
8781
8782 static int
8783 extended_remote_run (char *args)
8784 {
8785   struct remote_state *rs = get_remote_state ();
8786   int len;
8787   const char *remote_exec_file = get_remote_exec_file ();
8788
8789   /* If the user has disabled vRun support, or we have detected that
8790      support is not available, do not try it.  */
8791   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8792     return -1;
8793
8794   strcpy (rs->buf, "vRun;");
8795   len = strlen (rs->buf);
8796
8797   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8798     error (_("Remote file name too long for run packet"));
8799   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8800                       strlen (remote_exec_file));
8801
8802   gdb_assert (args != NULL);
8803   if (*args)
8804     {
8805       struct cleanup *back_to;
8806       int i;
8807       char **argv;
8808
8809       argv = gdb_buildargv (args);
8810       back_to = make_cleanup_freeargv (argv);
8811       for (i = 0; argv[i] != NULL; i++)
8812         {
8813           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8814             error (_("Argument list too long for run packet"));
8815           rs->buf[len++] = ';';
8816           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8817                               strlen (argv[i]));
8818         }
8819       do_cleanups (back_to);
8820     }
8821
8822   rs->buf[len++] = '\0';
8823
8824   putpkt (rs->buf);
8825   getpkt (&rs->buf, &rs->buf_size, 0);
8826
8827   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8828     {
8829     case PACKET_OK:
8830       /* We have a wait response.  All is well.  */
8831       return 0;
8832     case PACKET_UNKNOWN:
8833       return -1;
8834     case PACKET_ERROR:
8835       if (remote_exec_file[0] == '\0')
8836         error (_("Running the default executable on the remote target failed; "
8837                  "try \"set remote exec-file\"?"));
8838       else
8839         error (_("Running \"%s\" on the remote target failed"),
8840                remote_exec_file);
8841     default:
8842       gdb_assert_not_reached (_("bad switch"));
8843     }
8844 }
8845
8846 /* In the extended protocol we want to be able to do things like
8847    "run" and have them basically work as expected.  So we need
8848    a special create_inferior function.  We support changing the
8849    executable file and the command line arguments, but not the
8850    environment.  */
8851
8852 static void
8853 extended_remote_create_inferior (struct target_ops *ops,
8854                                  char *exec_file, char *args,
8855                                  char **env, int from_tty)
8856 {
8857   int run_worked;
8858   char *stop_reply;
8859   struct remote_state *rs = get_remote_state ();
8860   const char *remote_exec_file = get_remote_exec_file ();
8861
8862   /* If running asynchronously, register the target file descriptor
8863      with the event loop.  */
8864   if (target_can_async_p ())
8865     target_async (1);
8866
8867   /* Disable address space randomization if requested (and supported).  */
8868   if (extended_remote_supports_disable_randomization (ops))
8869     extended_remote_disable_randomization (disable_randomization);
8870
8871   /* Now restart the remote server.  */
8872   run_worked = extended_remote_run (args) != -1;
8873   if (!run_worked)
8874     {
8875       /* vRun was not supported.  Fail if we need it to do what the
8876          user requested.  */
8877       if (remote_exec_file[0])
8878         error (_("Remote target does not support \"set remote exec-file\""));
8879       if (args[0])
8880         error (_("Remote target does not support \"set args\" or run <ARGS>"));
8881
8882       /* Fall back to "R".  */
8883       extended_remote_restart ();
8884     }
8885
8886   if (!have_inferiors ())
8887     {
8888       /* Clean up from the last time we ran, before we mark the target
8889          running again.  This will mark breakpoints uninserted, and
8890          get_offsets may insert breakpoints.  */
8891       init_thread_list ();
8892       init_wait_for_inferior ();
8893     }
8894
8895   /* vRun's success return is a stop reply.  */
8896   stop_reply = run_worked ? rs->buf : NULL;
8897   add_current_inferior_and_thread (stop_reply);
8898
8899   /* Get updated offsets, if the stub uses qOffsets.  */
8900   get_offsets ();
8901 }
8902 \f
8903
8904 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
8905    the list of conditions (in agent expression bytecode format), if any, the
8906    target needs to evaluate.  The output is placed into the packet buffer
8907    started from BUF and ended at BUF_END.  */
8908
8909 static int
8910 remote_add_target_side_condition (struct gdbarch *gdbarch,
8911                                   struct bp_target_info *bp_tgt, char *buf,
8912                                   char *buf_end)
8913 {
8914   struct agent_expr *aexpr = NULL;
8915   int i, ix;
8916   char *pkt;
8917   char *buf_start = buf;
8918
8919   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8920     return 0;
8921
8922   buf += strlen (buf);
8923   xsnprintf (buf, buf_end - buf, "%s", ";");
8924   buf++;
8925
8926   /* Send conditions to the target and free the vector.  */
8927   for (ix = 0;
8928        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8929        ix++)
8930     {
8931       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8932       buf += strlen (buf);
8933       for (i = 0; i < aexpr->len; ++i)
8934         buf = pack_hex_byte (buf, aexpr->buf[i]);
8935       *buf = '\0';
8936     }
8937   return 0;
8938 }
8939
8940 static void
8941 remote_add_target_side_commands (struct gdbarch *gdbarch,
8942                                  struct bp_target_info *bp_tgt, char *buf)
8943 {
8944   struct agent_expr *aexpr = NULL;
8945   int i, ix;
8946
8947   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8948     return;
8949
8950   buf += strlen (buf);
8951
8952   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8953   buf += strlen (buf);
8954
8955   /* Concatenate all the agent expressions that are commands into the
8956      cmds parameter.  */
8957   for (ix = 0;
8958        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8959        ix++)
8960     {
8961       sprintf (buf, "X%x,", aexpr->len);
8962       buf += strlen (buf);
8963       for (i = 0; i < aexpr->len; ++i)
8964         buf = pack_hex_byte (buf, aexpr->buf[i]);
8965       *buf = '\0';
8966     }
8967 }
8968
8969 /* Insert a breakpoint.  On targets that have software breakpoint
8970    support, we ask the remote target to do the work; on targets
8971    which don't, we insert a traditional memory breakpoint.  */
8972
8973 static int
8974 remote_insert_breakpoint (struct target_ops *ops,
8975                           struct gdbarch *gdbarch,
8976                           struct bp_target_info *bp_tgt)
8977 {
8978   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8979      If it succeeds, then set the support to PACKET_ENABLE.  If it
8980      fails, and the user has explicitly requested the Z support then
8981      report an error, otherwise, mark it disabled and go on.  */
8982
8983   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8984     {
8985       CORE_ADDR addr = bp_tgt->reqstd_address;
8986       struct remote_state *rs;
8987       char *p, *endbuf;
8988       int bpsize;
8989       struct condition_list *cond = NULL;
8990
8991       /* Make sure the remote is pointing at the right process, if
8992          necessary.  */
8993       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8994         set_general_process ();
8995
8996       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8997
8998       rs = get_remote_state ();
8999       p = rs->buf;
9000       endbuf = rs->buf + get_remote_packet_size ();
9001
9002       *(p++) = 'Z';
9003       *(p++) = '0';
9004       *(p++) = ',';
9005       addr = (ULONGEST) remote_address_masked (addr);
9006       p += hexnumstr (p, addr);
9007       xsnprintf (p, endbuf - p, ",%d", bpsize);
9008
9009       if (remote_supports_cond_breakpoints (ops))
9010         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9011
9012       if (remote_can_run_breakpoint_commands (ops))
9013         remote_add_target_side_commands (gdbarch, bp_tgt, p);
9014
9015       putpkt (rs->buf);
9016       getpkt (&rs->buf, &rs->buf_size, 0);
9017
9018       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9019         {
9020         case PACKET_ERROR:
9021           return -1;
9022         case PACKET_OK:
9023           bp_tgt->placed_address = addr;
9024           bp_tgt->placed_size = bpsize;
9025           return 0;
9026         case PACKET_UNKNOWN:
9027           break;
9028         }
9029     }
9030
9031   /* If this breakpoint has target-side commands but this stub doesn't
9032      support Z0 packets, throw error.  */
9033   if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9034     throw_error (NOT_SUPPORTED_ERROR, _("\
9035 Target doesn't support breakpoints that have target side commands."));
9036
9037   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9038 }
9039
9040 static int
9041 remote_remove_breakpoint (struct target_ops *ops,
9042                           struct gdbarch *gdbarch,
9043                           struct bp_target_info *bp_tgt)
9044 {
9045   CORE_ADDR addr = bp_tgt->placed_address;
9046   struct remote_state *rs = get_remote_state ();
9047
9048   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9049     {
9050       char *p = rs->buf;
9051       char *endbuf = rs->buf + get_remote_packet_size ();
9052
9053       /* Make sure the remote is pointing at the right process, if
9054          necessary.  */
9055       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9056         set_general_process ();
9057
9058       *(p++) = 'z';
9059       *(p++) = '0';
9060       *(p++) = ',';
9061
9062       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9063       p += hexnumstr (p, addr);
9064       xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9065
9066       putpkt (rs->buf);
9067       getpkt (&rs->buf, &rs->buf_size, 0);
9068
9069       return (rs->buf[0] == 'E');
9070     }
9071
9072   return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9073 }
9074
9075 static enum Z_packet_type
9076 watchpoint_to_Z_packet (int type)
9077 {
9078   switch (type)
9079     {
9080     case hw_write:
9081       return Z_PACKET_WRITE_WP;
9082       break;
9083     case hw_read:
9084       return Z_PACKET_READ_WP;
9085       break;
9086     case hw_access:
9087       return Z_PACKET_ACCESS_WP;
9088       break;
9089     default:
9090       internal_error (__FILE__, __LINE__,
9091                       _("hw_bp_to_z: bad watchpoint type %d"), type);
9092     }
9093 }
9094
9095 static int
9096 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9097                           enum target_hw_bp_type type, struct expression *cond)
9098 {
9099   struct remote_state *rs = get_remote_state ();
9100   char *endbuf = rs->buf + get_remote_packet_size ();
9101   char *p;
9102   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9103
9104   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9105     return 1;
9106
9107   /* Make sure the remote is pointing at the right process, if
9108      necessary.  */
9109   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9110     set_general_process ();
9111
9112   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9113   p = strchr (rs->buf, '\0');
9114   addr = remote_address_masked (addr);
9115   p += hexnumstr (p, (ULONGEST) addr);
9116   xsnprintf (p, endbuf - p, ",%x", len);
9117
9118   putpkt (rs->buf);
9119   getpkt (&rs->buf, &rs->buf_size, 0);
9120
9121   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9122     {
9123     case PACKET_ERROR:
9124       return -1;
9125     case PACKET_UNKNOWN:
9126       return 1;
9127     case PACKET_OK:
9128       return 0;
9129     }
9130   internal_error (__FILE__, __LINE__,
9131                   _("remote_insert_watchpoint: reached end of function"));
9132 }
9133
9134 static int
9135 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9136                                      CORE_ADDR start, int length)
9137 {
9138   CORE_ADDR diff = remote_address_masked (addr - start);
9139
9140   return diff < length;
9141 }
9142
9143
9144 static int
9145 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9146                           enum target_hw_bp_type type, struct expression *cond)
9147 {
9148   struct remote_state *rs = get_remote_state ();
9149   char *endbuf = rs->buf + get_remote_packet_size ();
9150   char *p;
9151   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9152
9153   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9154     return -1;
9155
9156   /* Make sure the remote is pointing at the right process, if
9157      necessary.  */
9158   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9159     set_general_process ();
9160
9161   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9162   p = strchr (rs->buf, '\0');
9163   addr = remote_address_masked (addr);
9164   p += hexnumstr (p, (ULONGEST) addr);
9165   xsnprintf (p, endbuf - p, ",%x", len);
9166   putpkt (rs->buf);
9167   getpkt (&rs->buf, &rs->buf_size, 0);
9168
9169   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9170     {
9171     case PACKET_ERROR:
9172     case PACKET_UNKNOWN:
9173       return -1;
9174     case PACKET_OK:
9175       return 0;
9176     }
9177   internal_error (__FILE__, __LINE__,
9178                   _("remote_remove_watchpoint: reached end of function"));
9179 }
9180
9181
9182 int remote_hw_watchpoint_limit = -1;
9183 int remote_hw_watchpoint_length_limit = -1;
9184 int remote_hw_breakpoint_limit = -1;
9185
9186 static int
9187 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9188                                     CORE_ADDR addr, int len)
9189 {
9190   if (remote_hw_watchpoint_length_limit == 0)
9191     return 0;
9192   else if (remote_hw_watchpoint_length_limit < 0)
9193     return 1;
9194   else if (len <= remote_hw_watchpoint_length_limit)
9195     return 1;
9196   else
9197     return 0;
9198 }
9199
9200 static int
9201 remote_check_watch_resources (struct target_ops *self,
9202                               enum bptype type, int cnt, int ot)
9203 {
9204   if (type == bp_hardware_breakpoint)
9205     {
9206       if (remote_hw_breakpoint_limit == 0)
9207         return 0;
9208       else if (remote_hw_breakpoint_limit < 0)
9209         return 1;
9210       else if (cnt <= remote_hw_breakpoint_limit)
9211         return 1;
9212     }
9213   else
9214     {
9215       if (remote_hw_watchpoint_limit == 0)
9216         return 0;
9217       else if (remote_hw_watchpoint_limit < 0)
9218         return 1;
9219       else if (ot)
9220         return -1;
9221       else if (cnt <= remote_hw_watchpoint_limit)
9222         return 1;
9223     }
9224   return -1;
9225 }
9226
9227 /* The to_stopped_by_sw_breakpoint method of target remote.  */
9228
9229 static int
9230 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9231 {
9232   struct remote_state *rs = get_remote_state ();
9233
9234   return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
9235 }
9236
9237 /* The to_supports_stopped_by_sw_breakpoint method of target
9238    remote.  */
9239
9240 static int
9241 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9242 {
9243   struct remote_state *rs = get_remote_state ();
9244
9245   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9246 }
9247
9248 /* The to_stopped_by_hw_breakpoint method of target remote.  */
9249
9250 static int
9251 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9252 {
9253   struct remote_state *rs = get_remote_state ();
9254
9255   return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9256 }
9257
9258 /* The to_supports_stopped_by_hw_breakpoint method of target
9259    remote.  */
9260
9261 static int
9262 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9263 {
9264   struct remote_state *rs = get_remote_state ();
9265
9266   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9267 }
9268
9269 static int
9270 remote_stopped_by_watchpoint (struct target_ops *ops)
9271 {
9272   struct remote_state *rs = get_remote_state ();
9273
9274   return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
9275 }
9276
9277 static int
9278 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9279 {
9280   struct remote_state *rs = get_remote_state ();
9281   int rc = 0;
9282
9283   if (remote_stopped_by_watchpoint (target))
9284     {
9285       *addr_p = rs->remote_watch_data_address;
9286       rc = 1;
9287     }
9288
9289   return rc;
9290 }
9291
9292
9293 static int
9294 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9295                              struct bp_target_info *bp_tgt)
9296 {
9297   CORE_ADDR addr = bp_tgt->reqstd_address;
9298   struct remote_state *rs;
9299   char *p, *endbuf;
9300   char *message;
9301   int bpsize;
9302
9303   /* The length field should be set to the size of a breakpoint
9304      instruction, even though we aren't inserting one ourselves.  */
9305
9306   gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9307
9308   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9309     return -1;
9310
9311   /* Make sure the remote is pointing at the right process, if
9312      necessary.  */
9313   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9314     set_general_process ();
9315
9316   rs = get_remote_state ();
9317   p = rs->buf;
9318   endbuf = rs->buf + get_remote_packet_size ();
9319
9320   *(p++) = 'Z';
9321   *(p++) = '1';
9322   *(p++) = ',';
9323
9324   addr = remote_address_masked (addr);
9325   p += hexnumstr (p, (ULONGEST) addr);
9326   xsnprintf (p, endbuf - p, ",%x", bpsize);
9327
9328   if (remote_supports_cond_breakpoints (self))
9329     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9330
9331   if (remote_can_run_breakpoint_commands (self))
9332     remote_add_target_side_commands (gdbarch, bp_tgt, p);
9333
9334   putpkt (rs->buf);
9335   getpkt (&rs->buf, &rs->buf_size, 0);
9336
9337   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9338     {
9339     case PACKET_ERROR:
9340       if (rs->buf[1] == '.')
9341         {
9342           message = strchr (rs->buf + 2, '.');
9343           if (message)
9344             error (_("Remote failure reply: %s"), message + 1);
9345         }
9346       return -1;
9347     case PACKET_UNKNOWN:
9348       return -1;
9349     case PACKET_OK:
9350       bp_tgt->placed_address = addr;
9351       bp_tgt->placed_size = bpsize;
9352       return 0;
9353     }
9354   internal_error (__FILE__, __LINE__,
9355                   _("remote_insert_hw_breakpoint: reached end of function"));
9356 }
9357
9358
9359 static int
9360 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9361                              struct bp_target_info *bp_tgt)
9362 {
9363   CORE_ADDR addr;
9364   struct remote_state *rs = get_remote_state ();
9365   char *p = rs->buf;
9366   char *endbuf = rs->buf + get_remote_packet_size ();
9367
9368   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9369     return -1;
9370
9371   /* Make sure the remote is pointing at the right process, if
9372      necessary.  */
9373   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9374     set_general_process ();
9375
9376   *(p++) = 'z';
9377   *(p++) = '1';
9378   *(p++) = ',';
9379
9380   addr = remote_address_masked (bp_tgt->placed_address);
9381   p += hexnumstr (p, (ULONGEST) addr);
9382   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);
9383
9384   putpkt (rs->buf);
9385   getpkt (&rs->buf, &rs->buf_size, 0);
9386
9387   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9388     {
9389     case PACKET_ERROR:
9390     case PACKET_UNKNOWN:
9391       return -1;
9392     case PACKET_OK:
9393       return 0;
9394     }
9395   internal_error (__FILE__, __LINE__,
9396                   _("remote_remove_hw_breakpoint: reached end of function"));
9397 }
9398
9399 /* Verify memory using the "qCRC:" request.  */
9400
9401 static int
9402 remote_verify_memory (struct target_ops *ops,
9403                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9404 {
9405   struct remote_state *rs = get_remote_state ();
9406   unsigned long host_crc, target_crc;
9407   char *tmp;
9408
9409   /* It doesn't make sense to use qCRC if the remote target is
9410      connected but not running.  */
9411   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9412     {
9413       enum packet_result result;
9414
9415       /* Make sure the remote is pointing at the right process.  */
9416       set_general_process ();
9417
9418       /* FIXME: assumes lma can fit into long.  */
9419       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9420                  (long) lma, (long) size);
9421       putpkt (rs->buf);
9422
9423       /* Be clever; compute the host_crc before waiting for target
9424          reply.  */
9425       host_crc = xcrc32 (data, size, 0xffffffff);
9426
9427       getpkt (&rs->buf, &rs->buf_size, 0);
9428
9429       result = packet_ok (rs->buf,
9430                           &remote_protocol_packets[PACKET_qCRC]);
9431       if (result == PACKET_ERROR)
9432         return -1;
9433       else if (result == PACKET_OK)
9434         {
9435           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9436             target_crc = target_crc * 16 + fromhex (*tmp);
9437
9438           return (host_crc == target_crc);
9439         }
9440     }
9441
9442   return simple_verify_memory (ops, data, lma, size);
9443 }
9444
9445 /* compare-sections command
9446
9447    With no arguments, compares each loadable section in the exec bfd
9448    with the same memory range on the target, and reports mismatches.
9449    Useful for verifying the image on the target against the exec file.  */
9450
9451 static void
9452 compare_sections_command (char *args, int from_tty)
9453 {
9454   asection *s;
9455   struct cleanup *old_chain;
9456   gdb_byte *sectdata;
9457   const char *sectname;
9458   bfd_size_type size;
9459   bfd_vma lma;
9460   int matched = 0;
9461   int mismatched = 0;
9462   int res;
9463   int read_only = 0;
9464
9465   if (!exec_bfd)
9466     error (_("command cannot be used without an exec file"));
9467
9468   /* Make sure the remote is pointing at the right process.  */
9469   set_general_process ();
9470
9471   if (args != NULL && strcmp (args, "-r") == 0)
9472     {
9473       read_only = 1;
9474       args = NULL;
9475     }
9476
9477   for (s = exec_bfd->sections; s; s = s->next)
9478     {
9479       if (!(s->flags & SEC_LOAD))
9480         continue;               /* Skip non-loadable section.  */
9481
9482       if (read_only && (s->flags & SEC_READONLY) == 0)
9483         continue;               /* Skip writeable sections */
9484
9485       size = bfd_get_section_size (s);
9486       if (size == 0)
9487         continue;               /* Skip zero-length section.  */
9488
9489       sectname = bfd_get_section_name (exec_bfd, s);
9490       if (args && strcmp (args, sectname) != 0)
9491         continue;               /* Not the section selected by user.  */
9492
9493       matched = 1;              /* Do this section.  */
9494       lma = s->lma;
9495
9496       sectdata = (gdb_byte *) xmalloc (size);
9497       old_chain = make_cleanup (xfree, sectdata);
9498       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9499
9500       res = target_verify_memory (sectdata, lma, size);
9501
9502       if (res == -1)
9503         error (_("target memory fault, section %s, range %s -- %s"), sectname,
9504                paddress (target_gdbarch (), lma),
9505                paddress (target_gdbarch (), lma + size));
9506
9507       printf_filtered ("Section %s, range %s -- %s: ", sectname,
9508                        paddress (target_gdbarch (), lma),
9509                        paddress (target_gdbarch (), lma + size));
9510       if (res)
9511         printf_filtered ("matched.\n");
9512       else
9513         {
9514           printf_filtered ("MIS-MATCHED!\n");
9515           mismatched++;
9516         }
9517
9518       do_cleanups (old_chain);
9519     }
9520   if (mismatched > 0)
9521     warning (_("One or more sections of the target image does not match\n\
9522 the loaded file\n"));
9523   if (args && !matched)
9524     printf_filtered (_("No loaded section named '%s'.\n"), args);
9525 }
9526
9527 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9528    into remote target.  The number of bytes written to the remote
9529    target is returned, or -1 for error.  */
9530
9531 static enum target_xfer_status
9532 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9533                     const char *annex, const gdb_byte *writebuf, 
9534                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9535                     struct packet_config *packet)
9536 {
9537   int i, buf_len;
9538   ULONGEST n;
9539   struct remote_state *rs = get_remote_state ();
9540   int max_size = get_memory_write_packet_size (); 
9541
9542   if (packet->support == PACKET_DISABLE)
9543     return TARGET_XFER_E_IO;
9544
9545   /* Insert header.  */
9546   i = snprintf (rs->buf, max_size, 
9547                 "qXfer:%s:write:%s:%s:",
9548                 object_name, annex ? annex : "",
9549                 phex_nz (offset, sizeof offset));
9550   max_size -= (i + 1);
9551
9552   /* Escape as much data as fits into rs->buf.  */
9553   buf_len = remote_escape_output 
9554     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9555
9556   if (putpkt_binary (rs->buf, i + buf_len) < 0
9557       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9558       || packet_ok (rs->buf, packet) != PACKET_OK)
9559     return TARGET_XFER_E_IO;
9560
9561   unpack_varlen_hex (rs->buf, &n);
9562
9563   *xfered_len = n;
9564   return TARGET_XFER_OK;
9565 }
9566
9567 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9568    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9569    number of bytes read is returned, or 0 for EOF, or -1 for error.
9570    The number of bytes read may be less than LEN without indicating an
9571    EOF.  PACKET is checked and updated to indicate whether the remote
9572    target supports this object.  */
9573
9574 static enum target_xfer_status
9575 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9576                    const char *annex,
9577                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9578                    ULONGEST *xfered_len,
9579                    struct packet_config *packet)
9580 {
9581   struct remote_state *rs = get_remote_state ();
9582   LONGEST i, n, packet_len;
9583
9584   if (packet->support == PACKET_DISABLE)
9585     return TARGET_XFER_E_IO;
9586
9587   /* Check whether we've cached an end-of-object packet that matches
9588      this request.  */
9589   if (rs->finished_object)
9590     {
9591       if (strcmp (object_name, rs->finished_object) == 0
9592           && strcmp (annex ? annex : "", rs->finished_annex) == 0
9593           && offset == rs->finished_offset)
9594         return TARGET_XFER_EOF;
9595
9596
9597       /* Otherwise, we're now reading something different.  Discard
9598          the cache.  */
9599       xfree (rs->finished_object);
9600       xfree (rs->finished_annex);
9601       rs->finished_object = NULL;
9602       rs->finished_annex = NULL;
9603     }
9604
9605   /* Request only enough to fit in a single packet.  The actual data
9606      may not, since we don't know how much of it will need to be escaped;
9607      the target is free to respond with slightly less data.  We subtract
9608      five to account for the response type and the protocol frame.  */
9609   n = min (get_remote_packet_size () - 5, len);
9610   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9611             object_name, annex ? annex : "",
9612             phex_nz (offset, sizeof offset),
9613             phex_nz (n, sizeof n));
9614   i = putpkt (rs->buf);
9615   if (i < 0)
9616     return TARGET_XFER_E_IO;
9617
9618   rs->buf[0] = '\0';
9619   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9620   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9621     return TARGET_XFER_E_IO;
9622
9623   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9624     error (_("Unknown remote qXfer reply: %s"), rs->buf);
9625
9626   /* 'm' means there is (or at least might be) more data after this
9627      batch.  That does not make sense unless there's at least one byte
9628      of data in this reply.  */
9629   if (rs->buf[0] == 'm' && packet_len == 1)
9630     error (_("Remote qXfer reply contained no data."));
9631
9632   /* Got some data.  */
9633   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9634                              packet_len - 1, readbuf, n);
9635
9636   /* 'l' is an EOF marker, possibly including a final block of data,
9637      or possibly empty.  If we have the final block of a non-empty
9638      object, record this fact to bypass a subsequent partial read.  */
9639   if (rs->buf[0] == 'l' && offset + i > 0)
9640     {
9641       rs->finished_object = xstrdup (object_name);
9642       rs->finished_annex = xstrdup (annex ? annex : "");
9643       rs->finished_offset = offset + i;
9644     }
9645
9646   if (i == 0)
9647     return TARGET_XFER_EOF;
9648   else
9649     {
9650       *xfered_len = i;
9651       return TARGET_XFER_OK;
9652     }
9653 }
9654
9655 static enum target_xfer_status
9656 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9657                      const char *annex, gdb_byte *readbuf,
9658                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9659                      ULONGEST *xfered_len)
9660 {
9661   struct remote_state *rs;
9662   int i;
9663   char *p2;
9664   char query_type;
9665   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9666
9667   set_remote_traceframe ();
9668   set_general_thread (inferior_ptid);
9669
9670   rs = get_remote_state ();
9671
9672   /* Handle memory using the standard memory routines.  */
9673   if (object == TARGET_OBJECT_MEMORY)
9674     {
9675       /* If the remote target is connected but not running, we should
9676          pass this request down to a lower stratum (e.g. the executable
9677          file).  */
9678       if (!target_has_execution)
9679         return TARGET_XFER_EOF;
9680
9681       if (writebuf != NULL)
9682         return remote_write_bytes (offset, writebuf, len, unit_size,
9683                                    xfered_len);
9684       else
9685         return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9686                                   xfered_len);
9687     }
9688
9689   /* Handle SPU memory using qxfer packets.  */
9690   if (object == TARGET_OBJECT_SPU)
9691     {
9692       if (readbuf)
9693         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9694                                   xfered_len, &remote_protocol_packets
9695                                   [PACKET_qXfer_spu_read]);
9696       else
9697         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9698                                    xfered_len, &remote_protocol_packets
9699                                    [PACKET_qXfer_spu_write]);
9700     }
9701
9702   /* Handle extra signal info using qxfer packets.  */
9703   if (object == TARGET_OBJECT_SIGNAL_INFO)
9704     {
9705       if (readbuf)
9706         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9707                                   xfered_len, &remote_protocol_packets
9708                                   [PACKET_qXfer_siginfo_read]);
9709       else
9710         return remote_write_qxfer (ops, "siginfo", annex,
9711                                    writebuf, offset, len, xfered_len,
9712                                    &remote_protocol_packets
9713                                    [PACKET_qXfer_siginfo_write]);
9714     }
9715
9716   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9717     {
9718       if (readbuf)
9719         return remote_read_qxfer (ops, "statictrace", annex,
9720                                   readbuf, offset, len, xfered_len,
9721                                   &remote_protocol_packets
9722                                   [PACKET_qXfer_statictrace_read]);
9723       else
9724         return TARGET_XFER_E_IO;
9725     }
9726
9727   /* Only handle flash writes.  */
9728   if (writebuf != NULL)
9729     {
9730       LONGEST xfered;
9731
9732       switch (object)
9733         {
9734         case TARGET_OBJECT_FLASH:
9735           return remote_flash_write (ops, offset, len, xfered_len,
9736                                      writebuf);
9737
9738         default:
9739           return TARGET_XFER_E_IO;
9740         }
9741     }
9742
9743   /* Map pre-existing objects onto letters.  DO NOT do this for new
9744      objects!!!  Instead specify new query packets.  */
9745   switch (object)
9746     {
9747     case TARGET_OBJECT_AVR:
9748       query_type = 'R';
9749       break;
9750
9751     case TARGET_OBJECT_AUXV:
9752       gdb_assert (annex == NULL);
9753       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9754                                 xfered_len,
9755                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
9756
9757     case TARGET_OBJECT_AVAILABLE_FEATURES:
9758       return remote_read_qxfer
9759         (ops, "features", annex, readbuf, offset, len, xfered_len,
9760          &remote_protocol_packets[PACKET_qXfer_features]);
9761
9762     case TARGET_OBJECT_LIBRARIES:
9763       return remote_read_qxfer
9764         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9765          &remote_protocol_packets[PACKET_qXfer_libraries]);
9766
9767     case TARGET_OBJECT_LIBRARIES_SVR4:
9768       return remote_read_qxfer
9769         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9770          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9771
9772     case TARGET_OBJECT_MEMORY_MAP:
9773       gdb_assert (annex == NULL);
9774       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9775                                  xfered_len,
9776                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9777
9778     case TARGET_OBJECT_OSDATA:
9779       /* Should only get here if we're connected.  */
9780       gdb_assert (rs->remote_desc);
9781       return remote_read_qxfer
9782         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9783         &remote_protocol_packets[PACKET_qXfer_osdata]);
9784
9785     case TARGET_OBJECT_THREADS:
9786       gdb_assert (annex == NULL);
9787       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9788                                 xfered_len,
9789                                 &remote_protocol_packets[PACKET_qXfer_threads]);
9790
9791     case TARGET_OBJECT_TRACEFRAME_INFO:
9792       gdb_assert (annex == NULL);
9793       return remote_read_qxfer
9794         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9795          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9796
9797     case TARGET_OBJECT_FDPIC:
9798       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9799                                 xfered_len,
9800                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9801
9802     case TARGET_OBJECT_OPENVMS_UIB:
9803       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9804                                 xfered_len,
9805                                 &remote_protocol_packets[PACKET_qXfer_uib]);
9806
9807     case TARGET_OBJECT_BTRACE:
9808       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9809                                 xfered_len,
9810         &remote_protocol_packets[PACKET_qXfer_btrace]);
9811
9812     case TARGET_OBJECT_BTRACE_CONF:
9813       return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9814                                 len, xfered_len,
9815         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9816
9817     case TARGET_OBJECT_EXEC_FILE:
9818       return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9819                                 len, xfered_len,
9820         &remote_protocol_packets[PACKET_qXfer_exec_file]);
9821
9822     default:
9823       return TARGET_XFER_E_IO;
9824     }
9825
9826   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
9827      large enough let the caller deal with it.  */
9828   if (len < get_remote_packet_size ())
9829     return TARGET_XFER_E_IO;
9830   len = get_remote_packet_size ();
9831
9832   /* Except for querying the minimum buffer size, target must be open.  */
9833   if (!rs->remote_desc)
9834     error (_("remote query is only available after target open"));
9835
9836   gdb_assert (annex != NULL);
9837   gdb_assert (readbuf != NULL);
9838
9839   p2 = rs->buf;
9840   *p2++ = 'q';
9841   *p2++ = query_type;
9842
9843   /* We used one buffer char for the remote protocol q command and
9844      another for the query type.  As the remote protocol encapsulation
9845      uses 4 chars plus one extra in case we are debugging
9846      (remote_debug), we have PBUFZIZ - 7 left to pack the query
9847      string.  */
9848   i = 0;
9849   while (annex[i] && (i < (get_remote_packet_size () - 8)))
9850     {
9851       /* Bad caller may have sent forbidden characters.  */
9852       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9853       *p2++ = annex[i];
9854       i++;
9855     }
9856   *p2 = '\0';
9857   gdb_assert (annex[i] == '\0');
9858
9859   i = putpkt (rs->buf);
9860   if (i < 0)
9861     return TARGET_XFER_E_IO;
9862
9863   getpkt (&rs->buf, &rs->buf_size, 0);
9864   strcpy ((char *) readbuf, rs->buf);
9865
9866   *xfered_len = strlen ((char *) readbuf);
9867   return TARGET_XFER_OK;
9868 }
9869
9870 static int
9871 remote_search_memory (struct target_ops* ops,
9872                       CORE_ADDR start_addr, ULONGEST search_space_len,
9873                       const gdb_byte *pattern, ULONGEST pattern_len,
9874                       CORE_ADDR *found_addrp)
9875 {
9876   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9877   struct remote_state *rs = get_remote_state ();
9878   int max_size = get_memory_write_packet_size ();
9879   struct packet_config *packet =
9880     &remote_protocol_packets[PACKET_qSearch_memory];
9881   /* Number of packet bytes used to encode the pattern;
9882      this could be more than PATTERN_LEN due to escape characters.  */
9883   int escaped_pattern_len;
9884   /* Amount of pattern that was encodable in the packet.  */
9885   int used_pattern_len;
9886   int i;
9887   int found;
9888   ULONGEST found_addr;
9889
9890   /* Don't go to the target if we don't have to.
9891      This is done before checking packet->support to avoid the possibility that
9892      a success for this edge case means the facility works in general.  */
9893   if (pattern_len > search_space_len)
9894     return 0;
9895   if (pattern_len == 0)
9896     {
9897       *found_addrp = start_addr;
9898       return 1;
9899     }
9900
9901   /* If we already know the packet isn't supported, fall back to the simple
9902      way of searching memory.  */
9903
9904   if (packet_config_support (packet) == PACKET_DISABLE)
9905     {
9906       /* Target doesn't provided special support, fall back and use the
9907          standard support (copy memory and do the search here).  */
9908       return simple_search_memory (ops, start_addr, search_space_len,
9909                                    pattern, pattern_len, found_addrp);
9910     }
9911
9912   /* Make sure the remote is pointing at the right process.  */
9913   set_general_process ();
9914
9915   /* Insert header.  */
9916   i = snprintf (rs->buf, max_size, 
9917                 "qSearch:memory:%s;%s;",
9918                 phex_nz (start_addr, addr_size),
9919                 phex_nz (search_space_len, sizeof (search_space_len)));
9920   max_size -= (i + 1);
9921
9922   /* Escape as much data as fits into rs->buf.  */
9923   escaped_pattern_len =
9924     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
9925                           &used_pattern_len, max_size);
9926
9927   /* Bail if the pattern is too large.  */
9928   if (used_pattern_len != pattern_len)
9929     error (_("Pattern is too large to transmit to remote target."));
9930
9931   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9932       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9933       || packet_ok (rs->buf, packet) != PACKET_OK)
9934     {
9935       /* The request may not have worked because the command is not
9936          supported.  If so, fall back to the simple way.  */
9937       if (packet->support == PACKET_DISABLE)
9938         {
9939           return simple_search_memory (ops, start_addr, search_space_len,
9940                                        pattern, pattern_len, found_addrp);
9941         }
9942       return -1;
9943     }
9944
9945   if (rs->buf[0] == '0')
9946     found = 0;
9947   else if (rs->buf[0] == '1')
9948     {
9949       found = 1;
9950       if (rs->buf[1] != ',')
9951         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9952       unpack_varlen_hex (rs->buf + 2, &found_addr);
9953       *found_addrp = found_addr;
9954     }
9955   else
9956     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9957
9958   return found;
9959 }
9960
9961 static void
9962 remote_rcmd (struct target_ops *self, const char *command,
9963              struct ui_file *outbuf)
9964 {
9965   struct remote_state *rs = get_remote_state ();
9966   char *p = rs->buf;
9967
9968   if (!rs->remote_desc)
9969     error (_("remote rcmd is only available after target open"));
9970
9971   /* Send a NULL command across as an empty command.  */
9972   if (command == NULL)
9973     command = "";
9974
9975   /* The query prefix.  */
9976   strcpy (rs->buf, "qRcmd,");
9977   p = strchr (rs->buf, '\0');
9978
9979   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9980       > get_remote_packet_size ())
9981     error (_("\"monitor\" command ``%s'' is too long."), command);
9982
9983   /* Encode the actual command.  */
9984   bin2hex ((const gdb_byte *) command, p, strlen (command));
9985
9986   if (putpkt (rs->buf) < 0)
9987     error (_("Communication problem with target."));
9988
9989   /* get/display the response */
9990   while (1)
9991     {
9992       char *buf;
9993
9994       /* XXX - see also remote_get_noisy_reply().  */
9995       QUIT;                     /* Allow user to bail out with ^C.  */
9996       rs->buf[0] = '\0';
9997       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9998         { 
9999           /* Timeout.  Continue to (try to) read responses.
10000              This is better than stopping with an error, assuming the stub
10001              is still executing the (long) monitor command.
10002              If needed, the user can interrupt gdb using C-c, obtaining
10003              an effect similar to stop on timeout.  */
10004           continue;
10005         }
10006       buf = rs->buf;
10007       if (buf[0] == '\0')
10008         error (_("Target does not support this command."));
10009       if (buf[0] == 'O' && buf[1] != 'K')
10010         {
10011           remote_console_output (buf + 1); /* 'O' message from stub.  */
10012           continue;
10013         }
10014       if (strcmp (buf, "OK") == 0)
10015         break;
10016       if (strlen (buf) == 3 && buf[0] == 'E'
10017           && isdigit (buf[1]) && isdigit (buf[2]))
10018         {
10019           error (_("Protocol error with Rcmd"));
10020         }
10021       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10022         {
10023           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10024
10025           fputc_unfiltered (c, outbuf);
10026         }
10027       break;
10028     }
10029 }
10030
10031 static VEC(mem_region_s) *
10032 remote_memory_map (struct target_ops *ops)
10033 {
10034   VEC(mem_region_s) *result = NULL;
10035   char *text = target_read_stralloc (&current_target,
10036                                      TARGET_OBJECT_MEMORY_MAP, NULL);
10037
10038   if (text)
10039     {
10040       struct cleanup *back_to = make_cleanup (xfree, text);
10041
10042       result = parse_memory_map (text);
10043       do_cleanups (back_to);
10044     }
10045
10046   return result;
10047 }
10048
10049 static void
10050 packet_command (char *args, int from_tty)
10051 {
10052   struct remote_state *rs = get_remote_state ();
10053
10054   if (!rs->remote_desc)
10055     error (_("command can only be used with remote target"));
10056
10057   if (!args)
10058     error (_("remote-packet command requires packet text as argument"));
10059
10060   puts_filtered ("sending: ");
10061   print_packet (args);
10062   puts_filtered ("\n");
10063   putpkt (args);
10064
10065   getpkt (&rs->buf, &rs->buf_size, 0);
10066   puts_filtered ("received: ");
10067   print_packet (rs->buf);
10068   puts_filtered ("\n");
10069 }
10070
10071 #if 0
10072 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10073
10074 static void display_thread_info (struct gdb_ext_thread_info *info);
10075
10076 static void threadset_test_cmd (char *cmd, int tty);
10077
10078 static void threadalive_test (char *cmd, int tty);
10079
10080 static void threadlist_test_cmd (char *cmd, int tty);
10081
10082 int get_and_display_threadinfo (threadref *ref);
10083
10084 static void threadinfo_test_cmd (char *cmd, int tty);
10085
10086 static int thread_display_step (threadref *ref, void *context);
10087
10088 static void threadlist_update_test_cmd (char *cmd, int tty);
10089
10090 static void init_remote_threadtests (void);
10091
10092 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
10093
10094 static void
10095 threadset_test_cmd (char *cmd, int tty)
10096 {
10097   int sample_thread = SAMPLE_THREAD;
10098
10099   printf_filtered (_("Remote threadset test\n"));
10100   set_general_thread (sample_thread);
10101 }
10102
10103
10104 static void
10105 threadalive_test (char *cmd, int tty)
10106 {
10107   int sample_thread = SAMPLE_THREAD;
10108   int pid = ptid_get_pid (inferior_ptid);
10109   ptid_t ptid = ptid_build (pid, sample_thread, 0);
10110
10111   if (remote_thread_alive (ptid))
10112     printf_filtered ("PASS: Thread alive test\n");
10113   else
10114     printf_filtered ("FAIL: Thread alive test\n");
10115 }
10116
10117 void output_threadid (char *title, threadref *ref);
10118
10119 void
10120 output_threadid (char *title, threadref *ref)
10121 {
10122   char hexid[20];
10123
10124   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
10125   hexid[16] = 0;
10126   printf_filtered ("%s  %s\n", title, (&hexid[0]));
10127 }
10128
10129 static void
10130 threadlist_test_cmd (char *cmd, int tty)
10131 {
10132   int startflag = 1;
10133   threadref nextthread;
10134   int done, result_count;
10135   threadref threadlist[3];
10136
10137   printf_filtered ("Remote Threadlist test\n");
10138   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10139                               &result_count, &threadlist[0]))
10140     printf_filtered ("FAIL: threadlist test\n");
10141   else
10142     {
10143       threadref *scan = threadlist;
10144       threadref *limit = scan + result_count;
10145
10146       while (scan < limit)
10147         output_threadid (" thread ", scan++);
10148     }
10149 }
10150
10151 void
10152 display_thread_info (struct gdb_ext_thread_info *info)
10153 {
10154   output_threadid ("Threadid: ", &info->threadid);
10155   printf_filtered ("Name: %s\n ", info->shortname);
10156   printf_filtered ("State: %s\n", info->display);
10157   printf_filtered ("other: %s\n\n", info->more_display);
10158 }
10159
10160 int
10161 get_and_display_threadinfo (threadref *ref)
10162 {
10163   int result;
10164   int set;
10165   struct gdb_ext_thread_info threadinfo;
10166
10167   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10168     | TAG_MOREDISPLAY | TAG_DISPLAY;
10169   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10170     display_thread_info (&threadinfo);
10171   return result;
10172 }
10173
10174 static void
10175 threadinfo_test_cmd (char *cmd, int tty)
10176 {
10177   int athread = SAMPLE_THREAD;
10178   threadref thread;
10179   int set;
10180
10181   int_to_threadref (&thread, athread);
10182   printf_filtered ("Remote Threadinfo test\n");
10183   if (!get_and_display_threadinfo (&thread))
10184     printf_filtered ("FAIL cannot get thread info\n");
10185 }
10186
10187 static int
10188 thread_display_step (threadref *ref, void *context)
10189 {
10190   /* output_threadid(" threadstep ",ref); *//* simple test */
10191   return get_and_display_threadinfo (ref);
10192 }
10193
10194 static void
10195 threadlist_update_test_cmd (char *cmd, int tty)
10196 {
10197   printf_filtered ("Remote Threadlist update test\n");
10198   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10199 }
10200
10201 static void
10202 init_remote_threadtests (void)
10203 {
10204   add_com ("tlist", class_obscure, threadlist_test_cmd,
10205            _("Fetch and print the remote list of "
10206              "thread identifiers, one pkt only"));
10207   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10208            _("Fetch and display info about one thread"));
10209   add_com ("tset", class_obscure, threadset_test_cmd,
10210            _("Test setting to a different thread"));
10211   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10212            _("Iterate through updating all remote thread info"));
10213   add_com ("talive", class_obscure, threadalive_test,
10214            _(" Remote thread alive test "));
10215 }
10216
10217 #endif /* 0 */
10218
10219 /* Convert a thread ID to a string.  Returns the string in a static
10220    buffer.  */
10221
10222 static char *
10223 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10224 {
10225   static char buf[64];
10226   struct remote_state *rs = get_remote_state ();
10227
10228   if (ptid_equal (ptid, null_ptid))
10229     return normal_pid_to_str (ptid);
10230   else if (ptid_is_pid (ptid))
10231     {
10232       /* Printing an inferior target id.  */
10233
10234       /* When multi-process extensions are off, there's no way in the
10235          remote protocol to know the remote process id, if there's any
10236          at all.  There's one exception --- when we're connected with
10237          target extended-remote, and we manually attached to a process
10238          with "attach PID".  We don't record anywhere a flag that
10239          allows us to distinguish that case from the case of
10240          connecting with extended-remote and the stub already being
10241          attached to a process, and reporting yes to qAttached, hence
10242          no smart special casing here.  */
10243       if (!remote_multi_process_p (rs))
10244         {
10245           xsnprintf (buf, sizeof buf, "Remote target");
10246           return buf;
10247         }
10248
10249       return normal_pid_to_str (ptid);
10250     }
10251   else
10252     {
10253       if (ptid_equal (magic_null_ptid, ptid))
10254         xsnprintf (buf, sizeof buf, "Thread <main>");
10255       else if (rs->extended && remote_multi_process_p (rs))
10256         if (ptid_get_lwp (ptid) == 0)
10257           return normal_pid_to_str (ptid);
10258         else
10259           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10260                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
10261       else
10262         xsnprintf (buf, sizeof buf, "Thread %ld",
10263                    ptid_get_lwp (ptid));
10264       return buf;
10265     }
10266 }
10267
10268 /* Get the address of the thread local variable in OBJFILE which is
10269    stored at OFFSET within the thread local storage for thread PTID.  */
10270
10271 static CORE_ADDR
10272 remote_get_thread_local_address (struct target_ops *ops,
10273                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10274 {
10275   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10276     {
10277       struct remote_state *rs = get_remote_state ();
10278       char *p = rs->buf;
10279       char *endp = rs->buf + get_remote_packet_size ();
10280       enum packet_result result;
10281
10282       strcpy (p, "qGetTLSAddr:");
10283       p += strlen (p);
10284       p = write_ptid (p, endp, ptid);
10285       *p++ = ',';
10286       p += hexnumstr (p, offset);
10287       *p++ = ',';
10288       p += hexnumstr (p, lm);
10289       *p++ = '\0';
10290
10291       putpkt (rs->buf);
10292       getpkt (&rs->buf, &rs->buf_size, 0);
10293       result = packet_ok (rs->buf,
10294                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
10295       if (result == PACKET_OK)
10296         {
10297           ULONGEST result;
10298
10299           unpack_varlen_hex (rs->buf, &result);
10300           return result;
10301         }
10302       else if (result == PACKET_UNKNOWN)
10303         throw_error (TLS_GENERIC_ERROR,
10304                      _("Remote target doesn't support qGetTLSAddr packet"));
10305       else
10306         throw_error (TLS_GENERIC_ERROR,
10307                      _("Remote target failed to process qGetTLSAddr request"));
10308     }
10309   else
10310     throw_error (TLS_GENERIC_ERROR,
10311                  _("TLS not supported or disabled on this target"));
10312   /* Not reached.  */
10313   return 0;
10314 }
10315
10316 /* Provide thread local base, i.e. Thread Information Block address.
10317    Returns 1 if ptid is found and thread_local_base is non zero.  */
10318
10319 static int
10320 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10321 {
10322   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10323     {
10324       struct remote_state *rs = get_remote_state ();
10325       char *p = rs->buf;
10326       char *endp = rs->buf + get_remote_packet_size ();
10327       enum packet_result result;
10328
10329       strcpy (p, "qGetTIBAddr:");
10330       p += strlen (p);
10331       p = write_ptid (p, endp, ptid);
10332       *p++ = '\0';
10333
10334       putpkt (rs->buf);
10335       getpkt (&rs->buf, &rs->buf_size, 0);
10336       result = packet_ok (rs->buf,
10337                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
10338       if (result == PACKET_OK)
10339         {
10340           ULONGEST result;
10341
10342           unpack_varlen_hex (rs->buf, &result);
10343           if (addr)
10344             *addr = (CORE_ADDR) result;
10345           return 1;
10346         }
10347       else if (result == PACKET_UNKNOWN)
10348         error (_("Remote target doesn't support qGetTIBAddr packet"));
10349       else
10350         error (_("Remote target failed to process qGetTIBAddr request"));
10351     }
10352   else
10353     error (_("qGetTIBAddr not supported or disabled on this target"));
10354   /* Not reached.  */
10355   return 0;
10356 }
10357
10358 /* Support for inferring a target description based on the current
10359    architecture and the size of a 'g' packet.  While the 'g' packet
10360    can have any size (since optional registers can be left off the
10361    end), some sizes are easily recognizable given knowledge of the
10362    approximate architecture.  */
10363
10364 struct remote_g_packet_guess
10365 {
10366   int bytes;
10367   const struct target_desc *tdesc;
10368 };
10369 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10370 DEF_VEC_O(remote_g_packet_guess_s);
10371
10372 struct remote_g_packet_data
10373 {
10374   VEC(remote_g_packet_guess_s) *guesses;
10375 };
10376
10377 static struct gdbarch_data *remote_g_packet_data_handle;
10378
10379 static void *
10380 remote_g_packet_data_init (struct obstack *obstack)
10381 {
10382   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10383 }
10384
10385 void
10386 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10387                                 const struct target_desc *tdesc)
10388 {
10389   struct remote_g_packet_data *data
10390     = ((struct remote_g_packet_data *)
10391        gdbarch_data (gdbarch, remote_g_packet_data_handle));
10392   struct remote_g_packet_guess new_guess, *guess;
10393   int ix;
10394
10395   gdb_assert (tdesc != NULL);
10396
10397   for (ix = 0;
10398        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10399        ix++)
10400     if (guess->bytes == bytes)
10401       internal_error (__FILE__, __LINE__,
10402                       _("Duplicate g packet description added for size %d"),
10403                       bytes);
10404
10405   new_guess.bytes = bytes;
10406   new_guess.tdesc = tdesc;
10407   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10408 }
10409
10410 /* Return 1 if remote_read_description would do anything on this target
10411    and architecture, 0 otherwise.  */
10412
10413 static int
10414 remote_read_description_p (struct target_ops *target)
10415 {
10416   struct remote_g_packet_data *data
10417     = ((struct remote_g_packet_data *)
10418        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10419
10420   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10421     return 1;
10422
10423   return 0;
10424 }
10425
10426 static const struct target_desc *
10427 remote_read_description (struct target_ops *target)
10428 {
10429   struct remote_g_packet_data *data
10430     = ((struct remote_g_packet_data *)
10431        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10432
10433   /* Do not try this during initial connection, when we do not know
10434      whether there is a running but stopped thread.  */
10435   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10436     return target->beneath->to_read_description (target->beneath);
10437
10438   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10439     {
10440       struct remote_g_packet_guess *guess;
10441       int ix;
10442       int bytes = send_g_packet ();
10443
10444       for (ix = 0;
10445            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10446            ix++)
10447         if (guess->bytes == bytes)
10448           return guess->tdesc;
10449
10450       /* We discard the g packet.  A minor optimization would be to
10451          hold on to it, and fill the register cache once we have selected
10452          an architecture, but it's too tricky to do safely.  */
10453     }
10454
10455   return target->beneath->to_read_description (target->beneath);
10456 }
10457
10458 /* Remote file transfer support.  This is host-initiated I/O, not
10459    target-initiated; for target-initiated, see remote-fileio.c.  */
10460
10461 /* If *LEFT is at least the length of STRING, copy STRING to
10462    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10463    decrease *LEFT.  Otherwise raise an error.  */
10464
10465 static void
10466 remote_buffer_add_string (char **buffer, int *left, char *string)
10467 {
10468   int len = strlen (string);
10469
10470   if (len > *left)
10471     error (_("Packet too long for target."));
10472
10473   memcpy (*buffer, string, len);
10474   *buffer += len;
10475   *left -= len;
10476
10477   /* NUL-terminate the buffer as a convenience, if there is
10478      room.  */
10479   if (*left)
10480     **buffer = '\0';
10481 }
10482
10483 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10484    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10485    decrease *LEFT.  Otherwise raise an error.  */
10486
10487 static void
10488 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10489                          int len)
10490 {
10491   if (2 * len > *left)
10492     error (_("Packet too long for target."));
10493
10494   bin2hex (bytes, *buffer, len);
10495   *buffer += 2 * len;
10496   *left -= 2 * len;
10497
10498   /* NUL-terminate the buffer as a convenience, if there is
10499      room.  */
10500   if (*left)
10501     **buffer = '\0';
10502 }
10503
10504 /* If *LEFT is large enough, convert VALUE to hex and add it to
10505    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10506    decrease *LEFT.  Otherwise raise an error.  */
10507
10508 static void
10509 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10510 {
10511   int len = hexnumlen (value);
10512
10513   if (len > *left)
10514     error (_("Packet too long for target."));
10515
10516   hexnumstr (*buffer, value);
10517   *buffer += len;
10518   *left -= len;
10519
10520   /* NUL-terminate the buffer as a convenience, if there is
10521      room.  */
10522   if (*left)
10523     **buffer = '\0';
10524 }
10525
10526 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
10527    value, *REMOTE_ERRNO to the remote error number or zero if none
10528    was included, and *ATTACHMENT to point to the start of the annex
10529    if any.  The length of the packet isn't needed here; there may
10530    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10531
10532    Return 0 if the packet could be parsed, -1 if it could not.  If
10533    -1 is returned, the other variables may not be initialized.  */
10534
10535 static int
10536 remote_hostio_parse_result (char *buffer, int *retcode,
10537                             int *remote_errno, char **attachment)
10538 {
10539   char *p, *p2;
10540
10541   *remote_errno = 0;
10542   *attachment = NULL;
10543
10544   if (buffer[0] != 'F')
10545     return -1;
10546
10547   errno = 0;
10548   *retcode = strtol (&buffer[1], &p, 16);
10549   if (errno != 0 || p == &buffer[1])
10550     return -1;
10551
10552   /* Check for ",errno".  */
10553   if (*p == ',')
10554     {
10555       errno = 0;
10556       *remote_errno = strtol (p + 1, &p2, 16);
10557       if (errno != 0 || p + 1 == p2)
10558         return -1;
10559       p = p2;
10560     }
10561
10562   /* Check for ";attachment".  If there is no attachment, the
10563      packet should end here.  */
10564   if (*p == ';')
10565     {
10566       *attachment = p + 1;
10567       return 0;
10568     }
10569   else if (*p == '\0')
10570     return 0;
10571   else
10572     return -1;
10573 }
10574
10575 /* Send a prepared I/O packet to the target and read its response.
10576    The prepared packet is in the global RS->BUF before this function
10577    is called, and the answer is there when we return.
10578
10579    COMMAND_BYTES is the length of the request to send, which may include
10580    binary data.  WHICH_PACKET is the packet configuration to check
10581    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
10582    is set to the error number and -1 is returned.  Otherwise the value
10583    returned by the function is returned.
10584
10585    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10586    attachment is expected; an error will be reported if there's a
10587    mismatch.  If one is found, *ATTACHMENT will be set to point into
10588    the packet buffer and *ATTACHMENT_LEN will be set to the
10589    attachment's length.  */
10590
10591 static int
10592 remote_hostio_send_command (int command_bytes, int which_packet,
10593                             int *remote_errno, char **attachment,
10594                             int *attachment_len)
10595 {
10596   struct remote_state *rs = get_remote_state ();
10597   int ret, bytes_read;
10598   char *attachment_tmp;
10599
10600   if (!rs->remote_desc
10601       || packet_support (which_packet) == PACKET_DISABLE)
10602     {
10603       *remote_errno = FILEIO_ENOSYS;
10604       return -1;
10605     }
10606
10607   putpkt_binary (rs->buf, command_bytes);
10608   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10609
10610   /* If it timed out, something is wrong.  Don't try to parse the
10611      buffer.  */
10612   if (bytes_read < 0)
10613     {
10614       *remote_errno = FILEIO_EINVAL;
10615       return -1;
10616     }
10617
10618   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10619     {
10620     case PACKET_ERROR:
10621       *remote_errno = FILEIO_EINVAL;
10622       return -1;
10623     case PACKET_UNKNOWN:
10624       *remote_errno = FILEIO_ENOSYS;
10625       return -1;
10626     case PACKET_OK:
10627       break;
10628     }
10629
10630   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10631                                   &attachment_tmp))
10632     {
10633       *remote_errno = FILEIO_EINVAL;
10634       return -1;
10635     }
10636
10637   /* Make sure we saw an attachment if and only if we expected one.  */
10638   if ((attachment_tmp == NULL && attachment != NULL)
10639       || (attachment_tmp != NULL && attachment == NULL))
10640     {
10641       *remote_errno = FILEIO_EINVAL;
10642       return -1;
10643     }
10644
10645   /* If an attachment was found, it must point into the packet buffer;
10646      work out how many bytes there were.  */
10647   if (attachment_tmp != NULL)
10648     {
10649       *attachment = attachment_tmp;
10650       *attachment_len = bytes_read - (*attachment - rs->buf);
10651     }
10652
10653   return ret;
10654 }
10655
10656 /* Invalidate the readahead cache.  */
10657
10658 static void
10659 readahead_cache_invalidate (void)
10660 {
10661   struct remote_state *rs = get_remote_state ();
10662
10663   rs->readahead_cache.fd = -1;
10664 }
10665
10666 /* Invalidate the readahead cache if it is holding data for FD.  */
10667
10668 static void
10669 readahead_cache_invalidate_fd (int fd)
10670 {
10671   struct remote_state *rs = get_remote_state ();
10672
10673   if (rs->readahead_cache.fd == fd)
10674     rs->readahead_cache.fd = -1;
10675 }
10676
10677 /* Set the filesystem remote_hostio functions that take FILENAME
10678    arguments will use.  Return 0 on success, or -1 if an error
10679    occurs (and set *REMOTE_ERRNO).  */
10680
10681 static int
10682 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10683 {
10684   struct remote_state *rs = get_remote_state ();
10685   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10686   char *p = rs->buf;
10687   int left = get_remote_packet_size () - 1;
10688   char arg[9];
10689   int ret;
10690
10691   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10692     return 0;
10693
10694   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10695     return 0;
10696
10697   remote_buffer_add_string (&p, &left, "vFile:setfs:");
10698
10699   xsnprintf (arg, sizeof (arg), "%x", required_pid);
10700   remote_buffer_add_string (&p, &left, arg);
10701
10702   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10703                                     remote_errno, NULL, NULL);
10704
10705   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10706     return 0;
10707
10708   if (ret == 0)
10709     rs->fs_pid = required_pid;
10710
10711   return ret;
10712 }
10713
10714 /* Implementation of to_fileio_open.  */
10715
10716 static int
10717 remote_hostio_open (struct target_ops *self,
10718                     struct inferior *inf, const char *filename,
10719                     int flags, int mode, int warn_if_slow,
10720                     int *remote_errno)
10721 {
10722   struct remote_state *rs = get_remote_state ();
10723   char *p = rs->buf;
10724   int left = get_remote_packet_size () - 1;
10725
10726   if (warn_if_slow)
10727     {
10728       static int warning_issued = 0;
10729
10730       printf_unfiltered (_("Reading %s from remote target...\n"),
10731                          filename);
10732
10733       if (!warning_issued)
10734         {
10735           warning (_("File transfers from remote targets can be slow."
10736                      " Use \"set sysroot\" to access files locally"
10737                      " instead."));
10738           warning_issued = 1;
10739         }
10740     }
10741
10742   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10743     return -1;
10744
10745   remote_buffer_add_string (&p, &left, "vFile:open:");
10746
10747   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10748                            strlen (filename));
10749   remote_buffer_add_string (&p, &left, ",");
10750
10751   remote_buffer_add_int (&p, &left, flags);
10752   remote_buffer_add_string (&p, &left, ",");
10753
10754   remote_buffer_add_int (&p, &left, mode);
10755
10756   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10757                                      remote_errno, NULL, NULL);
10758 }
10759
10760 /* Implementation of to_fileio_pwrite.  */
10761
10762 static int
10763 remote_hostio_pwrite (struct target_ops *self,
10764                       int fd, const gdb_byte *write_buf, int len,
10765                       ULONGEST offset, int *remote_errno)
10766 {
10767   struct remote_state *rs = get_remote_state ();
10768   char *p = rs->buf;
10769   int left = get_remote_packet_size ();
10770   int out_len;
10771
10772   readahead_cache_invalidate_fd (fd);
10773
10774   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10775
10776   remote_buffer_add_int (&p, &left, fd);
10777   remote_buffer_add_string (&p, &left, ",");
10778
10779   remote_buffer_add_int (&p, &left, offset);
10780   remote_buffer_add_string (&p, &left, ",");
10781
10782   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10783                              get_remote_packet_size () - (p - rs->buf));
10784
10785   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10786                                      remote_errno, NULL, NULL);
10787 }
10788
10789 /* Helper for the implementation of to_fileio_pread.  Read the file
10790    from the remote side with vFile:pread.  */
10791
10792 static int
10793 remote_hostio_pread_vFile (struct target_ops *self,
10794                            int fd, gdb_byte *read_buf, int len,
10795                            ULONGEST offset, int *remote_errno)
10796 {
10797   struct remote_state *rs = get_remote_state ();
10798   char *p = rs->buf;
10799   char *attachment;
10800   int left = get_remote_packet_size ();
10801   int ret, attachment_len;
10802   int read_len;
10803
10804   remote_buffer_add_string (&p, &left, "vFile:pread:");
10805
10806   remote_buffer_add_int (&p, &left, fd);
10807   remote_buffer_add_string (&p, &left, ",");
10808
10809   remote_buffer_add_int (&p, &left, len);
10810   remote_buffer_add_string (&p, &left, ",");
10811
10812   remote_buffer_add_int (&p, &left, offset);
10813
10814   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10815                                     remote_errno, &attachment,
10816                                     &attachment_len);
10817
10818   if (ret < 0)
10819     return ret;
10820
10821   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10822                                     read_buf, len);
10823   if (read_len != ret)
10824     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10825
10826   return ret;
10827 }
10828
10829 /* Serve pread from the readahead cache.  Returns number of bytes
10830    read, or 0 if the request can't be served from the cache.  */
10831
10832 static int
10833 remote_hostio_pread_from_cache (struct remote_state *rs,
10834                                 int fd, gdb_byte *read_buf, size_t len,
10835                                 ULONGEST offset)
10836 {
10837   struct readahead_cache *cache = &rs->readahead_cache;
10838
10839   if (cache->fd == fd
10840       && cache->offset <= offset
10841       && offset < cache->offset + cache->bufsize)
10842     {
10843       ULONGEST max = cache->offset + cache->bufsize;
10844
10845       if (offset + len > max)
10846         len = max - offset;
10847
10848       memcpy (read_buf, cache->buf + offset - cache->offset, len);
10849       return len;
10850     }
10851
10852   return 0;
10853 }
10854
10855 /* Implementation of to_fileio_pread.  */
10856
10857 static int
10858 remote_hostio_pread (struct target_ops *self,
10859                      int fd, gdb_byte *read_buf, int len,
10860                      ULONGEST offset, int *remote_errno)
10861 {
10862   int ret;
10863   struct remote_state *rs = get_remote_state ();
10864   struct readahead_cache *cache = &rs->readahead_cache;
10865
10866   ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10867   if (ret > 0)
10868     {
10869       cache->hit_count++;
10870
10871       if (remote_debug)
10872         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10873                             pulongest (cache->hit_count));
10874       return ret;
10875     }
10876
10877   cache->miss_count++;
10878   if (remote_debug)
10879     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10880                         pulongest (cache->miss_count));
10881
10882   cache->fd = fd;
10883   cache->offset = offset;
10884   cache->bufsize = get_remote_packet_size ();
10885   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
10886
10887   ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10888                                    cache->offset, remote_errno);
10889   if (ret <= 0)
10890     {
10891       readahead_cache_invalidate_fd (fd);
10892       return ret;
10893     }
10894
10895   cache->bufsize = ret;
10896   return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10897 }
10898
10899 /* Implementation of to_fileio_close.  */
10900
10901 static int
10902 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
10903 {
10904   struct remote_state *rs = get_remote_state ();
10905   char *p = rs->buf;
10906   int left = get_remote_packet_size () - 1;
10907
10908   readahead_cache_invalidate_fd (fd);
10909
10910   remote_buffer_add_string (&p, &left, "vFile:close:");
10911
10912   remote_buffer_add_int (&p, &left, fd);
10913
10914   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10915                                      remote_errno, NULL, NULL);
10916 }
10917
10918 /* Implementation of to_fileio_unlink.  */
10919
10920 static int
10921 remote_hostio_unlink (struct target_ops *self,
10922                       struct inferior *inf, const char *filename,
10923                       int *remote_errno)
10924 {
10925   struct remote_state *rs = get_remote_state ();
10926   char *p = rs->buf;
10927   int left = get_remote_packet_size () - 1;
10928
10929   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10930     return -1;
10931
10932   remote_buffer_add_string (&p, &left, "vFile:unlink:");
10933
10934   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10935                            strlen (filename));
10936
10937   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10938                                      remote_errno, NULL, NULL);
10939 }
10940
10941 /* Implementation of to_fileio_readlink.  */
10942
10943 static char *
10944 remote_hostio_readlink (struct target_ops *self,
10945                         struct inferior *inf, const char *filename,
10946                         int *remote_errno)
10947 {
10948   struct remote_state *rs = get_remote_state ();
10949   char *p = rs->buf;
10950   char *attachment;
10951   int left = get_remote_packet_size ();
10952   int len, attachment_len;
10953   int read_len;
10954   char *ret;
10955
10956   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10957     return NULL;
10958
10959   remote_buffer_add_string (&p, &left, "vFile:readlink:");
10960
10961   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10962                            strlen (filename));
10963
10964   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10965                                     remote_errno, &attachment,
10966                                     &attachment_len);
10967
10968   if (len < 0)
10969     return NULL;
10970
10971   ret = (char *) xmalloc (len + 1);
10972
10973   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10974                                     (gdb_byte *) ret, len);
10975   if (read_len != len)
10976     error (_("Readlink returned %d, but %d bytes."), len, read_len);
10977
10978   ret[len] = '\0';
10979   return ret;
10980 }
10981
10982 /* Implementation of to_fileio_fstat.  */
10983
10984 static int
10985 remote_hostio_fstat (struct target_ops *self,
10986                      int fd, struct stat *st,
10987                      int *remote_errno)
10988 {
10989   struct remote_state *rs = get_remote_state ();
10990   char *p = rs->buf;
10991   int left = get_remote_packet_size ();
10992   int attachment_len, ret;
10993   char *attachment;
10994   struct fio_stat fst;
10995   int read_len;
10996
10997   remote_buffer_add_string (&p, &left, "vFile:fstat:");
10998
10999   remote_buffer_add_int (&p, &left, fd);
11000
11001   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11002                                     remote_errno, &attachment,
11003                                     &attachment_len);
11004   if (ret < 0)
11005     {
11006       if (*remote_errno != FILEIO_ENOSYS)
11007         return ret;
11008
11009       /* Strictly we should return -1, ENOSYS here, but when
11010          "set sysroot remote:" was implemented in August 2008
11011          BFD's need for a stat function was sidestepped with
11012          this hack.  This was not remedied until March 2015
11013          so we retain the previous behavior to avoid breaking
11014          compatibility.
11015
11016          Note that the memset is a March 2015 addition; older
11017          GDBs set st_size *and nothing else* so the structure
11018          would have garbage in all other fields.  This might
11019          break something but retaining the previous behavior
11020          here would be just too wrong.  */
11021
11022       memset (st, 0, sizeof (struct stat));
11023       st->st_size = INT_MAX;
11024       return 0;
11025     }
11026
11027   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11028                                     (gdb_byte *) &fst, sizeof (fst));
11029
11030   if (read_len != ret)
11031     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11032
11033   if (read_len != sizeof (fst))
11034     error (_("vFile:fstat returned %d bytes, but expecting %d."),
11035            read_len, (int) sizeof (fst));
11036
11037   remote_fileio_to_host_stat (&fst, st);
11038
11039   return 0;
11040 }
11041
11042 /* Implementation of to_filesystem_is_local.  */
11043
11044 static int
11045 remote_filesystem_is_local (struct target_ops *self)
11046 {
11047   /* Valgrind GDB presents itself as a remote target but works
11048      on the local filesystem: it does not implement remote get
11049      and users are not expected to set a sysroot.  To handle
11050      this case we treat the remote filesystem as local if the
11051      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11052      does not support vFile:open.  */
11053   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11054     {
11055       enum packet_support ps = packet_support (PACKET_vFile_open);
11056
11057       if (ps == PACKET_SUPPORT_UNKNOWN)
11058         {
11059           int fd, remote_errno;
11060
11061           /* Try opening a file to probe support.  The supplied
11062              filename is irrelevant, we only care about whether
11063              the stub recognizes the packet or not.  */
11064           fd = remote_hostio_open (self, NULL, "just probing",
11065                                    FILEIO_O_RDONLY, 0700, 0,
11066                                    &remote_errno);
11067
11068           if (fd >= 0)
11069             remote_hostio_close (self, fd, &remote_errno);
11070
11071           ps = packet_support (PACKET_vFile_open);
11072         }
11073
11074       if (ps == PACKET_DISABLE)
11075         {
11076           static int warning_issued = 0;
11077
11078           if (!warning_issued)
11079             {
11080               warning (_("remote target does not support file"
11081                          " transfer, attempting to access files"
11082                          " from local filesystem."));
11083               warning_issued = 1;
11084             }
11085
11086           return 1;
11087         }
11088     }
11089
11090   return 0;
11091 }
11092
11093 static int
11094 remote_fileio_errno_to_host (int errnum)
11095 {
11096   switch (errnum)
11097     {
11098       case FILEIO_EPERM:
11099         return EPERM;
11100       case FILEIO_ENOENT:
11101         return ENOENT;
11102       case FILEIO_EINTR:
11103         return EINTR;
11104       case FILEIO_EIO:
11105         return EIO;
11106       case FILEIO_EBADF:
11107         return EBADF;
11108       case FILEIO_EACCES:
11109         return EACCES;
11110       case FILEIO_EFAULT:
11111         return EFAULT;
11112       case FILEIO_EBUSY:
11113         return EBUSY;
11114       case FILEIO_EEXIST:
11115         return EEXIST;
11116       case FILEIO_ENODEV:
11117         return ENODEV;
11118       case FILEIO_ENOTDIR:
11119         return ENOTDIR;
11120       case FILEIO_EISDIR:
11121         return EISDIR;
11122       case FILEIO_EINVAL:
11123         return EINVAL;
11124       case FILEIO_ENFILE:
11125         return ENFILE;
11126       case FILEIO_EMFILE:
11127         return EMFILE;
11128       case FILEIO_EFBIG:
11129         return EFBIG;
11130       case FILEIO_ENOSPC:
11131         return ENOSPC;
11132       case FILEIO_ESPIPE:
11133         return ESPIPE;
11134       case FILEIO_EROFS:
11135         return EROFS;
11136       case FILEIO_ENOSYS:
11137         return ENOSYS;
11138       case FILEIO_ENAMETOOLONG:
11139         return ENAMETOOLONG;
11140     }
11141   return -1;
11142 }
11143
11144 static char *
11145 remote_hostio_error (int errnum)
11146 {
11147   int host_error = remote_fileio_errno_to_host (errnum);
11148
11149   if (host_error == -1)
11150     error (_("Unknown remote I/O error %d"), errnum);
11151   else
11152     error (_("Remote I/O error: %s"), safe_strerror (host_error));
11153 }
11154
11155 static void
11156 remote_hostio_close_cleanup (void *opaque)
11157 {
11158   int fd = *(int *) opaque;
11159   int remote_errno;
11160
11161   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11162 }
11163
11164 void
11165 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11166 {
11167   struct cleanup *back_to, *close_cleanup;
11168   int retcode, fd, remote_errno, bytes, io_size;
11169   FILE *file;
11170   gdb_byte *buffer;
11171   int bytes_in_buffer;
11172   int saw_eof;
11173   ULONGEST offset;
11174   struct remote_state *rs = get_remote_state ();
11175
11176   if (!rs->remote_desc)
11177     error (_("command can only be used with remote target"));
11178
11179   file = gdb_fopen_cloexec (local_file, "rb");
11180   if (file == NULL)
11181     perror_with_name (local_file);
11182   back_to = make_cleanup_fclose (file);
11183
11184   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11185                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11186                                          | FILEIO_O_TRUNC),
11187                            0700, 0, &remote_errno);
11188   if (fd == -1)
11189     remote_hostio_error (remote_errno);
11190
11191   /* Send up to this many bytes at once.  They won't all fit in the
11192      remote packet limit, so we'll transfer slightly fewer.  */
11193   io_size = get_remote_packet_size ();
11194   buffer = (gdb_byte *) xmalloc (io_size);
11195   make_cleanup (xfree, buffer);
11196
11197   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11198
11199   bytes_in_buffer = 0;
11200   saw_eof = 0;
11201   offset = 0;
11202   while (bytes_in_buffer || !saw_eof)
11203     {
11204       if (!saw_eof)
11205         {
11206           bytes = fread (buffer + bytes_in_buffer, 1,
11207                          io_size - bytes_in_buffer,
11208                          file);
11209           if (bytes == 0)
11210             {
11211               if (ferror (file))
11212                 error (_("Error reading %s."), local_file);
11213               else
11214                 {
11215                   /* EOF.  Unless there is something still in the
11216                      buffer from the last iteration, we are done.  */
11217                   saw_eof = 1;
11218                   if (bytes_in_buffer == 0)
11219                     break;
11220                 }
11221             }
11222         }
11223       else
11224         bytes = 0;
11225
11226       bytes += bytes_in_buffer;
11227       bytes_in_buffer = 0;
11228
11229       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11230                                       fd, buffer, bytes,
11231                                       offset, &remote_errno);
11232
11233       if (retcode < 0)
11234         remote_hostio_error (remote_errno);
11235       else if (retcode == 0)
11236         error (_("Remote write of %d bytes returned 0!"), bytes);
11237       else if (retcode < bytes)
11238         {
11239           /* Short write.  Save the rest of the read data for the next
11240              write.  */
11241           bytes_in_buffer = bytes - retcode;
11242           memmove (buffer, buffer + retcode, bytes_in_buffer);
11243         }
11244
11245       offset += retcode;
11246     }
11247
11248   discard_cleanups (close_cleanup);
11249   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11250     remote_hostio_error (remote_errno);
11251
11252   if (from_tty)
11253     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11254   do_cleanups (back_to);
11255 }
11256
11257 void
11258 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11259 {
11260   struct cleanup *back_to, *close_cleanup;
11261   int fd, remote_errno, bytes, io_size;
11262   FILE *file;
11263   gdb_byte *buffer;
11264   ULONGEST offset;
11265   struct remote_state *rs = get_remote_state ();
11266
11267   if (!rs->remote_desc)
11268     error (_("command can only be used with remote target"));
11269
11270   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11271                            remote_file, FILEIO_O_RDONLY, 0, 0,
11272                            &remote_errno);
11273   if (fd == -1)
11274     remote_hostio_error (remote_errno);
11275
11276   file = gdb_fopen_cloexec (local_file, "wb");
11277   if (file == NULL)
11278     perror_with_name (local_file);
11279   back_to = make_cleanup_fclose (file);
11280
11281   /* Send up to this many bytes at once.  They won't all fit in the
11282      remote packet limit, so we'll transfer slightly fewer.  */
11283   io_size = get_remote_packet_size ();
11284   buffer = (gdb_byte *) xmalloc (io_size);
11285   make_cleanup (xfree, buffer);
11286
11287   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11288
11289   offset = 0;
11290   while (1)
11291     {
11292       bytes = remote_hostio_pread (find_target_at (process_stratum),
11293                                    fd, buffer, io_size, offset, &remote_errno);
11294       if (bytes == 0)
11295         /* Success, but no bytes, means end-of-file.  */
11296         break;
11297       if (bytes == -1)
11298         remote_hostio_error (remote_errno);
11299
11300       offset += bytes;
11301
11302       bytes = fwrite (buffer, 1, bytes, file);
11303       if (bytes == 0)
11304         perror_with_name (local_file);
11305     }
11306
11307   discard_cleanups (close_cleanup);
11308   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11309     remote_hostio_error (remote_errno);
11310
11311   if (from_tty)
11312     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11313   do_cleanups (back_to);
11314 }
11315
11316 void
11317 remote_file_delete (const char *remote_file, int from_tty)
11318 {
11319   int retcode, remote_errno;
11320   struct remote_state *rs = get_remote_state ();
11321
11322   if (!rs->remote_desc)
11323     error (_("command can only be used with remote target"));
11324
11325   retcode = remote_hostio_unlink (find_target_at (process_stratum),
11326                                   NULL, remote_file, &remote_errno);
11327   if (retcode == -1)
11328     remote_hostio_error (remote_errno);
11329
11330   if (from_tty)
11331     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11332 }
11333
11334 static void
11335 remote_put_command (char *args, int from_tty)
11336 {
11337   struct cleanup *back_to;
11338   char **argv;
11339
11340   if (args == NULL)
11341     error_no_arg (_("file to put"));
11342
11343   argv = gdb_buildargv (args);
11344   back_to = make_cleanup_freeargv (argv);
11345   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11346     error (_("Invalid parameters to remote put"));
11347
11348   remote_file_put (argv[0], argv[1], from_tty);
11349
11350   do_cleanups (back_to);
11351 }
11352
11353 static void
11354 remote_get_command (char *args, int from_tty)
11355 {
11356   struct cleanup *back_to;
11357   char **argv;
11358
11359   if (args == NULL)
11360     error_no_arg (_("file to get"));
11361
11362   argv = gdb_buildargv (args);
11363   back_to = make_cleanup_freeargv (argv);
11364   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11365     error (_("Invalid parameters to remote get"));
11366
11367   remote_file_get (argv[0], argv[1], from_tty);
11368
11369   do_cleanups (back_to);
11370 }
11371
11372 static void
11373 remote_delete_command (char *args, int from_tty)
11374 {
11375   struct cleanup *back_to;
11376   char **argv;
11377
11378   if (args == NULL)
11379     error_no_arg (_("file to delete"));
11380
11381   argv = gdb_buildargv (args);
11382   back_to = make_cleanup_freeargv (argv);
11383   if (argv[0] == NULL || argv[1] != NULL)
11384     error (_("Invalid parameters to remote delete"));
11385
11386   remote_file_delete (argv[0], from_tty);
11387
11388   do_cleanups (back_to);
11389 }
11390
11391 static void
11392 remote_command (char *args, int from_tty)
11393 {
11394   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11395 }
11396
11397 static int
11398 remote_can_execute_reverse (struct target_ops *self)
11399 {
11400   if (packet_support (PACKET_bs) == PACKET_ENABLE
11401       || packet_support (PACKET_bc) == PACKET_ENABLE)
11402     return 1;
11403   else
11404     return 0;
11405 }
11406
11407 static int
11408 remote_supports_non_stop (struct target_ops *self)
11409 {
11410   return 1;
11411 }
11412
11413 static int
11414 remote_supports_disable_randomization (struct target_ops *self)
11415 {
11416   /* Only supported in extended mode.  */
11417   return 0;
11418 }
11419
11420 static int
11421 remote_supports_multi_process (struct target_ops *self)
11422 {
11423   struct remote_state *rs = get_remote_state ();
11424
11425   /* Only extended-remote handles being attached to multiple
11426      processes, even though plain remote can use the multi-process
11427      thread id extensions, so that GDB knows the target process's
11428      PID.  */
11429   return rs->extended && remote_multi_process_p (rs);
11430 }
11431
11432 static int
11433 remote_supports_cond_tracepoints (void)
11434 {
11435   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11436 }
11437
11438 static int
11439 remote_supports_cond_breakpoints (struct target_ops *self)
11440 {
11441   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11442 }
11443
11444 static int
11445 remote_supports_fast_tracepoints (void)
11446 {
11447   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11448 }
11449
11450 static int
11451 remote_supports_static_tracepoints (void)
11452 {
11453   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11454 }
11455
11456 static int
11457 remote_supports_install_in_trace (void)
11458 {
11459   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11460 }
11461
11462 static int
11463 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11464 {
11465   return (packet_support (PACKET_EnableDisableTracepoints_feature)
11466           == PACKET_ENABLE);
11467 }
11468
11469 static int
11470 remote_supports_string_tracing (struct target_ops *self)
11471 {
11472   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11473 }
11474
11475 static int
11476 remote_can_run_breakpoint_commands (struct target_ops *self)
11477 {
11478   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11479 }
11480
11481 static void
11482 remote_trace_init (struct target_ops *self)
11483 {
11484   putpkt ("QTinit");
11485   remote_get_noisy_reply (&target_buf, &target_buf_size);
11486   if (strcmp (target_buf, "OK") != 0)
11487     error (_("Target does not support this command."));
11488 }
11489
11490 static void free_actions_list (char **actions_list);
11491 static void free_actions_list_cleanup_wrapper (void *);
11492 static void
11493 free_actions_list_cleanup_wrapper (void *al)
11494 {
11495   free_actions_list ((char **) al);
11496 }
11497
11498 static void
11499 free_actions_list (char **actions_list)
11500 {
11501   int ndx;
11502
11503   if (actions_list == 0)
11504     return;
11505
11506   for (ndx = 0; actions_list[ndx]; ndx++)
11507     xfree (actions_list[ndx]);
11508
11509   xfree (actions_list);
11510 }
11511
11512 /* Recursive routine to walk through command list including loops, and
11513    download packets for each command.  */
11514
11515 static void
11516 remote_download_command_source (int num, ULONGEST addr,
11517                                 struct command_line *cmds)
11518 {
11519   struct remote_state *rs = get_remote_state ();
11520   struct command_line *cmd;
11521
11522   for (cmd = cmds; cmd; cmd = cmd->next)
11523     {
11524       QUIT;     /* Allow user to bail out with ^C.  */
11525       strcpy (rs->buf, "QTDPsrc:");
11526       encode_source_string (num, addr, "cmd", cmd->line,
11527                             rs->buf + strlen (rs->buf),
11528                             rs->buf_size - strlen (rs->buf));
11529       putpkt (rs->buf);
11530       remote_get_noisy_reply (&target_buf, &target_buf_size);
11531       if (strcmp (target_buf, "OK"))
11532         warning (_("Target does not support source download."));
11533
11534       if (cmd->control_type == while_control
11535           || cmd->control_type == while_stepping_control)
11536         {
11537           remote_download_command_source (num, addr, *cmd->body_list);
11538
11539           QUIT; /* Allow user to bail out with ^C.  */
11540           strcpy (rs->buf, "QTDPsrc:");
11541           encode_source_string (num, addr, "cmd", "end",
11542                                 rs->buf + strlen (rs->buf),
11543                                 rs->buf_size - strlen (rs->buf));
11544           putpkt (rs->buf);
11545           remote_get_noisy_reply (&target_buf, &target_buf_size);
11546           if (strcmp (target_buf, "OK"))
11547             warning (_("Target does not support source download."));
11548         }
11549     }
11550 }
11551
11552 static void
11553 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11554 {
11555 #define BUF_SIZE 2048
11556
11557   CORE_ADDR tpaddr;
11558   char addrbuf[40];
11559   char buf[BUF_SIZE];
11560   char **tdp_actions;
11561   char **stepping_actions;
11562   int ndx;
11563   struct cleanup *old_chain = NULL;
11564   struct agent_expr *aexpr;
11565   struct cleanup *aexpr_chain = NULL;
11566   char *pkt;
11567   struct breakpoint *b = loc->owner;
11568   struct tracepoint *t = (struct tracepoint *) b;
11569
11570   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11571   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11572                             tdp_actions);
11573   (void) make_cleanup (free_actions_list_cleanup_wrapper,
11574                        stepping_actions);
11575
11576   tpaddr = loc->address;
11577   sprintf_vma (addrbuf, tpaddr);
11578   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11579              addrbuf, /* address */
11580              (b->enable_state == bp_enabled ? 'E' : 'D'),
11581              t->step_count, t->pass_count);
11582   /* Fast tracepoints are mostly handled by the target, but we can
11583      tell the target how big of an instruction block should be moved
11584      around.  */
11585   if (b->type == bp_fast_tracepoint)
11586     {
11587       /* Only test for support at download time; we may not know
11588          target capabilities at definition time.  */
11589       if (remote_supports_fast_tracepoints ())
11590         {
11591           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11592                                                 NULL))
11593             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11594                        gdb_insn_length (loc->gdbarch, tpaddr));
11595           else
11596             /* If it passed validation at definition but fails now,
11597                something is very wrong.  */
11598             internal_error (__FILE__, __LINE__,
11599                             _("Fast tracepoint not "
11600                               "valid during download"));
11601         }
11602       else
11603         /* Fast tracepoints are functionally identical to regular
11604            tracepoints, so don't take lack of support as a reason to
11605            give up on the trace run.  */
11606         warning (_("Target does not support fast tracepoints, "
11607                    "downloading %d as regular tracepoint"), b->number);
11608     }
11609   else if (b->type == bp_static_tracepoint)
11610     {
11611       /* Only test for support at download time; we may not know
11612          target capabilities at definition time.  */
11613       if (remote_supports_static_tracepoints ())
11614         {
11615           struct static_tracepoint_marker marker;
11616
11617           if (target_static_tracepoint_marker_at (tpaddr, &marker))
11618             strcat (buf, ":S");
11619           else
11620             error (_("Static tracepoint not valid during download"));
11621         }
11622       else
11623         /* Fast tracepoints are functionally identical to regular
11624            tracepoints, so don't take lack of support as a reason
11625            to give up on the trace run.  */
11626         error (_("Target does not support static tracepoints"));
11627     }
11628   /* If the tracepoint has a conditional, make it into an agent
11629      expression and append to the definition.  */
11630   if (loc->cond)
11631     {
11632       /* Only test support at download time, we may not know target
11633          capabilities at definition time.  */
11634       if (remote_supports_cond_tracepoints ())
11635         {
11636           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11637           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11638           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11639                      aexpr->len);
11640           pkt = buf + strlen (buf);
11641           for (ndx = 0; ndx < aexpr->len; ++ndx)
11642             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11643           *pkt = '\0';
11644           do_cleanups (aexpr_chain);
11645         }
11646       else
11647         warning (_("Target does not support conditional tracepoints, "
11648                    "ignoring tp %d cond"), b->number);
11649     }
11650
11651   if (b->commands || *default_collect)
11652     strcat (buf, "-");
11653   putpkt (buf);
11654   remote_get_noisy_reply (&target_buf, &target_buf_size);
11655   if (strcmp (target_buf, "OK"))
11656     error (_("Target does not support tracepoints."));
11657
11658   /* do_single_steps (t); */
11659   if (tdp_actions)
11660     {
11661       for (ndx = 0; tdp_actions[ndx]; ndx++)
11662         {
11663           QUIT; /* Allow user to bail out with ^C.  */
11664           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11665                      b->number, addrbuf, /* address */
11666                      tdp_actions[ndx],
11667                      ((tdp_actions[ndx + 1] || stepping_actions)
11668                       ? '-' : 0));
11669           putpkt (buf);
11670           remote_get_noisy_reply (&target_buf,
11671                                   &target_buf_size);
11672           if (strcmp (target_buf, "OK"))
11673             error (_("Error on target while setting tracepoints."));
11674         }
11675     }
11676   if (stepping_actions)
11677     {
11678       for (ndx = 0; stepping_actions[ndx]; ndx++)
11679         {
11680           QUIT; /* Allow user to bail out with ^C.  */
11681           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11682                      b->number, addrbuf, /* address */
11683                      ((ndx == 0) ? "S" : ""),
11684                      stepping_actions[ndx],
11685                      (stepping_actions[ndx + 1] ? "-" : ""));
11686           putpkt (buf);
11687           remote_get_noisy_reply (&target_buf,
11688                                   &target_buf_size);
11689           if (strcmp (target_buf, "OK"))
11690             error (_("Error on target while setting tracepoints."));
11691         }
11692     }
11693
11694   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11695     {
11696       if (b->location != NULL)
11697         {
11698           strcpy (buf, "QTDPsrc:");
11699           encode_source_string (b->number, loc->address, "at",
11700                                 event_location_to_string (b->location),
11701                                 buf + strlen (buf), 2048 - strlen (buf));
11702           putpkt (buf);
11703           remote_get_noisy_reply (&target_buf, &target_buf_size);
11704           if (strcmp (target_buf, "OK"))
11705             warning (_("Target does not support source download."));
11706         }
11707       if (b->cond_string)
11708         {
11709           strcpy (buf, "QTDPsrc:");
11710           encode_source_string (b->number, loc->address,
11711                                 "cond", b->cond_string, buf + strlen (buf),
11712                                 2048 - strlen (buf));
11713           putpkt (buf);
11714           remote_get_noisy_reply (&target_buf, &target_buf_size);
11715           if (strcmp (target_buf, "OK"))
11716             warning (_("Target does not support source download."));
11717         }
11718       remote_download_command_source (b->number, loc->address,
11719                                       breakpoint_commands (b));
11720     }
11721
11722   do_cleanups (old_chain);
11723 }
11724
11725 static int
11726 remote_can_download_tracepoint (struct target_ops *self)
11727 {
11728   struct remote_state *rs = get_remote_state ();
11729   struct trace_status *ts;
11730   int status;
11731
11732   /* Don't try to install tracepoints until we've relocated our
11733      symbols, and fetched and merged the target's tracepoint list with
11734      ours.  */
11735   if (rs->starting_up)
11736     return 0;
11737
11738   ts = current_trace_status ();
11739   status = remote_get_trace_status (self, ts);
11740
11741   if (status == -1 || !ts->running_known || !ts->running)
11742     return 0;
11743
11744   /* If we are in a tracing experiment, but remote stub doesn't support
11745      installing tracepoint in trace, we have to return.  */
11746   if (!remote_supports_install_in_trace ())
11747     return 0;
11748
11749   return 1;
11750 }
11751
11752
11753 static void
11754 remote_download_trace_state_variable (struct target_ops *self,
11755                                       struct trace_state_variable *tsv)
11756 {
11757   struct remote_state *rs = get_remote_state ();
11758   char *p;
11759
11760   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11761              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11762              tsv->builtin);
11763   p = rs->buf + strlen (rs->buf);
11764   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11765     error (_("Trace state variable name too long for tsv definition packet"));
11766   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11767   *p++ = '\0';
11768   putpkt (rs->buf);
11769   remote_get_noisy_reply (&target_buf, &target_buf_size);
11770   if (*target_buf == '\0')
11771     error (_("Target does not support this command."));
11772   if (strcmp (target_buf, "OK") != 0)
11773     error (_("Error on target while downloading trace state variable."));
11774 }
11775
11776 static void
11777 remote_enable_tracepoint (struct target_ops *self,
11778                           struct bp_location *location)
11779 {
11780   struct remote_state *rs = get_remote_state ();
11781   char addr_buf[40];
11782
11783   sprintf_vma (addr_buf, location->address);
11784   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11785              location->owner->number, addr_buf);
11786   putpkt (rs->buf);
11787   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11788   if (*rs->buf == '\0')
11789     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11790   if (strcmp (rs->buf, "OK") != 0)
11791     error (_("Error on target while enabling tracepoint."));
11792 }
11793
11794 static void
11795 remote_disable_tracepoint (struct target_ops *self,
11796                            struct bp_location *location)
11797 {
11798   struct remote_state *rs = get_remote_state ();
11799   char addr_buf[40];
11800
11801   sprintf_vma (addr_buf, location->address);
11802   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11803              location->owner->number, addr_buf);
11804   putpkt (rs->buf);
11805   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11806   if (*rs->buf == '\0')
11807     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11808   if (strcmp (rs->buf, "OK") != 0)
11809     error (_("Error on target while disabling tracepoint."));
11810 }
11811
11812 static void
11813 remote_trace_set_readonly_regions (struct target_ops *self)
11814 {
11815   asection *s;
11816   bfd *abfd = NULL;
11817   bfd_size_type size;
11818   bfd_vma vma;
11819   int anysecs = 0;
11820   int offset = 0;
11821
11822   if (!exec_bfd)
11823     return;                     /* No information to give.  */
11824
11825   strcpy (target_buf, "QTro");
11826   offset = strlen (target_buf);
11827   for (s = exec_bfd->sections; s; s = s->next)
11828     {
11829       char tmp1[40], tmp2[40];
11830       int sec_length;
11831
11832       if ((s->flags & SEC_LOAD) == 0 ||
11833       /*  (s->flags & SEC_CODE) == 0 || */
11834           (s->flags & SEC_READONLY) == 0)
11835         continue;
11836
11837       anysecs = 1;
11838       vma = bfd_get_section_vma (abfd, s);
11839       size = bfd_get_section_size (s);
11840       sprintf_vma (tmp1, vma);
11841       sprintf_vma (tmp2, vma + size);
11842       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11843       if (offset + sec_length + 1 > target_buf_size)
11844         {
11845           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
11846             warning (_("\
11847 Too many sections for read-only sections definition packet."));
11848           break;
11849         }
11850       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11851                  tmp1, tmp2);
11852       offset += sec_length;
11853     }
11854   if (anysecs)
11855     {
11856       putpkt (target_buf);
11857       getpkt (&target_buf, &target_buf_size, 0);
11858     }
11859 }
11860
11861 static void
11862 remote_trace_start (struct target_ops *self)
11863 {
11864   putpkt ("QTStart");
11865   remote_get_noisy_reply (&target_buf, &target_buf_size);
11866   if (*target_buf == '\0')
11867     error (_("Target does not support this command."));
11868   if (strcmp (target_buf, "OK") != 0)
11869     error (_("Bogus reply from target: %s"), target_buf);
11870 }
11871
11872 static int
11873 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
11874 {
11875   /* Initialize it just to avoid a GCC false warning.  */
11876   char *p = NULL;
11877   /* FIXME we need to get register block size some other way.  */
11878   extern int trace_regblock_size;
11879   enum packet_result result;
11880
11881   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
11882     return -1;
11883
11884   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11885
11886   putpkt ("qTStatus");
11887
11888   TRY
11889     {
11890       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11891     }
11892   CATCH (ex, RETURN_MASK_ERROR)
11893     {
11894       if (ex.error != TARGET_CLOSE_ERROR)
11895         {
11896           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11897           return -1;
11898         }
11899       throw_exception (ex);
11900     }
11901   END_CATCH
11902
11903   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11904
11905   /* If the remote target doesn't do tracing, flag it.  */
11906   if (result == PACKET_UNKNOWN)
11907     return -1;
11908
11909   /* We're working with a live target.  */
11910   ts->filename = NULL;
11911
11912   if (*p++ != 'T')
11913     error (_("Bogus trace status reply from target: %s"), target_buf);
11914
11915   /* Function 'parse_trace_status' sets default value of each field of
11916      'ts' at first, so we don't have to do it here.  */
11917   parse_trace_status (p, ts);
11918
11919   return ts->running;
11920 }
11921
11922 static void
11923 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
11924                               struct uploaded_tp *utp)
11925 {
11926   struct remote_state *rs = get_remote_state ();
11927   char *reply;
11928   struct bp_location *loc;
11929   struct tracepoint *tp = (struct tracepoint *) bp;
11930   size_t size = get_remote_packet_size ();
11931
11932   if (tp)
11933     {
11934       tp->base.hit_count = 0;
11935       tp->traceframe_usage = 0;
11936       for (loc = tp->base.loc; loc; loc = loc->next)
11937         {
11938           /* If the tracepoint was never downloaded, don't go asking for
11939              any status.  */
11940           if (tp->number_on_target == 0)
11941             continue;
11942           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11943                      phex_nz (loc->address, 0));
11944           putpkt (rs->buf);
11945           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11946           if (reply && *reply)
11947             {
11948               if (*reply == 'V')
11949                 parse_tracepoint_status (reply + 1, bp, utp);
11950             }
11951         }
11952     }
11953   else if (utp)
11954     {
11955       utp->hit_count = 0;
11956       utp->traceframe_usage = 0;
11957       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11958                  phex_nz (utp->addr, 0));
11959       putpkt (rs->buf);
11960       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11961       if (reply && *reply)
11962         {
11963           if (*reply == 'V')
11964             parse_tracepoint_status (reply + 1, bp, utp);
11965         }
11966     }
11967 }
11968
11969 static void
11970 remote_trace_stop (struct target_ops *self)
11971 {
11972   putpkt ("QTStop");
11973   remote_get_noisy_reply (&target_buf, &target_buf_size);
11974   if (*target_buf == '\0')
11975     error (_("Target does not support this command."));
11976   if (strcmp (target_buf, "OK") != 0)
11977     error (_("Bogus reply from target: %s"), target_buf);
11978 }
11979
11980 static int
11981 remote_trace_find (struct target_ops *self,
11982                    enum trace_find_type type, int num,
11983                    CORE_ADDR addr1, CORE_ADDR addr2,
11984                    int *tpp)
11985 {
11986   struct remote_state *rs = get_remote_state ();
11987   char *endbuf = rs->buf + get_remote_packet_size ();
11988   char *p, *reply;
11989   int target_frameno = -1, target_tracept = -1;
11990
11991   /* Lookups other than by absolute frame number depend on the current
11992      trace selected, so make sure it is correct on the remote end
11993      first.  */
11994   if (type != tfind_number)
11995     set_remote_traceframe ();
11996
11997   p = rs->buf;
11998   strcpy (p, "QTFrame:");
11999   p = strchr (p, '\0');
12000   switch (type)
12001     {
12002     case tfind_number:
12003       xsnprintf (p, endbuf - p, "%x", num);
12004       break;
12005     case tfind_pc:
12006       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12007       break;
12008     case tfind_tp:
12009       xsnprintf (p, endbuf - p, "tdp:%x", num);
12010       break;
12011     case tfind_range:
12012       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12013                  phex_nz (addr2, 0));
12014       break;
12015     case tfind_outside:
12016       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12017                  phex_nz (addr2, 0));
12018       break;
12019     default:
12020       error (_("Unknown trace find type %d"), type);
12021     }
12022
12023   putpkt (rs->buf);
12024   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12025   if (*reply == '\0')
12026     error (_("Target does not support this command."));
12027
12028   while (reply && *reply)
12029     switch (*reply)
12030       {
12031       case 'F':
12032         p = ++reply;
12033         target_frameno = (int) strtol (p, &reply, 16);
12034         if (reply == p)
12035           error (_("Unable to parse trace frame number"));
12036         /* Don't update our remote traceframe number cache on failure
12037            to select a remote traceframe.  */
12038         if (target_frameno == -1)
12039           return -1;
12040         break;
12041       case 'T':
12042         p = ++reply;
12043         target_tracept = (int) strtol (p, &reply, 16);
12044         if (reply == p)
12045           error (_("Unable to parse tracepoint number"));
12046         break;
12047       case 'O':         /* "OK"? */
12048         if (reply[1] == 'K' && reply[2] == '\0')
12049           reply += 2;
12050         else
12051           error (_("Bogus reply from target: %s"), reply);
12052         break;
12053       default:
12054         error (_("Bogus reply from target: %s"), reply);
12055       }
12056   if (tpp)
12057     *tpp = target_tracept;
12058
12059   rs->remote_traceframe_number = target_frameno;
12060   return target_frameno;
12061 }
12062
12063 static int
12064 remote_get_trace_state_variable_value (struct target_ops *self,
12065                                        int tsvnum, LONGEST *val)
12066 {
12067   struct remote_state *rs = get_remote_state ();
12068   char *reply;
12069   ULONGEST uval;
12070
12071   set_remote_traceframe ();
12072
12073   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12074   putpkt (rs->buf);
12075   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12076   if (reply && *reply)
12077     {
12078       if (*reply == 'V')
12079         {
12080           unpack_varlen_hex (reply + 1, &uval);
12081           *val = (LONGEST) uval;
12082           return 1;
12083         }
12084     }
12085   return 0;
12086 }
12087
12088 static int
12089 remote_save_trace_data (struct target_ops *self, const char *filename)
12090 {
12091   struct remote_state *rs = get_remote_state ();
12092   char *p, *reply;
12093
12094   p = rs->buf;
12095   strcpy (p, "QTSave:");
12096   p += strlen (p);
12097   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12098     error (_("Remote file name too long for trace save packet"));
12099   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12100   *p++ = '\0';
12101   putpkt (rs->buf);
12102   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12103   if (*reply == '\0')
12104     error (_("Target does not support this command."));
12105   if (strcmp (reply, "OK") != 0)
12106     error (_("Bogus reply from target: %s"), reply);
12107   return 0;
12108 }
12109
12110 /* This is basically a memory transfer, but needs to be its own packet
12111    because we don't know how the target actually organizes its trace
12112    memory, plus we want to be able to ask for as much as possible, but
12113    not be unhappy if we don't get as much as we ask for.  */
12114
12115 static LONGEST
12116 remote_get_raw_trace_data (struct target_ops *self,
12117                            gdb_byte *buf, ULONGEST offset, LONGEST len)
12118 {
12119   struct remote_state *rs = get_remote_state ();
12120   char *reply;
12121   char *p;
12122   int rslt;
12123
12124   p = rs->buf;
12125   strcpy (p, "qTBuffer:");
12126   p += strlen (p);
12127   p += hexnumstr (p, offset);
12128   *p++ = ',';
12129   p += hexnumstr (p, len);
12130   *p++ = '\0';
12131
12132   putpkt (rs->buf);
12133   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12134   if (reply && *reply)
12135     {
12136       /* 'l' by itself means we're at the end of the buffer and
12137          there is nothing more to get.  */
12138       if (*reply == 'l')
12139         return 0;
12140
12141       /* Convert the reply into binary.  Limit the number of bytes to
12142          convert according to our passed-in buffer size, rather than
12143          what was returned in the packet; if the target is
12144          unexpectedly generous and gives us a bigger reply than we
12145          asked for, we don't want to crash.  */
12146       rslt = hex2bin (target_buf, buf, len);
12147       return rslt;
12148     }
12149
12150   /* Something went wrong, flag as an error.  */
12151   return -1;
12152 }
12153
12154 static void
12155 remote_set_disconnected_tracing (struct target_ops *self, int val)
12156 {
12157   struct remote_state *rs = get_remote_state ();
12158
12159   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12160     {
12161       char *reply;
12162
12163       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12164       putpkt (rs->buf);
12165       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12166       if (*reply == '\0')
12167         error (_("Target does not support this command."));
12168       if (strcmp (reply, "OK") != 0)
12169         error (_("Bogus reply from target: %s"), reply);
12170     }
12171   else if (val)
12172     warning (_("Target does not support disconnected tracing."));
12173 }
12174
12175 static int
12176 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12177 {
12178   struct thread_info *info = find_thread_ptid (ptid);
12179
12180   if (info && info->priv)
12181     return info->priv->core;
12182   return -1;
12183 }
12184
12185 static void
12186 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12187 {
12188   struct remote_state *rs = get_remote_state ();
12189   char *reply;
12190
12191   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12192   putpkt (rs->buf);
12193   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12194   if (*reply == '\0')
12195     error (_("Target does not support this command."));
12196   if (strcmp (reply, "OK") != 0)
12197     error (_("Bogus reply from target: %s"), reply);
12198 }
12199
12200 static struct traceframe_info *
12201 remote_traceframe_info (struct target_ops *self)
12202 {
12203   char *text;
12204
12205   text = target_read_stralloc (&current_target,
12206                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12207   if (text != NULL)
12208     {
12209       struct traceframe_info *info;
12210       struct cleanup *back_to = make_cleanup (xfree, text);
12211
12212       info = parse_traceframe_info (text);
12213       do_cleanups (back_to);
12214       return info;
12215     }
12216
12217   return NULL;
12218 }
12219
12220 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
12221    instruction on which a fast tracepoint may be placed.  Returns -1
12222    if the packet is not supported, and 0 if the minimum instruction
12223    length is unknown.  */
12224
12225 static int
12226 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12227 {
12228   struct remote_state *rs = get_remote_state ();
12229   char *reply;
12230
12231   /* If we're not debugging a process yet, the IPA can't be
12232      loaded.  */
12233   if (!target_has_execution)
12234     return 0;
12235
12236   /* Make sure the remote is pointing at the right process.  */
12237   set_general_process ();
12238
12239   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12240   putpkt (rs->buf);
12241   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12242   if (*reply == '\0')
12243     return -1;
12244   else
12245     {
12246       ULONGEST min_insn_len;
12247
12248       unpack_varlen_hex (reply, &min_insn_len);
12249
12250       return (int) min_insn_len;
12251     }
12252 }
12253
12254 static void
12255 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12256 {
12257   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12258     {
12259       struct remote_state *rs = get_remote_state ();
12260       char *buf = rs->buf;
12261       char *endbuf = rs->buf + get_remote_packet_size ();
12262       enum packet_result result;
12263
12264       gdb_assert (val >= 0 || val == -1);
12265       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12266       /* Send -1 as literal "-1" to avoid host size dependency.  */
12267       if (val < 0)
12268         {
12269           *buf++ = '-';
12270           buf += hexnumstr (buf, (ULONGEST) -val);
12271         }
12272       else
12273         buf += hexnumstr (buf, (ULONGEST) val);
12274
12275       putpkt (rs->buf);
12276       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12277       result = packet_ok (rs->buf,
12278                   &remote_protocol_packets[PACKET_QTBuffer_size]);
12279
12280       if (result != PACKET_OK)
12281         warning (_("Bogus reply from target: %s"), rs->buf);
12282     }
12283 }
12284
12285 static int
12286 remote_set_trace_notes (struct target_ops *self,
12287                         const char *user, const char *notes,
12288                         const char *stop_notes)
12289 {
12290   struct remote_state *rs = get_remote_state ();
12291   char *reply;
12292   char *buf = rs->buf;
12293   char *endbuf = rs->buf + get_remote_packet_size ();
12294   int nbytes;
12295
12296   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12297   if (user)
12298     {
12299       buf += xsnprintf (buf, endbuf - buf, "user:");
12300       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12301       buf += 2 * nbytes;
12302       *buf++ = ';';
12303     }
12304   if (notes)
12305     {
12306       buf += xsnprintf (buf, endbuf - buf, "notes:");
12307       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12308       buf += 2 * nbytes;
12309       *buf++ = ';';
12310     }
12311   if (stop_notes)
12312     {
12313       buf += xsnprintf (buf, endbuf - buf, "tstop:");
12314       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12315       buf += 2 * nbytes;
12316       *buf++ = ';';
12317     }
12318   /* Ensure the buffer is terminated.  */
12319   *buf = '\0';
12320
12321   putpkt (rs->buf);
12322   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12323   if (*reply == '\0')
12324     return 0;
12325
12326   if (strcmp (reply, "OK") != 0)
12327     error (_("Bogus reply from target: %s"), reply);
12328
12329   return 1;
12330 }
12331
12332 static int
12333 remote_use_agent (struct target_ops *self, int use)
12334 {
12335   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12336     {
12337       struct remote_state *rs = get_remote_state ();
12338
12339       /* If the stub supports QAgent.  */
12340       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12341       putpkt (rs->buf);
12342       getpkt (&rs->buf, &rs->buf_size, 0);
12343
12344       if (strcmp (rs->buf, "OK") == 0)
12345         {
12346           use_agent = use;
12347           return 1;
12348         }
12349     }
12350
12351   return 0;
12352 }
12353
12354 static int
12355 remote_can_use_agent (struct target_ops *self)
12356 {
12357   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12358 }
12359
12360 struct btrace_target_info
12361 {
12362   /* The ptid of the traced thread.  */
12363   ptid_t ptid;
12364
12365   /* The obtained branch trace configuration.  */
12366   struct btrace_config conf;
12367 };
12368
12369 /* Reset our idea of our target's btrace configuration.  */
12370
12371 static void
12372 remote_btrace_reset (void)
12373 {
12374   struct remote_state *rs = get_remote_state ();
12375
12376   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12377 }
12378
12379 /* Check whether the target supports branch tracing.  */
12380
12381 static int
12382 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12383 {
12384   if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12385     return 0;
12386   if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12387     return 0;
12388
12389   switch (format)
12390     {
12391       case BTRACE_FORMAT_NONE:
12392         return 0;
12393
12394       case BTRACE_FORMAT_BTS:
12395         return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12396
12397       case BTRACE_FORMAT_PT:
12398         /* The trace is decoded on the host.  Even if our target supports it,
12399            we still need to have libipt to decode the trace.  */
12400 #if defined (HAVE_LIBIPT)
12401         return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12402 #else /* !defined (HAVE_LIBIPT)  */
12403         return 0;
12404 #endif /* !defined (HAVE_LIBIPT)  */
12405     }
12406
12407   internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12408 }
12409
12410 /* Synchronize the configuration with the target.  */
12411
12412 static void
12413 btrace_sync_conf (const struct btrace_config *conf)
12414 {
12415   struct packet_config *packet;
12416   struct remote_state *rs;
12417   char *buf, *pos, *endbuf;
12418
12419   rs = get_remote_state ();
12420   buf = rs->buf;
12421   endbuf = buf + get_remote_packet_size ();
12422
12423   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12424   if (packet_config_support (packet) == PACKET_ENABLE
12425       && conf->bts.size != rs->btrace_config.bts.size)
12426     {
12427       pos = buf;
12428       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12429                         conf->bts.size);
12430
12431       putpkt (buf);
12432       getpkt (&buf, &rs->buf_size, 0);
12433
12434       if (packet_ok (buf, packet) == PACKET_ERROR)
12435         {
12436           if (buf[0] == 'E' && buf[1] == '.')
12437             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12438           else
12439             error (_("Failed to configure the BTS buffer size."));
12440         }
12441
12442       rs->btrace_config.bts.size = conf->bts.size;
12443     }
12444
12445   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12446   if (packet_config_support (packet) == PACKET_ENABLE
12447       && conf->pt.size != rs->btrace_config.pt.size)
12448     {
12449       pos = buf;
12450       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12451                         conf->pt.size);
12452
12453       putpkt (buf);
12454       getpkt (&buf, &rs->buf_size, 0);
12455
12456       if (packet_ok (buf, packet) == PACKET_ERROR)
12457         {
12458           if (buf[0] == 'E' && buf[1] == '.')
12459             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12460           else
12461             error (_("Failed to configure the trace buffer size."));
12462         }
12463
12464       rs->btrace_config.pt.size = conf->pt.size;
12465     }
12466 }
12467
12468 /* Read the current thread's btrace configuration from the target and
12469    store it into CONF.  */
12470
12471 static void
12472 btrace_read_config (struct btrace_config *conf)
12473 {
12474   char *xml;
12475
12476   xml = target_read_stralloc (&current_target,
12477                               TARGET_OBJECT_BTRACE_CONF, "");
12478   if (xml != NULL)
12479     {
12480       struct cleanup *cleanup;
12481
12482       cleanup = make_cleanup (xfree, xml);
12483       parse_xml_btrace_conf (conf, xml);
12484       do_cleanups (cleanup);
12485     }
12486 }
12487
12488 /* Enable branch tracing.  */
12489
12490 static struct btrace_target_info *
12491 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12492                       const struct btrace_config *conf)
12493 {
12494   struct btrace_target_info *tinfo = NULL;
12495   struct packet_config *packet = NULL;
12496   struct remote_state *rs = get_remote_state ();
12497   char *buf = rs->buf;
12498   char *endbuf = rs->buf + get_remote_packet_size ();
12499
12500   switch (conf->format)
12501     {
12502       case BTRACE_FORMAT_BTS:
12503         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12504         break;
12505
12506       case BTRACE_FORMAT_PT:
12507         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12508         break;
12509     }
12510
12511   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12512     error (_("Target does not support branch tracing."));
12513
12514   btrace_sync_conf (conf);
12515
12516   set_general_thread (ptid);
12517
12518   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12519   putpkt (rs->buf);
12520   getpkt (&rs->buf, &rs->buf_size, 0);
12521
12522   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12523     {
12524       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12525         error (_("Could not enable branch tracing for %s: %s"),
12526                target_pid_to_str (ptid), rs->buf + 2);
12527       else
12528         error (_("Could not enable branch tracing for %s."),
12529                target_pid_to_str (ptid));
12530     }
12531
12532   tinfo = XCNEW (struct btrace_target_info);
12533   tinfo->ptid = ptid;
12534
12535   /* If we fail to read the configuration, we lose some information, but the
12536      tracing itself is not impacted.  */
12537   TRY
12538     {
12539       btrace_read_config (&tinfo->conf);
12540     }
12541   CATCH (err, RETURN_MASK_ERROR)
12542     {
12543       if (err.message != NULL)
12544         warning ("%s", err.message);
12545     }
12546   END_CATCH
12547
12548   return tinfo;
12549 }
12550
12551 /* Disable branch tracing.  */
12552
12553 static void
12554 remote_disable_btrace (struct target_ops *self,
12555                        struct btrace_target_info *tinfo)
12556 {
12557   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12558   struct remote_state *rs = get_remote_state ();
12559   char *buf = rs->buf;
12560   char *endbuf = rs->buf + get_remote_packet_size ();
12561
12562   if (packet_config_support (packet) != PACKET_ENABLE)
12563     error (_("Target does not support branch tracing."));
12564
12565   set_general_thread (tinfo->ptid);
12566
12567   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12568   putpkt (rs->buf);
12569   getpkt (&rs->buf, &rs->buf_size, 0);
12570
12571   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12572     {
12573       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12574         error (_("Could not disable branch tracing for %s: %s"),
12575                target_pid_to_str (tinfo->ptid), rs->buf + 2);
12576       else
12577         error (_("Could not disable branch tracing for %s."),
12578                target_pid_to_str (tinfo->ptid));
12579     }
12580
12581   xfree (tinfo);
12582 }
12583
12584 /* Teardown branch tracing.  */
12585
12586 static void
12587 remote_teardown_btrace (struct target_ops *self,
12588                         struct btrace_target_info *tinfo)
12589 {
12590   /* We must not talk to the target during teardown.  */
12591   xfree (tinfo);
12592 }
12593
12594 /* Read the branch trace.  */
12595
12596 static enum btrace_error
12597 remote_read_btrace (struct target_ops *self,
12598                     struct btrace_data *btrace,
12599                     struct btrace_target_info *tinfo,
12600                     enum btrace_read_type type)
12601 {
12602   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12603   struct remote_state *rs = get_remote_state ();
12604   struct cleanup *cleanup;
12605   const char *annex;
12606   char *xml;
12607
12608   if (packet_config_support (packet) != PACKET_ENABLE)
12609     error (_("Target does not support branch tracing."));
12610
12611 #if !defined(HAVE_LIBEXPAT)
12612   error (_("Cannot process branch tracing result. XML parsing not supported."));
12613 #endif
12614
12615   switch (type)
12616     {
12617     case BTRACE_READ_ALL:
12618       annex = "all";
12619       break;
12620     case BTRACE_READ_NEW:
12621       annex = "new";
12622       break;
12623     case BTRACE_READ_DELTA:
12624       annex = "delta";
12625       break;
12626     default:
12627       internal_error (__FILE__, __LINE__,
12628                       _("Bad branch tracing read type: %u."),
12629                       (unsigned int) type);
12630     }
12631
12632   xml = target_read_stralloc (&current_target,
12633                               TARGET_OBJECT_BTRACE, annex);
12634   if (xml == NULL)
12635     return BTRACE_ERR_UNKNOWN;
12636
12637   cleanup = make_cleanup (xfree, xml);
12638   parse_xml_btrace (btrace, xml);
12639   do_cleanups (cleanup);
12640
12641   return BTRACE_ERR_NONE;
12642 }
12643
12644 static const struct btrace_config *
12645 remote_btrace_conf (struct target_ops *self,
12646                     const struct btrace_target_info *tinfo)
12647 {
12648   return &tinfo->conf;
12649 }
12650
12651 static int
12652 remote_augmented_libraries_svr4_read (struct target_ops *self)
12653 {
12654   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12655           == PACKET_ENABLE);
12656 }
12657
12658 /* Implementation of to_load.  */
12659
12660 static void
12661 remote_load (struct target_ops *self, const char *name, int from_tty)
12662 {
12663   generic_load (name, from_tty);
12664 }
12665
12666 /* Accepts an integer PID; returns a string representing a file that
12667    can be opened on the remote side to get the symbols for the child
12668    process.  Returns NULL if the operation is not supported.  */
12669
12670 static char *
12671 remote_pid_to_exec_file (struct target_ops *self, int pid)
12672 {
12673   static char *filename = NULL;
12674   struct inferior *inf;
12675   char *annex = NULL;
12676
12677   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12678     return NULL;
12679
12680   if (filename != NULL)
12681     xfree (filename);
12682
12683   inf = find_inferior_pid (pid);
12684   if (inf == NULL)
12685     internal_error (__FILE__, __LINE__,
12686                     _("not currently attached to process %d"), pid);
12687
12688   if (!inf->fake_pid_p)
12689     {
12690       const int annex_size = 9;
12691
12692       annex = (char *) alloca (annex_size);
12693       xsnprintf (annex, annex_size, "%x", pid);
12694     }
12695
12696   filename = target_read_stralloc (&current_target,
12697                                    TARGET_OBJECT_EXEC_FILE, annex);
12698
12699   return filename;
12700 }
12701
12702 /* Implement the to_can_do_single_step target_ops method.  */
12703
12704 static int
12705 remote_can_do_single_step (struct target_ops *ops)
12706 {
12707   /* We can only tell whether target supports single step or not by
12708      supported s and S vCont actions if the stub supports vContSupported
12709      feature.  If the stub doesn't support vContSupported feature,
12710      we have conservatively to think target doesn't supports single
12711      step.  */
12712   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12713     {
12714       struct remote_state *rs = get_remote_state ();
12715
12716       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12717         remote_vcont_probe (rs);
12718
12719       return rs->supports_vCont.s && rs->supports_vCont.S;
12720     }
12721   else
12722     return 0;
12723 }
12724
12725 static void
12726 init_remote_ops (void)
12727 {
12728   remote_ops.to_shortname = "remote";
12729   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12730   remote_ops.to_doc =
12731     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12732 Specify the serial device it is connected to\n\
12733 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12734   remote_ops.to_open = remote_open;
12735   remote_ops.to_close = remote_close;
12736   remote_ops.to_detach = remote_detach;
12737   remote_ops.to_disconnect = remote_disconnect;
12738   remote_ops.to_resume = remote_resume;
12739   remote_ops.to_wait = remote_wait;
12740   remote_ops.to_fetch_registers = remote_fetch_registers;
12741   remote_ops.to_store_registers = remote_store_registers;
12742   remote_ops.to_prepare_to_store = remote_prepare_to_store;
12743   remote_ops.to_files_info = remote_files_info;
12744   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12745   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12746   remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12747   remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12748   remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12749   remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12750   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12751   remote_ops.to_stopped_data_address = remote_stopped_data_address;
12752   remote_ops.to_watchpoint_addr_within_range =
12753     remote_watchpoint_addr_within_range;
12754   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12755   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12756   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12757   remote_ops.to_region_ok_for_hw_watchpoint
12758      = remote_region_ok_for_hw_watchpoint;
12759   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12760   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12761   remote_ops.to_kill = remote_kill;
12762   remote_ops.to_load = remote_load;
12763   remote_ops.to_mourn_inferior = remote_mourn;
12764   remote_ops.to_pass_signals = remote_pass_signals;
12765   remote_ops.to_program_signals = remote_program_signals;
12766   remote_ops.to_thread_alive = remote_thread_alive;
12767   remote_ops.to_thread_name = remote_thread_name;
12768   remote_ops.to_update_thread_list = remote_update_thread_list;
12769   remote_ops.to_pid_to_str = remote_pid_to_str;
12770   remote_ops.to_extra_thread_info = remote_threads_extra_info;
12771   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12772   remote_ops.to_stop = remote_stop;
12773   remote_ops.to_interrupt = remote_interrupt;
12774   remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12775   remote_ops.to_xfer_partial = remote_xfer_partial;
12776   remote_ops.to_rcmd = remote_rcmd;
12777   remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12778   remote_ops.to_log_command = serial_log_command;
12779   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12780   remote_ops.to_stratum = process_stratum;
12781   remote_ops.to_has_all_memory = default_child_has_all_memory;
12782   remote_ops.to_has_memory = default_child_has_memory;
12783   remote_ops.to_has_stack = default_child_has_stack;
12784   remote_ops.to_has_registers = default_child_has_registers;
12785   remote_ops.to_has_execution = default_child_has_execution;
12786   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
12787   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12788   remote_ops.to_magic = OPS_MAGIC;
12789   remote_ops.to_memory_map = remote_memory_map;
12790   remote_ops.to_flash_erase = remote_flash_erase;
12791   remote_ops.to_flash_done = remote_flash_done;
12792   remote_ops.to_read_description = remote_read_description;
12793   remote_ops.to_search_memory = remote_search_memory;
12794   remote_ops.to_can_async_p = remote_can_async_p;
12795   remote_ops.to_is_async_p = remote_is_async_p;
12796   remote_ops.to_async = remote_async;
12797   remote_ops.to_can_do_single_step = remote_can_do_single_step;
12798   remote_ops.to_terminal_inferior = remote_terminal_inferior;
12799   remote_ops.to_terminal_ours = remote_terminal_ours;
12800   remote_ops.to_supports_non_stop = remote_supports_non_stop;
12801   remote_ops.to_supports_multi_process = remote_supports_multi_process;
12802   remote_ops.to_supports_disable_randomization
12803     = remote_supports_disable_randomization;
12804   remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
12805   remote_ops.to_fileio_open = remote_hostio_open;
12806   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12807   remote_ops.to_fileio_pread = remote_hostio_pread;
12808   remote_ops.to_fileio_fstat = remote_hostio_fstat;
12809   remote_ops.to_fileio_close = remote_hostio_close;
12810   remote_ops.to_fileio_unlink = remote_hostio_unlink;
12811   remote_ops.to_fileio_readlink = remote_hostio_readlink;
12812   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12813   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
12814   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12815   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
12816   remote_ops.to_trace_init = remote_trace_init;
12817   remote_ops.to_download_tracepoint = remote_download_tracepoint;
12818   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
12819   remote_ops.to_download_trace_state_variable
12820     = remote_download_trace_state_variable;
12821   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12822   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
12823   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12824   remote_ops.to_trace_start = remote_trace_start;
12825   remote_ops.to_get_trace_status = remote_get_trace_status;
12826   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
12827   remote_ops.to_trace_stop = remote_trace_stop;
12828   remote_ops.to_trace_find = remote_trace_find;
12829   remote_ops.to_get_trace_state_variable_value
12830     = remote_get_trace_state_variable_value;
12831   remote_ops.to_save_trace_data = remote_save_trace_data;
12832   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
12833   remote_ops.to_upload_trace_state_variables
12834     = remote_upload_trace_state_variables;
12835   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
12836   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
12837   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
12838   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
12839   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
12840   remote_ops.to_set_trace_notes = remote_set_trace_notes;
12841   remote_ops.to_core_of_thread = remote_core_of_thread;
12842   remote_ops.to_verify_memory = remote_verify_memory;
12843   remote_ops.to_get_tib_address = remote_get_tib_address;
12844   remote_ops.to_set_permissions = remote_set_permissions;
12845   remote_ops.to_static_tracepoint_marker_at
12846     = remote_static_tracepoint_marker_at;
12847   remote_ops.to_static_tracepoint_markers_by_strid
12848     = remote_static_tracepoint_markers_by_strid;
12849   remote_ops.to_traceframe_info = remote_traceframe_info;
12850   remote_ops.to_use_agent = remote_use_agent;
12851   remote_ops.to_can_use_agent = remote_can_use_agent;
12852   remote_ops.to_supports_btrace = remote_supports_btrace;
12853   remote_ops.to_enable_btrace = remote_enable_btrace;
12854   remote_ops.to_disable_btrace = remote_disable_btrace;
12855   remote_ops.to_teardown_btrace = remote_teardown_btrace;
12856   remote_ops.to_read_btrace = remote_read_btrace;
12857   remote_ops.to_btrace_conf = remote_btrace_conf;
12858   remote_ops.to_augmented_libraries_svr4_read =
12859     remote_augmented_libraries_svr4_read;
12860 }
12861
12862 /* Set up the extended remote vector by making a copy of the standard
12863    remote vector and adding to it.  */
12864
12865 static void
12866 init_extended_remote_ops (void)
12867 {
12868   extended_remote_ops = remote_ops;
12869
12870   extended_remote_ops.to_shortname = "extended-remote";
12871   extended_remote_ops.to_longname =
12872     "Extended remote serial target in gdb-specific protocol";
12873   extended_remote_ops.to_doc =
12874     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12875 Specify the serial device it is connected to (e.g. /dev/ttya).";
12876   extended_remote_ops.to_open = extended_remote_open;
12877   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12878   extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
12879   extended_remote_ops.to_detach = extended_remote_detach;
12880   extended_remote_ops.to_attach = extended_remote_attach;
12881   extended_remote_ops.to_post_attach = extended_remote_post_attach;
12882   extended_remote_ops.to_kill = extended_remote_kill;
12883   extended_remote_ops.to_supports_disable_randomization
12884     = extended_remote_supports_disable_randomization;
12885   extended_remote_ops.to_follow_fork = remote_follow_fork;
12886   extended_remote_ops.to_follow_exec = remote_follow_exec;
12887   extended_remote_ops.to_insert_fork_catchpoint
12888     = remote_insert_fork_catchpoint;
12889   extended_remote_ops.to_remove_fork_catchpoint
12890     = remote_remove_fork_catchpoint;
12891   extended_remote_ops.to_insert_vfork_catchpoint
12892     = remote_insert_vfork_catchpoint;
12893   extended_remote_ops.to_remove_vfork_catchpoint
12894     = remote_remove_vfork_catchpoint;
12895   extended_remote_ops.to_insert_exec_catchpoint
12896     = remote_insert_exec_catchpoint;
12897   extended_remote_ops.to_remove_exec_catchpoint
12898     = remote_remove_exec_catchpoint;
12899 }
12900
12901 static int
12902 remote_can_async_p (struct target_ops *ops)
12903 {
12904   struct remote_state *rs = get_remote_state ();
12905
12906   if (!target_async_permitted)
12907     /* We only enable async when the user specifically asks for it.  */
12908     return 0;
12909
12910   /* We're async whenever the serial device is.  */
12911   return serial_can_async_p (rs->remote_desc);
12912 }
12913
12914 static int
12915 remote_is_async_p (struct target_ops *ops)
12916 {
12917   struct remote_state *rs = get_remote_state ();
12918
12919   if (!target_async_permitted)
12920     /* We only enable async when the user specifically asks for it.  */
12921     return 0;
12922
12923   /* We're async whenever the serial device is.  */
12924   return serial_is_async_p (rs->remote_desc);
12925 }
12926
12927 /* Pass the SERIAL event on and up to the client.  One day this code
12928    will be able to delay notifying the client of an event until the
12929    point where an entire packet has been received.  */
12930
12931 static serial_event_ftype remote_async_serial_handler;
12932
12933 static void
12934 remote_async_serial_handler (struct serial *scb, void *context)
12935 {
12936   struct remote_state *rs = (struct remote_state *) context;
12937
12938   /* Don't propogate error information up to the client.  Instead let
12939      the client find out about the error by querying the target.  */
12940   inferior_event_handler (INF_REG_EVENT, NULL);
12941 }
12942
12943 static void
12944 remote_async_inferior_event_handler (gdb_client_data data)
12945 {
12946   inferior_event_handler (INF_REG_EVENT, NULL);
12947 }
12948
12949 static void
12950 remote_async (struct target_ops *ops, int enable)
12951 {
12952   struct remote_state *rs = get_remote_state ();
12953
12954   if (enable)
12955     {
12956       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
12957
12958       /* If there are pending events in the stop reply queue tell the
12959          event loop to process them.  */
12960       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12961         mark_async_event_handler (remote_async_inferior_event_token);
12962     }
12963   else
12964     {
12965       serial_async (rs->remote_desc, NULL, NULL);
12966       clear_async_event_handler (remote_async_inferior_event_token);
12967     }
12968 }
12969
12970 static void
12971 set_remote_cmd (char *args, int from_tty)
12972 {
12973   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
12974 }
12975
12976 static void
12977 show_remote_cmd (char *args, int from_tty)
12978 {
12979   /* We can't just use cmd_show_list here, because we want to skip
12980      the redundant "show remote Z-packet" and the legacy aliases.  */
12981   struct cleanup *showlist_chain;
12982   struct cmd_list_element *list = remote_show_cmdlist;
12983   struct ui_out *uiout = current_uiout;
12984
12985   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12986   for (; list != NULL; list = list->next)
12987     if (strcmp (list->name, "Z-packet") == 0)
12988       continue;
12989     else if (list->type == not_set_cmd)
12990       /* Alias commands are exactly like the original, except they
12991          don't have the normal type.  */
12992       continue;
12993     else
12994       {
12995         struct cleanup *option_chain
12996           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
12997
12998         ui_out_field_string (uiout, "name", list->name);
12999         ui_out_text (uiout, ":  ");
13000         if (list->type == show_cmd)
13001           do_show_command ((char *) NULL, from_tty, list);
13002         else
13003           cmd_func (list, NULL, from_tty);
13004         /* Close the tuple.  */
13005         do_cleanups (option_chain);
13006       }
13007
13008   /* Close the tuple.  */
13009   do_cleanups (showlist_chain);
13010 }
13011
13012
13013 /* Function to be called whenever a new objfile (shlib) is detected.  */
13014 static void
13015 remote_new_objfile (struct objfile *objfile)
13016 {
13017   struct remote_state *rs = get_remote_state ();
13018
13019   if (rs->remote_desc != 0)             /* Have a remote connection.  */
13020     remote_check_symbols ();
13021 }
13022
13023 /* Pull all the tracepoints defined on the target and create local
13024    data structures representing them.  We don't want to create real
13025    tracepoints yet, we don't want to mess up the user's existing
13026    collection.  */
13027   
13028 static int
13029 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13030 {
13031   struct remote_state *rs = get_remote_state ();
13032   char *p;
13033
13034   /* Ask for a first packet of tracepoint definition.  */
13035   putpkt ("qTfP");
13036   getpkt (&rs->buf, &rs->buf_size, 0);
13037   p = rs->buf;
13038   while (*p && *p != 'l')
13039     {
13040       parse_tracepoint_definition (p, utpp);
13041       /* Ask for another packet of tracepoint definition.  */
13042       putpkt ("qTsP");
13043       getpkt (&rs->buf, &rs->buf_size, 0);
13044       p = rs->buf;
13045     }
13046   return 0;
13047 }
13048
13049 static int
13050 remote_upload_trace_state_variables (struct target_ops *self,
13051                                      struct uploaded_tsv **utsvp)
13052 {
13053   struct remote_state *rs = get_remote_state ();
13054   char *p;
13055
13056   /* Ask for a first packet of variable definition.  */
13057   putpkt ("qTfV");
13058   getpkt (&rs->buf, &rs->buf_size, 0);
13059   p = rs->buf;
13060   while (*p && *p != 'l')
13061     {
13062       parse_tsv_definition (p, utsvp);
13063       /* Ask for another packet of variable definition.  */
13064       putpkt ("qTsV");
13065       getpkt (&rs->buf, &rs->buf_size, 0);
13066       p = rs->buf;
13067     }
13068   return 0;
13069 }
13070
13071 /* The "set/show range-stepping" show hook.  */
13072
13073 static void
13074 show_range_stepping (struct ui_file *file, int from_tty,
13075                      struct cmd_list_element *c,
13076                      const char *value)
13077 {
13078   fprintf_filtered (file,
13079                     _("Debugger's willingness to use range stepping "
13080                       "is %s.\n"), value);
13081 }
13082
13083 /* The "set/show range-stepping" set hook.  */
13084
13085 static void
13086 set_range_stepping (char *ignore_args, int from_tty,
13087                     struct cmd_list_element *c)
13088 {
13089   struct remote_state *rs = get_remote_state ();
13090
13091   /* Whene enabling, check whether range stepping is actually
13092      supported by the target, and warn if not.  */
13093   if (use_range_stepping)
13094     {
13095       if (rs->remote_desc != NULL)
13096         {
13097           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13098             remote_vcont_probe (rs);
13099
13100           if (packet_support (PACKET_vCont) == PACKET_ENABLE
13101               && rs->supports_vCont.r)
13102             return;
13103         }
13104
13105       warning (_("Range stepping is not supported by the current target"));
13106     }
13107 }
13108
13109 void
13110 _initialize_remote (void)
13111 {
13112   struct remote_state *rs;
13113   struct cmd_list_element *cmd;
13114   const char *cmd_name;
13115
13116   /* architecture specific data */
13117   remote_gdbarch_data_handle =
13118     gdbarch_data_register_post_init (init_remote_state);
13119   remote_g_packet_data_handle =
13120     gdbarch_data_register_pre_init (remote_g_packet_data_init);
13121
13122   remote_pspace_data
13123     = register_program_space_data_with_cleanup (NULL,
13124                                                 remote_pspace_data_cleanup);
13125
13126   /* Initialize the per-target state.  At the moment there is only one
13127      of these, not one per target.  Only one target is active at a
13128      time.  */
13129   remote_state = new_remote_state ();
13130
13131   init_remote_ops ();
13132   add_target (&remote_ops);
13133
13134   init_extended_remote_ops ();
13135   add_target (&extended_remote_ops);
13136
13137   /* Hook into new objfile notification.  */
13138   observer_attach_new_objfile (remote_new_objfile);
13139   /* We're no longer interested in notification events of an inferior
13140      when it exits.  */
13141   observer_attach_inferior_exit (discard_pending_stop_replies);
13142
13143   /* Set up signal handlers.  */
13144   async_sigint_remote_token =
13145     create_async_signal_handler (async_remote_interrupt, NULL);
13146   async_sigint_remote_twice_token =
13147     create_async_signal_handler (async_remote_interrupt_twice, NULL);
13148
13149 #if 0
13150   init_remote_threadtests ();
13151 #endif
13152
13153   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13154   /* set/show remote ...  */
13155
13156   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13157 Remote protocol specific variables\n\
13158 Configure various remote-protocol specific variables such as\n\
13159 the packets being used"),
13160                   &remote_set_cmdlist, "set remote ",
13161                   0 /* allow-unknown */, &setlist);
13162   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13163 Remote protocol specific variables\n\
13164 Configure various remote-protocol specific variables such as\n\
13165 the packets being used"),
13166                   &remote_show_cmdlist, "show remote ",
13167                   0 /* allow-unknown */, &showlist);
13168
13169   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13170 Compare section data on target to the exec file.\n\
13171 Argument is a single section name (default: all loaded sections).\n\
13172 To compare only read-only loaded sections, specify the -r option."),
13173            &cmdlist);
13174
13175   add_cmd ("packet", class_maintenance, packet_command, _("\
13176 Send an arbitrary packet to a remote target.\n\
13177    maintenance packet TEXT\n\
13178 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13179 this command sends the string TEXT to the inferior, and displays the\n\
13180 response packet.  GDB supplies the initial `$' character, and the\n\
13181 terminating `#' character and checksum."),
13182            &maintenancelist);
13183
13184   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13185 Set whether to send break if interrupted."), _("\
13186 Show whether to send break if interrupted."), _("\
13187 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13188                            set_remotebreak, show_remotebreak,
13189                            &setlist, &showlist);
13190   cmd_name = "remotebreak";
13191   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13192   deprecate_cmd (cmd, "set remote interrupt-sequence");
13193   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13194   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13195   deprecate_cmd (cmd, "show remote interrupt-sequence");
13196
13197   add_setshow_enum_cmd ("interrupt-sequence", class_support,
13198                         interrupt_sequence_modes, &interrupt_sequence_mode,
13199                         _("\
13200 Set interrupt sequence to remote target."), _("\
13201 Show interrupt sequence to remote target."), _("\
13202 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13203                         NULL, show_interrupt_sequence,
13204                         &remote_set_cmdlist,
13205                         &remote_show_cmdlist);
13206
13207   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13208                            &interrupt_on_connect, _("\
13209 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
13210 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
13211 If set, interrupt sequence is sent to remote target."),
13212                            NULL, NULL,
13213                            &remote_set_cmdlist, &remote_show_cmdlist);
13214
13215   /* Install commands for configuring memory read/write packets.  */
13216
13217   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13218 Set the maximum number of bytes per memory write packet (deprecated)."),
13219            &setlist);
13220   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13221 Show the maximum number of bytes per memory write packet (deprecated)."),
13222            &showlist);
13223   add_cmd ("memory-write-packet-size", no_class,
13224            set_memory_write_packet_size, _("\
13225 Set the maximum number of bytes per memory-write packet.\n\
13226 Specify the number of bytes in a packet or 0 (zero) for the\n\
13227 default packet size.  The actual limit is further reduced\n\
13228 dependent on the target.  Specify ``fixed'' to disable the\n\
13229 further restriction and ``limit'' to enable that restriction."),
13230            &remote_set_cmdlist);
13231   add_cmd ("memory-read-packet-size", no_class,
13232            set_memory_read_packet_size, _("\
13233 Set the maximum number of bytes per memory-read packet.\n\
13234 Specify the number of bytes in a packet or 0 (zero) for the\n\
13235 default packet size.  The actual limit is further reduced\n\
13236 dependent on the target.  Specify ``fixed'' to disable the\n\
13237 further restriction and ``limit'' to enable that restriction."),
13238            &remote_set_cmdlist);
13239   add_cmd ("memory-write-packet-size", no_class,
13240            show_memory_write_packet_size,
13241            _("Show the maximum number of bytes per memory-write packet."),
13242            &remote_show_cmdlist);
13243   add_cmd ("memory-read-packet-size", no_class,
13244            show_memory_read_packet_size,
13245            _("Show the maximum number of bytes per memory-read packet."),
13246            &remote_show_cmdlist);
13247
13248   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13249                             &remote_hw_watchpoint_limit, _("\
13250 Set the maximum number of target hardware watchpoints."), _("\
13251 Show the maximum number of target hardware watchpoints."), _("\
13252 Specify a negative limit for unlimited."),
13253                             NULL, NULL, /* FIXME: i18n: The maximum
13254                                            number of target hardware
13255                                            watchpoints is %s.  */
13256                             &remote_set_cmdlist, &remote_show_cmdlist);
13257   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13258                             &remote_hw_watchpoint_length_limit, _("\
13259 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13260 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13261 Specify a negative limit for unlimited."),
13262                             NULL, NULL, /* FIXME: i18n: The maximum
13263                                            length (in bytes) of a target
13264                                            hardware watchpoint is %s.  */
13265                             &remote_set_cmdlist, &remote_show_cmdlist);
13266   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13267                             &remote_hw_breakpoint_limit, _("\
13268 Set the maximum number of target hardware breakpoints."), _("\
13269 Show the maximum number of target hardware breakpoints."), _("\
13270 Specify a negative limit for unlimited."),
13271                             NULL, NULL, /* FIXME: i18n: The maximum
13272                                            number of target hardware
13273                                            breakpoints is %s.  */
13274                             &remote_set_cmdlist, &remote_show_cmdlist);
13275
13276   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13277                              &remote_address_size, _("\
13278 Set the maximum size of the address (in bits) in a memory packet."), _("\
13279 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13280                              NULL,
13281                              NULL, /* FIXME: i18n: */
13282                              &setlist, &showlist);
13283
13284   init_all_packet_configs ();
13285
13286   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13287                          "X", "binary-download", 1);
13288
13289   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13290                          "vCont", "verbose-resume", 0);
13291
13292   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13293                          "QPassSignals", "pass-signals", 0);
13294
13295   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13296                          "QProgramSignals", "program-signals", 0);
13297
13298   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13299                          "qSymbol", "symbol-lookup", 0);
13300
13301   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13302                          "P", "set-register", 1);
13303
13304   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13305                          "p", "fetch-register", 1);
13306
13307   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13308                          "Z0", "software-breakpoint", 0);
13309
13310   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13311                          "Z1", "hardware-breakpoint", 0);
13312
13313   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13314                          "Z2", "write-watchpoint", 0);
13315
13316   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13317                          "Z3", "read-watchpoint", 0);
13318
13319   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13320                          "Z4", "access-watchpoint", 0);
13321
13322   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13323                          "qXfer:auxv:read", "read-aux-vector", 0);
13324
13325   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13326                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
13327
13328   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13329                          "qXfer:features:read", "target-features", 0);
13330
13331   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13332                          "qXfer:libraries:read", "library-info", 0);
13333
13334   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13335                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13336
13337   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13338                          "qXfer:memory-map:read", "memory-map", 0);
13339
13340   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13341                          "qXfer:spu:read", "read-spu-object", 0);
13342
13343   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13344                          "qXfer:spu:write", "write-spu-object", 0);
13345
13346   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13347                         "qXfer:osdata:read", "osdata", 0);
13348
13349   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13350                          "qXfer:threads:read", "threads", 0);
13351
13352   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13353                          "qXfer:siginfo:read", "read-siginfo-object", 0);
13354
13355   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13356                          "qXfer:siginfo:write", "write-siginfo-object", 0);
13357
13358   add_packet_config_cmd
13359     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13360      "qXfer:traceframe-info:read", "traceframe-info", 0);
13361
13362   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13363                          "qXfer:uib:read", "unwind-info-block", 0);
13364
13365   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13366                          "qGetTLSAddr", "get-thread-local-storage-address",
13367                          0);
13368
13369   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13370                          "qGetTIBAddr", "get-thread-information-block-address",
13371                          0);
13372
13373   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13374                          "bc", "reverse-continue", 0);
13375
13376   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13377                          "bs", "reverse-step", 0);
13378
13379   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13380                          "qSupported", "supported-packets", 0);
13381
13382   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13383                          "qSearch:memory", "search-memory", 0);
13384
13385   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13386                          "qTStatus", "trace-status", 0);
13387
13388   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13389                          "vFile:setfs", "hostio-setfs", 0);
13390
13391   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13392                          "vFile:open", "hostio-open", 0);
13393
13394   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13395                          "vFile:pread", "hostio-pread", 0);
13396
13397   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13398                          "vFile:pwrite", "hostio-pwrite", 0);
13399
13400   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13401                          "vFile:close", "hostio-close", 0);
13402
13403   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13404                          "vFile:unlink", "hostio-unlink", 0);
13405
13406   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13407                          "vFile:readlink", "hostio-readlink", 0);
13408
13409   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13410                          "vFile:fstat", "hostio-fstat", 0);
13411
13412   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13413                          "vAttach", "attach", 0);
13414
13415   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13416                          "vRun", "run", 0);
13417
13418   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13419                          "QStartNoAckMode", "noack", 0);
13420
13421   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13422                          "vKill", "kill", 0);
13423
13424   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13425                          "qAttached", "query-attached", 0);
13426
13427   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13428                          "ConditionalTracepoints",
13429                          "conditional-tracepoints", 0);
13430
13431   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13432                          "ConditionalBreakpoints",
13433                          "conditional-breakpoints", 0);
13434
13435   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13436                          "BreakpointCommands",
13437                          "breakpoint-commands", 0);
13438
13439   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13440                          "FastTracepoints", "fast-tracepoints", 0);
13441
13442   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13443                          "TracepointSource", "TracepointSource", 0);
13444
13445   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13446                          "QAllow", "allow", 0);
13447
13448   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13449                          "StaticTracepoints", "static-tracepoints", 0);
13450
13451   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13452                          "InstallInTrace", "install-in-trace", 0);
13453
13454   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13455                          "qXfer:statictrace:read", "read-sdata-object", 0);
13456
13457   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13458                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13459
13460   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13461                          "QDisableRandomization", "disable-randomization", 0);
13462
13463   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13464                          "QAgent", "agent", 0);
13465
13466   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13467                          "QTBuffer:size", "trace-buffer-size", 0);
13468
13469   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13470        "Qbtrace:off", "disable-btrace", 0);
13471
13472   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13473        "Qbtrace:bts", "enable-btrace-bts", 0);
13474
13475   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13476        "Qbtrace:pt", "enable-btrace-pt", 0);
13477
13478   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13479        "qXfer:btrace", "read-btrace", 0);
13480
13481   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13482        "qXfer:btrace-conf", "read-btrace-conf", 0);
13483
13484   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13485        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13486
13487   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13488        "multiprocess-feature", "multiprocess-feature", 0);
13489
13490   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13491                          "swbreak-feature", "swbreak-feature", 0);
13492
13493   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13494                          "hwbreak-feature", "hwbreak-feature", 0);
13495
13496   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13497                          "fork-event-feature", "fork-event-feature", 0);
13498
13499   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13500                          "vfork-event-feature", "vfork-event-feature", 0);
13501
13502   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13503        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13504
13505   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13506                          "vContSupported", "verbose-resume-supported", 0);
13507
13508   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13509                          "exec-event-feature", "exec-event-feature", 0);
13510
13511   /* Assert that we've registered "set remote foo-packet" commands
13512      for all packet configs.  */
13513   {
13514     int i;
13515
13516     for (i = 0; i < PACKET_MAX; i++)
13517       {
13518         /* Ideally all configs would have a command associated.  Some
13519            still don't though.  */
13520         int excepted;
13521
13522         switch (i)
13523           {
13524           case PACKET_QNonStop:
13525           case PACKET_EnableDisableTracepoints_feature:
13526           case PACKET_tracenz_feature:
13527           case PACKET_DisconnectedTracing_feature:
13528           case PACKET_augmented_libraries_svr4_read_feature:
13529           case PACKET_qCRC:
13530             /* Additions to this list need to be well justified:
13531                pre-existing packets are OK; new packets are not.  */
13532             excepted = 1;
13533             break;
13534           default:
13535             excepted = 0;
13536             break;
13537           }
13538
13539         /* This catches both forgetting to add a config command, and
13540            forgetting to remove a packet from the exception list.  */
13541         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13542       }
13543   }
13544
13545   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
13546      Z sub-packet has its own set and show commands, but users may
13547      have sets to this variable in their .gdbinit files (or in their
13548      documentation).  */
13549   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13550                                 &remote_Z_packet_detect, _("\
13551 Set use of remote protocol `Z' packets"), _("\
13552 Show use of remote protocol `Z' packets "), _("\
13553 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13554 packets."),
13555                                 set_remote_protocol_Z_packet_cmd,
13556                                 show_remote_protocol_Z_packet_cmd,
13557                                 /* FIXME: i18n: Use of remote protocol
13558                                    `Z' packets is %s.  */
13559                                 &remote_set_cmdlist, &remote_show_cmdlist);
13560
13561   add_prefix_cmd ("remote", class_files, remote_command, _("\
13562 Manipulate files on the remote system\n\
13563 Transfer files to and from the remote target system."),
13564                   &remote_cmdlist, "remote ",
13565                   0 /* allow-unknown */, &cmdlist);
13566
13567   add_cmd ("put", class_files, remote_put_command,
13568            _("Copy a local file to the remote system."),
13569            &remote_cmdlist);
13570
13571   add_cmd ("get", class_files, remote_get_command,
13572            _("Copy a remote file to the local system."),
13573            &remote_cmdlist);
13574
13575   add_cmd ("delete", class_files, remote_delete_command,
13576            _("Delete a remote file."),
13577            &remote_cmdlist);
13578
13579   add_setshow_string_noescape_cmd ("exec-file", class_files,
13580                                    &remote_exec_file_var, _("\
13581 Set the remote pathname for \"run\""), _("\
13582 Show the remote pathname for \"run\""), NULL,
13583                                    set_remote_exec_file,
13584                                    show_remote_exec_file,
13585                                    &remote_set_cmdlist,
13586                                    &remote_show_cmdlist);
13587
13588   add_setshow_boolean_cmd ("range-stepping", class_run,
13589                            &use_range_stepping, _("\
13590 Enable or disable range stepping."), _("\
13591 Show whether target-assisted range stepping is enabled."), _("\
13592 If on, and the target supports it, when stepping a source line, GDB\n\
13593 tells the target to step the corresponding range of addresses itself instead\n\
13594 of issuing multiple single-steps.  This speeds up source level\n\
13595 stepping.  If off, GDB always issues single-steps, even if range\n\
13596 stepping is supported by the target.  The default is on."),
13597                            set_range_stepping,
13598                            show_range_stepping,
13599                            &setlist,
13600                            &showlist);
13601
13602   /* Eventually initialize fileio.  See fileio.c */
13603   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13604
13605   /* Take advantage of the fact that the TID field is not used, to tag
13606      special ptids with it set to != 0.  */
13607   magic_null_ptid = ptid_build (42000, -1, 1);
13608   not_sent_ptid = ptid_build (42000, -2, 1);
13609   any_thread_ptid = ptid_build (42000, 0, 1);
13610
13611   target_buf_size = 2048;
13612   target_buf = (char *) xmalloc (target_buf_size);
13613 }
13614