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