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