Implement 'catch syscall' for gdbserver
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2016 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* See the GDB User Guide for details of the GDB remote protocol.  */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 /*#include "terminal.h" */
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observer.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "filestuff.h"
46 #include "rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdb_sys_time.h"
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "agent.h"
72 #include "btrace.h"
73
74 /* Temp hacks for tracepoint encoding migration.  */
75 static char *target_buf;
76 static long target_buf_size;
77
78 /* Per-program-space data key.  */
79 static const struct program_space_data *remote_pspace_data;
80
81 /* The variable registered as the control variable used by the
82    remote exec-file commands.  While the remote exec-file setting is
83    per-program-space, the set/show machinery uses this as the 
84    location of the remote exec-file value.  */
85 static char *remote_exec_file_var;
86
87 /* The size to align memory write packets, when practical.  The protocol
88    does not guarantee any alignment, and gdb will generate short
89    writes and unaligned writes, but even as a best-effort attempt this
90    can improve bulk transfers.  For instance, if a write is misaligned
91    relative to the target's data bus, the stub may need to make an extra
92    round trip fetching data from the target.  This doesn't make a
93    huge difference, but it's easy to do, so we try to be helpful.
94
95    The alignment chosen is arbitrary; usually data bus width is
96    important here, not the possibly larger cache line size.  */
97 enum { REMOTE_ALIGN_WRITES = 16 };
98
99 /* Prototypes for local functions.  */
100 static void async_cleanup_sigint_signal_handler (void *dummy);
101 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
102 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
103                                  int forever, int *is_notif);
104
105 static void async_handle_remote_sigint (int);
106 static void async_handle_remote_sigint_twice (int);
107
108 static void remote_files_info (struct target_ops *ignore);
109
110 static void remote_prepare_to_store (struct target_ops *self,
111                                      struct regcache *regcache);
112
113 static void remote_open_1 (const char *, int, struct target_ops *,
114                            int extended_p);
115
116 static void remote_close (struct target_ops *self);
117
118 struct remote_state;
119
120 static int remote_vkill (int pid, struct remote_state *rs);
121
122 static void remote_kill_k (void);
123
124 static void remote_mourn (struct target_ops *ops);
125
126 static void extended_remote_restart (void);
127
128 static void remote_send (char **buf, long *sizeof_buf_p);
129
130 static int readchar (int timeout);
131
132 static void remote_serial_write (const char *str, int len);
133
134 static void remote_kill (struct target_ops *ops);
135
136 static int remote_can_async_p (struct target_ops *);
137
138 static int remote_is_async_p (struct target_ops *);
139
140 static void remote_async (struct target_ops *ops, int enable);
141
142 static void remote_thread_events (struct target_ops *ops, int enable);
143
144 static void sync_remote_interrupt_twice (int signo);
145
146 static void interrupt_query (void);
147
148 static void set_general_thread (struct ptid ptid);
149 static void set_continue_thread (struct ptid ptid);
150
151 static void get_offsets (void);
152
153 static void skip_frame (void);
154
155 static long read_frame (char **buf_p, long *sizeof_buf);
156
157 static int hexnumlen (ULONGEST num);
158
159 static void init_remote_ops (void);
160
161 static void init_extended_remote_ops (void);
162
163 static void remote_stop (struct target_ops *self, ptid_t);
164
165 static int stubhex (int ch);
166
167 static int hexnumstr (char *, ULONGEST);
168
169 static int hexnumnstr (char *, ULONGEST, int);
170
171 static CORE_ADDR remote_address_masked (CORE_ADDR);
172
173 static void print_packet (const char *);
174
175 static void compare_sections_command (char *, int);
176
177 static void packet_command (char *, int);
178
179 static int stub_unpack_int (char *buff, int fieldlength);
180
181 static ptid_t remote_current_thread (ptid_t oldptid);
182
183 static int putpkt_binary (const char *buf, int cnt);
184
185 static void check_binary_download (CORE_ADDR addr);
186
187 struct packet_config;
188
189 static void show_packet_config_cmd (struct packet_config *config);
190
191 static void show_remote_protocol_packet_cmd (struct ui_file *file,
192                                              int from_tty,
193                                              struct cmd_list_element *c,
194                                              const char *value);
195
196 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
197 static ptid_t read_ptid (char *buf, char **obuf);
198
199 static void remote_set_permissions (struct target_ops *self);
200
201 static int remote_get_trace_status (struct target_ops *self,
202                                     struct trace_status *ts);
203
204 static int remote_upload_tracepoints (struct target_ops *self,
205                                       struct uploaded_tp **utpp);
206
207 static int remote_upload_trace_state_variables (struct target_ops *self,
208                                                 struct uploaded_tsv **utsvp);
209   
210 static void remote_query_supported (void);
211
212 static void remote_check_symbols (void);
213
214 void _initialize_remote (void);
215
216 struct stop_reply;
217 static void stop_reply_xfree (struct stop_reply *);
218 static void remote_parse_stop_reply (char *, struct stop_reply *);
219 static void push_stop_reply (struct stop_reply *);
220 static void discard_pending_stop_replies_in_queue (struct remote_state *);
221 static int peek_stop_reply (ptid_t ptid);
222
223 struct threads_listing_context;
224 static void remove_new_fork_children (struct threads_listing_context *);
225
226 static void remote_async_inferior_event_handler (gdb_client_data);
227
228 static void remote_terminal_ours (struct target_ops *self);
229
230 static int remote_read_description_p (struct target_ops *target);
231
232 static void remote_console_output (char *msg);
233
234 static int remote_supports_cond_breakpoints (struct target_ops *self);
235
236 static int remote_can_run_breakpoint_commands (struct target_ops *self);
237
238 static void remote_btrace_reset (void);
239
240 static int stop_reply_queue_length (void);
241
242 static void readahead_cache_invalidate (void);
243
244 /* For "remote".  */
245
246 static struct cmd_list_element *remote_cmdlist;
247
248 /* For "set remote" and "show remote".  */
249
250 static struct cmd_list_element *remote_set_cmdlist;
251 static struct cmd_list_element *remote_show_cmdlist;
252
253 /* Stub vCont actions support.
254
255    Each field is a boolean flag indicating whether the stub reports
256    support for the corresponding action.  */
257
258 struct vCont_action_support
259 {
260   /* vCont;t */
261   int t;
262
263   /* vCont;r */
264   int r;
265
266   /* vCont;s */
267   int s;
268
269   /* vCont;S */
270   int S;
271 };
272
273 /* Controls whether GDB is willing to use range stepping.  */
274
275 static int use_range_stepping = 1;
276
277 #define OPAQUETHREADBYTES 8
278
279 /* a 64 bit opaque identifier */
280 typedef unsigned char threadref[OPAQUETHREADBYTES];
281
282 /* About this many threadisds fit in a packet.  */
283
284 #define MAXTHREADLISTRESULTS 32
285
286 /* Data for the vFile:pread readahead cache.  */
287
288 struct readahead_cache
289 {
290   /* The file descriptor for the file that is being cached.  -1 if the
291      cache is invalid.  */
292   int fd;
293
294   /* The offset into the file that the cache buffer corresponds
295      to.  */
296   ULONGEST offset;
297
298   /* The buffer holding the cache contents.  */
299   gdb_byte *buf;
300   /* The buffer's size.  We try to read as much as fits into a packet
301      at a time.  */
302   size_t bufsize;
303
304   /* Cache hit and miss counters.  */
305   ULONGEST hit_count;
306   ULONGEST miss_count;
307 };
308
309 /* Description of the remote protocol state for the currently
310    connected target.  This is per-target state, and independent of the
311    selected architecture.  */
312
313 struct remote_state
314 {
315   /* A buffer to use for incoming packets, and its current size.  The
316      buffer is grown dynamically for larger incoming packets.
317      Outgoing packets may also be constructed in this buffer.
318      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
320      packets.  */
321   char *buf;
322   long buf_size;
323
324   /* True if we're going through initial connection setup (finding out
325      about the remote side's threads, relocating symbols, etc.).  */
326   int starting_up;
327
328   /* If we negotiated packet size explicitly (and thus can bypass
329      heuristics for the largest packet size that will not overflow
330      a buffer in the stub), this will be set to that packet size.
331      Otherwise zero, meaning to use the guessed size.  */
332   long explicit_packet_size;
333
334   /* remote_wait is normally called when the target is running and
335      waits for a stop reply packet.  But sometimes we need to call it
336      when the target is already stopped.  We can send a "?" packet
337      and have remote_wait read the response.  Or, if we already have
338      the response, we can stash it in BUF and tell remote_wait to
339      skip calling getpkt.  This flag is set when BUF contains a
340      stop reply packet and the target is not waiting.  */
341   int cached_wait_status;
342
343   /* True, if in no ack mode.  That is, neither GDB nor the stub will
344      expect acks from each other.  The connection is assumed to be
345      reliable.  */
346   int noack_mode;
347
348   /* True if we're connected in extended remote mode.  */
349   int extended;
350
351   /* True if we resumed the target and we're waiting for the target to
352      stop.  In the mean time, we can't start another command/query.
353      The remote server wouldn't be ready to process it, so we'd
354      timeout waiting for a reply that would never come and eventually
355      we'd close the connection.  This can happen in asynchronous mode
356      because we allow GDB commands while the target is running.  */
357   int waiting_for_stop_reply;
358
359   /* The status of the stub support for the various vCont actions.  */
360   struct vCont_action_support supports_vCont;
361
362   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363      responded to that.  */
364   int ctrlc_pending_p;
365
366   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
367      remote_open knows that we don't have a file open when the program
368      starts.  */
369   struct serial *remote_desc;
370
371   /* These are the threads which we last sent to the remote system.  The
372      TID member will be -1 for all or -2 for not sent yet.  */
373   ptid_t general_thread;
374   ptid_t continue_thread;
375
376   /* This is the traceframe which we last selected on the remote system.
377      It will be -1 if no traceframe is selected.  */
378   int remote_traceframe_number;
379
380   char *last_pass_packet;
381
382   /* The last QProgramSignals packet sent to the target.  We bypass
383      sending a new program signals list down to the target if the new
384      packet is exactly the same as the last we sent.  IOW, we only let
385      the target know about program signals list changes.  */
386   char *last_program_signals_packet;
387
388   enum gdb_signal last_sent_signal;
389
390   int last_sent_step;
391
392   char *finished_object;
393   char *finished_annex;
394   ULONGEST finished_offset;
395
396   /* Should we try the 'ThreadInfo' query packet?
397
398      This variable (NOT available to the user: auto-detect only!)
399      determines whether GDB will use the new, simpler "ThreadInfo"
400      query or the older, more complex syntax for thread queries.
401      This is an auto-detect variable (set to true at each connect,
402      and set to false when the target fails to recognize it).  */
403   int use_threadinfo_query;
404   int use_threadextra_query;
405
406   threadref echo_nextthread;
407   threadref nextthread;
408   threadref resultthreadlist[MAXTHREADLISTRESULTS];
409
410   /* The state of remote notification.  */
411   struct remote_notif_state *notif_state;
412
413   /* The branch trace configuration.  */
414   struct btrace_config btrace_config;
415
416   /* The argument to the last "vFile:setfs:" packet we sent, used
417      to avoid sending repeated unnecessary "vFile:setfs:" packets.
418      Initialized to -1 to indicate that no "vFile:setfs:" packet
419      has yet been sent.  */
420   int fs_pid;
421
422   /* A readahead cache for vFile:pread.  Often, reading a binary
423      involves a sequence of small reads.  E.g., when parsing an ELF
424      file.  A readahead cache helps mostly the case of remote
425      debugging on a connection with higher latency, due to the
426      request/reply nature of the RSP.  We only cache data for a single
427      file descriptor at a time.  */
428   struct readahead_cache readahead_cache;
429 };
430
431 /* Private data that we'll store in (struct thread_info)->private.  */
432 struct private_thread_info
433 {
434   char *extra;
435   char *name;
436   int core;
437
438   /* Whether the target stopped for a breakpoint/watchpoint.  */
439   enum target_stop_reason stop_reason;
440
441   /* This is set to the data address of the access causing the target
442      to stop for a watchpoint.  */
443   CORE_ADDR watch_data_address;
444 };
445
446 static void
447 free_private_thread_info (struct private_thread_info *info)
448 {
449   xfree (info->extra);
450   xfree (info->name);
451   xfree (info);
452 }
453
454 /* This data could be associated with a target, but we do not always
455    have access to the current target when we need it, so for now it is
456    static.  This will be fine for as long as only one target is in use
457    at a time.  */
458 static struct remote_state *remote_state;
459
460 static struct remote_state *
461 get_remote_state_raw (void)
462 {
463   return remote_state;
464 }
465
466 /* Allocate a new struct remote_state with xmalloc, initialize it, and
467    return it.  */
468
469 static struct remote_state *
470 new_remote_state (void)
471 {
472   struct remote_state *result = XCNEW (struct remote_state);
473
474   /* The default buffer size is unimportant; it will be expanded
475      whenever a larger buffer is needed. */
476   result->buf_size = 400;
477   result->buf = (char *) xmalloc (result->buf_size);
478   result->remote_traceframe_number = -1;
479   result->last_sent_signal = GDB_SIGNAL_0;
480   result->fs_pid = -1;
481
482   return result;
483 }
484
485 /* Description of the remote protocol for a given architecture.  */
486
487 struct packet_reg
488 {
489   long offset; /* Offset into G packet.  */
490   long regnum; /* GDB's internal register number.  */
491   LONGEST pnum; /* Remote protocol register number.  */
492   int in_g_packet; /* Always part of G packet.  */
493   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
494      at present.  */
495   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
496      at present.  */
497 };
498
499 struct remote_arch_state
500 {
501   /* Description of the remote protocol registers.  */
502   long sizeof_g_packet;
503
504   /* Description of the remote protocol registers indexed by REGNUM
505      (making an array gdbarch_num_regs in size).  */
506   struct packet_reg *regs;
507
508   /* This is the size (in chars) of the first response to the ``g''
509      packet.  It is used as a heuristic when determining the maximum
510      size of memory-read and memory-write packets.  A target will
511      typically only reserve a buffer large enough to hold the ``g''
512      packet.  The size does not include packet overhead (headers and
513      trailers).  */
514   long actual_register_packet_size;
515
516   /* This is the maximum size (in chars) of a non read/write packet.
517      It is also used as a cap on the size of read/write packets.  */
518   long remote_packet_size;
519 };
520
521 /* Utility: generate error from an incoming stub packet.  */
522 static void
523 trace_error (char *buf)
524 {
525   if (*buf++ != 'E')
526     return;                     /* not an error msg */
527   switch (*buf)
528     {
529     case '1':                   /* malformed packet error */
530       if (*++buf == '0')        /*   general case: */
531         error (_("remote.c: error in outgoing packet."));
532       else
533         error (_("remote.c: error in outgoing packet at field #%ld."),
534                strtol (buf, NULL, 16));
535     default:
536       error (_("Target returns error code '%s'."), buf);
537     }
538 }
539
540 /* Utility: wait for reply from stub, while accepting "O" packets.  */
541 static char *
542 remote_get_noisy_reply (char **buf_p,
543                         long *sizeof_buf)
544 {
545   do                            /* Loop on reply from remote stub.  */
546     {
547       char *buf;
548
549       QUIT;                     /* Allow user to bail out with ^C.  */
550       getpkt (buf_p, sizeof_buf, 0);
551       buf = *buf_p;
552       if (buf[0] == 'E')
553         trace_error (buf);
554       else if (startswith (buf, "qRelocInsn:"))
555         {
556           ULONGEST ul;
557           CORE_ADDR from, to, org_to;
558           char *p, *pp;
559           int adjusted_size = 0;
560           int relocated = 0;
561
562           p = buf + strlen ("qRelocInsn:");
563           pp = unpack_varlen_hex (p, &ul);
564           if (*pp != ';')
565             error (_("invalid qRelocInsn packet: %s"), buf);
566           from = ul;
567
568           p = pp + 1;
569           unpack_varlen_hex (p, &ul);
570           to = ul;
571
572           org_to = to;
573
574           TRY
575             {
576               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
577               relocated = 1;
578             }
579           CATCH (ex, RETURN_MASK_ALL)
580             {
581               if (ex.error == MEMORY_ERROR)
582                 {
583                   /* Propagate memory errors silently back to the
584                      target.  The stub may have limited the range of
585                      addresses we can write to, for example.  */
586                 }
587               else
588                 {
589                   /* Something unexpectedly bad happened.  Be verbose
590                      so we can tell what, and propagate the error back
591                      to the stub, so it doesn't get stuck waiting for
592                      a response.  */
593                   exception_fprintf (gdb_stderr, ex,
594                                      _("warning: relocating instruction: "));
595                 }
596               putpkt ("E01");
597             }
598           END_CATCH
599
600           if (relocated)
601             {
602               adjusted_size = to - org_to;
603
604               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
605               putpkt (buf);
606             }
607         }
608       else if (buf[0] == 'O' && buf[1] != 'K')
609         remote_console_output (buf + 1);        /* 'O' message from stub */
610       else
611         return buf;             /* Here's the actual reply.  */
612     }
613   while (1);
614 }
615
616 /* Handle for retreving the remote protocol data from gdbarch.  */
617 static struct gdbarch_data *remote_gdbarch_data_handle;
618
619 static struct remote_arch_state *
620 get_remote_arch_state (void)
621 {
622   gdb_assert (target_gdbarch () != NULL);
623   return ((struct remote_arch_state *)
624           gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
625 }
626
627 /* Fetch the global remote target state.  */
628
629 static struct remote_state *
630 get_remote_state (void)
631 {
632   /* Make sure that the remote architecture state has been
633      initialized, because doing so might reallocate rs->buf.  Any
634      function which calls getpkt also needs to be mindful of changes
635      to rs->buf, but this call limits the number of places which run
636      into trouble.  */
637   get_remote_arch_state ();
638
639   return get_remote_state_raw ();
640 }
641
642 /* Cleanup routine for the remote module's pspace data.  */
643
644 static void
645 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
646 {
647   char *remote_exec_file = (char *) arg;
648
649   xfree (remote_exec_file);
650 }
651
652 /* Fetch the remote exec-file from the current program space.  */
653
654 static const char *
655 get_remote_exec_file (void)
656 {
657   char *remote_exec_file;
658
659   remote_exec_file
660     = (char *) program_space_data (current_program_space,
661                                    remote_pspace_data);
662   if (remote_exec_file == NULL)
663     return "";
664
665   return remote_exec_file;
666 }
667
668 /* Set the remote exec file for PSPACE.  */
669
670 static void
671 set_pspace_remote_exec_file (struct program_space *pspace,
672                         char *remote_exec_file)
673 {
674   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
675
676   xfree (old_file);
677   set_program_space_data (pspace, remote_pspace_data,
678                           xstrdup (remote_exec_file));
679 }
680
681 /* The "set/show remote exec-file" set command hook.  */
682
683 static void
684 set_remote_exec_file (char *ignored, int from_tty,
685                       struct cmd_list_element *c)
686 {
687   gdb_assert (remote_exec_file_var != NULL);
688   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
689 }
690
691 /* The "set/show remote exec-file" show command hook.  */
692
693 static void
694 show_remote_exec_file (struct ui_file *file, int from_tty,
695                        struct cmd_list_element *cmd, const char *value)
696 {
697   fprintf_filtered (file, "%s\n", remote_exec_file_var);
698 }
699
700 static int
701 compare_pnums (const void *lhs_, const void *rhs_)
702 {
703   const struct packet_reg * const *lhs
704     = (const struct packet_reg * const *) lhs_;
705   const struct packet_reg * const *rhs
706     = (const struct packet_reg * const *) rhs_;
707
708   if ((*lhs)->pnum < (*rhs)->pnum)
709     return -1;
710   else if ((*lhs)->pnum == (*rhs)->pnum)
711     return 0;
712   else
713     return 1;
714 }
715
716 static int
717 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
718 {
719   int regnum, num_remote_regs, offset;
720   struct packet_reg **remote_regs;
721
722   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
723     {
724       struct packet_reg *r = &regs[regnum];
725
726       if (register_size (gdbarch, regnum) == 0)
727         /* Do not try to fetch zero-sized (placeholder) registers.  */
728         r->pnum = -1;
729       else
730         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
731
732       r->regnum = regnum;
733     }
734
735   /* Define the g/G packet format as the contents of each register
736      with a remote protocol number, in order of ascending protocol
737      number.  */
738
739   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
740   for (num_remote_regs = 0, regnum = 0;
741        regnum < gdbarch_num_regs (gdbarch);
742        regnum++)
743     if (regs[regnum].pnum != -1)
744       remote_regs[num_remote_regs++] = &regs[regnum];
745
746   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
747          compare_pnums);
748
749   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
750     {
751       remote_regs[regnum]->in_g_packet = 1;
752       remote_regs[regnum]->offset = offset;
753       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
754     }
755
756   return offset;
757 }
758
759 /* Given the architecture described by GDBARCH, return the remote
760    protocol register's number and the register's offset in the g/G
761    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
762    If the target does not have a mapping for REGNUM, return false,
763    otherwise, return true.  */
764
765 int
766 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
767                                    int *pnum, int *poffset)
768 {
769   int sizeof_g_packet;
770   struct packet_reg *regs;
771   struct cleanup *old_chain;
772
773   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
774
775   regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
776   old_chain = make_cleanup (xfree, regs);
777
778   sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
779
780   *pnum = regs[regnum].pnum;
781   *poffset = regs[regnum].offset;
782
783   do_cleanups (old_chain);
784
785   return *pnum != -1;
786 }
787
788 static void *
789 init_remote_state (struct gdbarch *gdbarch)
790 {
791   struct remote_state *rs = get_remote_state_raw ();
792   struct remote_arch_state *rsa;
793
794   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
795
796   /* Use the architecture to build a regnum<->pnum table, which will be
797      1:1 unless a feature set specifies otherwise.  */
798   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
799                                       gdbarch_num_regs (gdbarch),
800                                       struct packet_reg);
801
802   /* Record the maximum possible size of the g packet - it may turn out
803      to be smaller.  */
804   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
805
806   /* Default maximum number of characters in a packet body.  Many
807      remote stubs have a hardwired buffer size of 400 bytes
808      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
809      as the maximum packet-size to ensure that the packet and an extra
810      NUL character can always fit in the buffer.  This stops GDB
811      trashing stubs that try to squeeze an extra NUL into what is
812      already a full buffer (As of 1999-12-04 that was most stubs).  */
813   rsa->remote_packet_size = 400 - 1;
814
815   /* This one is filled in when a ``g'' packet is received.  */
816   rsa->actual_register_packet_size = 0;
817
818   /* Should rsa->sizeof_g_packet needs more space than the
819      default, adjust the size accordingly.  Remember that each byte is
820      encoded as two characters.  32 is the overhead for the packet
821      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
822      (``$NN:G...#NN'') is a better guess, the below has been padded a
823      little.  */
824   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
825     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
826
827   /* Make sure that the packet buffer is plenty big enough for
828      this architecture.  */
829   if (rs->buf_size < rsa->remote_packet_size)
830     {
831       rs->buf_size = 2 * rsa->remote_packet_size;
832       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
833     }
834
835   return rsa;
836 }
837
838 /* Return the current allowed size of a remote packet.  This is
839    inferred from the current architecture, and should be used to
840    limit the length of outgoing packets.  */
841 static long
842 get_remote_packet_size (void)
843 {
844   struct remote_state *rs = get_remote_state ();
845   struct remote_arch_state *rsa = get_remote_arch_state ();
846
847   if (rs->explicit_packet_size)
848     return rs->explicit_packet_size;
849
850   return rsa->remote_packet_size;
851 }
852
853 static struct packet_reg *
854 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
855 {
856   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
857     return NULL;
858   else
859     {
860       struct packet_reg *r = &rsa->regs[regnum];
861
862       gdb_assert (r->regnum == regnum);
863       return r;
864     }
865 }
866
867 static struct packet_reg *
868 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
869 {
870   int i;
871
872   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
873     {
874       struct packet_reg *r = &rsa->regs[i];
875
876       if (r->pnum == pnum)
877         return r;
878     }
879   return NULL;
880 }
881
882 static struct target_ops remote_ops;
883
884 static struct target_ops extended_remote_ops;
885
886 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
887    ``forever'' still use the normal timeout mechanism.  This is
888    currently used by the ASYNC code to guarentee that target reads
889    during the initial connect always time-out.  Once getpkt has been
890    modified to return a timeout indication and, in turn
891    remote_wait()/wait_for_inferior() have gained a timeout parameter
892    this can go away.  */
893 static int wait_forever_enabled_p = 1;
894
895 /* Allow the user to specify what sequence to send to the remote
896    when he requests a program interruption: Although ^C is usually
897    what remote systems expect (this is the default, here), it is
898    sometimes preferable to send a break.  On other systems such
899    as the Linux kernel, a break followed by g, which is Magic SysRq g
900    is required in order to interrupt the execution.  */
901 const char interrupt_sequence_control_c[] = "Ctrl-C";
902 const char interrupt_sequence_break[] = "BREAK";
903 const char interrupt_sequence_break_g[] = "BREAK-g";
904 static const char *const interrupt_sequence_modes[] =
905   {
906     interrupt_sequence_control_c,
907     interrupt_sequence_break,
908     interrupt_sequence_break_g,
909     NULL
910   };
911 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
912
913 static void
914 show_interrupt_sequence (struct ui_file *file, int from_tty,
915                          struct cmd_list_element *c,
916                          const char *value)
917 {
918   if (interrupt_sequence_mode == interrupt_sequence_control_c)
919     fprintf_filtered (file,
920                       _("Send the ASCII ETX character (Ctrl-c) "
921                         "to the remote target to interrupt the "
922                         "execution of the program.\n"));
923   else if (interrupt_sequence_mode == interrupt_sequence_break)
924     fprintf_filtered (file,
925                       _("send a break signal to the remote target "
926                         "to interrupt the execution of the program.\n"));
927   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
928     fprintf_filtered (file,
929                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
930                         "the remote target to interrupt the execution "
931                         "of Linux kernel.\n"));
932   else
933     internal_error (__FILE__, __LINE__,
934                     _("Invalid value for interrupt_sequence_mode: %s."),
935                     interrupt_sequence_mode);
936 }
937
938 /* This boolean variable specifies whether interrupt_sequence is sent
939    to the remote target when gdb connects to it.
940    This is mostly needed when you debug the Linux kernel: The Linux kernel
941    expects BREAK g which is Magic SysRq g for connecting gdb.  */
942 static int interrupt_on_connect = 0;
943
944 /* This variable is used to implement the "set/show remotebreak" commands.
945    Since these commands are now deprecated in favor of "set/show remote
946    interrupt-sequence", it no longer has any effect on the code.  */
947 static int remote_break;
948
949 static void
950 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
951 {
952   if (remote_break)
953     interrupt_sequence_mode = interrupt_sequence_break;
954   else
955     interrupt_sequence_mode = interrupt_sequence_control_c;
956 }
957
958 static void
959 show_remotebreak (struct ui_file *file, int from_tty,
960                   struct cmd_list_element *c,
961                   const char *value)
962 {
963 }
964
965 /* This variable sets the number of bits in an address that are to be
966    sent in a memory ("M" or "m") packet.  Normally, after stripping
967    leading zeros, the entire address would be sent.  This variable
968    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
969    initial implementation of remote.c restricted the address sent in
970    memory packets to ``host::sizeof long'' bytes - (typically 32
971    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
972    address was never sent.  Since fixing this bug may cause a break in
973    some remote targets this variable is principly provided to
974    facilitate backward compatibility.  */
975
976 static unsigned int remote_address_size;
977
978 /* Temporary to track who currently owns the terminal.  See
979    remote_terminal_* for more details.  */
980
981 static int remote_async_terminal_ours_p;
982
983 \f
984 /* User configurable variables for the number of characters in a
985    memory read/write packet.  MIN (rsa->remote_packet_size,
986    rsa->sizeof_g_packet) is the default.  Some targets need smaller
987    values (fifo overruns, et.al.) and some users need larger values
988    (speed up transfers).  The variables ``preferred_*'' (the user
989    request), ``current_*'' (what was actually set) and ``forced_*''
990    (Positive - a soft limit, negative - a hard limit).  */
991
992 struct memory_packet_config
993 {
994   char *name;
995   long size;
996   int fixed_p;
997 };
998
999 /* The default max memory-write-packet-size.  The 16k is historical.
1000    (It came from older GDB's using alloca for buffers and the
1001    knowledge (folklore?) that some hosts don't cope very well with
1002    large alloca calls.)  */
1003 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1004
1005 /* The minimum remote packet size for memory transfers.  Ensures we
1006    can write at least one byte.  */
1007 #define MIN_MEMORY_PACKET_SIZE 20
1008
1009 /* Compute the current size of a read/write packet.  Since this makes
1010    use of ``actual_register_packet_size'' the computation is dynamic.  */
1011
1012 static long
1013 get_memory_packet_size (struct memory_packet_config *config)
1014 {
1015   struct remote_state *rs = get_remote_state ();
1016   struct remote_arch_state *rsa = get_remote_arch_state ();
1017
1018   long what_they_get;
1019   if (config->fixed_p)
1020     {
1021       if (config->size <= 0)
1022         what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1023       else
1024         what_they_get = config->size;
1025     }
1026   else
1027     {
1028       what_they_get = get_remote_packet_size ();
1029       /* Limit the packet to the size specified by the user.  */
1030       if (config->size > 0
1031           && what_they_get > config->size)
1032         what_they_get = config->size;
1033
1034       /* Limit it to the size of the targets ``g'' response unless we have
1035          permission from the stub to use a larger packet size.  */
1036       if (rs->explicit_packet_size == 0
1037           && rsa->actual_register_packet_size > 0
1038           && what_they_get > rsa->actual_register_packet_size)
1039         what_they_get = rsa->actual_register_packet_size;
1040     }
1041   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1042     what_they_get = MIN_MEMORY_PACKET_SIZE;
1043
1044   /* Make sure there is room in the global buffer for this packet
1045      (including its trailing NUL byte).  */
1046   if (rs->buf_size < what_they_get + 1)
1047     {
1048       rs->buf_size = 2 * what_they_get;
1049       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1050     }
1051
1052   return what_they_get;
1053 }
1054
1055 /* Update the size of a read/write packet.  If they user wants
1056    something really big then do a sanity check.  */
1057
1058 static void
1059 set_memory_packet_size (char *args, struct memory_packet_config *config)
1060 {
1061   int fixed_p = config->fixed_p;
1062   long size = config->size;
1063
1064   if (args == NULL)
1065     error (_("Argument required (integer, `fixed' or `limited')."));
1066   else if (strcmp (args, "hard") == 0
1067       || strcmp (args, "fixed") == 0)
1068     fixed_p = 1;
1069   else if (strcmp (args, "soft") == 0
1070            || strcmp (args, "limit") == 0)
1071     fixed_p = 0;
1072   else
1073     {
1074       char *end;
1075
1076       size = strtoul (args, &end, 0);
1077       if (args == end)
1078         error (_("Invalid %s (bad syntax)."), config->name);
1079
1080       /* Instead of explicitly capping the size of a packet to or
1081          disallowing it, the user is allowed to set the size to
1082          something arbitrarily large.  */
1083     }
1084
1085   /* So that the query shows the correct value.  */
1086   if (size <= 0)
1087     size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1088
1089   /* Extra checks?  */
1090   if (fixed_p && !config->fixed_p)
1091     {
1092       if (! query (_("The target may not be able to correctly handle a %s\n"
1093                    "of %ld bytes. Change the packet size? "),
1094                    config->name, size))
1095         error (_("Packet size not changed."));
1096     }
1097   /* Update the config.  */
1098   config->fixed_p = fixed_p;
1099   config->size = size;
1100 }
1101
1102 static void
1103 show_memory_packet_size (struct memory_packet_config *config)
1104 {
1105   printf_filtered (_("The %s is %ld. "), config->name, config->size);
1106   if (config->fixed_p)
1107     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1108                      get_memory_packet_size (config));
1109   else
1110     printf_filtered (_("Packets are limited to %ld bytes.\n"),
1111                      get_memory_packet_size (config));
1112 }
1113
1114 static struct memory_packet_config memory_write_packet_config =
1115 {
1116   "memory-write-packet-size",
1117 };
1118
1119 static void
1120 set_memory_write_packet_size (char *args, int from_tty)
1121 {
1122   set_memory_packet_size (args, &memory_write_packet_config);
1123 }
1124
1125 static void
1126 show_memory_write_packet_size (char *args, int from_tty)
1127 {
1128   show_memory_packet_size (&memory_write_packet_config);
1129 }
1130
1131 static long
1132 get_memory_write_packet_size (void)
1133 {
1134   return get_memory_packet_size (&memory_write_packet_config);
1135 }
1136
1137 static struct memory_packet_config memory_read_packet_config =
1138 {
1139   "memory-read-packet-size",
1140 };
1141
1142 static void
1143 set_memory_read_packet_size (char *args, int from_tty)
1144 {
1145   set_memory_packet_size (args, &memory_read_packet_config);
1146 }
1147
1148 static void
1149 show_memory_read_packet_size (char *args, int from_tty)
1150 {
1151   show_memory_packet_size (&memory_read_packet_config);
1152 }
1153
1154 static long
1155 get_memory_read_packet_size (void)
1156 {
1157   long size = get_memory_packet_size (&memory_read_packet_config);
1158
1159   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1160      extra buffer size argument before the memory read size can be
1161      increased beyond this.  */
1162   if (size > get_remote_packet_size ())
1163     size = get_remote_packet_size ();
1164   return size;
1165 }
1166
1167 \f
1168 /* Generic configuration support for packets the stub optionally
1169    supports.  Allows the user to specify the use of the packet as well
1170    as allowing GDB to auto-detect support in the remote stub.  */
1171
1172 enum packet_support
1173   {
1174     PACKET_SUPPORT_UNKNOWN = 0,
1175     PACKET_ENABLE,
1176     PACKET_DISABLE
1177   };
1178
1179 struct packet_config
1180   {
1181     const char *name;
1182     const char *title;
1183
1184     /* If auto, GDB auto-detects support for this packet or feature,
1185        either through qSupported, or by trying the packet and looking
1186        at the response.  If true, GDB assumes the target supports this
1187        packet.  If false, the packet is disabled.  Configs that don't
1188        have an associated command always have this set to auto.  */
1189     enum auto_boolean detect;
1190
1191     /* Does the target support this packet?  */
1192     enum packet_support support;
1193   };
1194
1195 /* Analyze a packet's return value and update the packet config
1196    accordingly.  */
1197
1198 enum packet_result
1199 {
1200   PACKET_ERROR,
1201   PACKET_OK,
1202   PACKET_UNKNOWN
1203 };
1204
1205 static enum packet_support packet_config_support (struct packet_config *config);
1206 static enum packet_support packet_support (int packet);
1207
1208 static void
1209 show_packet_config_cmd (struct packet_config *config)
1210 {
1211   char *support = "internal-error";
1212
1213   switch (packet_config_support (config))
1214     {
1215     case PACKET_ENABLE:
1216       support = "enabled";
1217       break;
1218     case PACKET_DISABLE:
1219       support = "disabled";
1220       break;
1221     case PACKET_SUPPORT_UNKNOWN:
1222       support = "unknown";
1223       break;
1224     }
1225   switch (config->detect)
1226     {
1227     case AUTO_BOOLEAN_AUTO:
1228       printf_filtered (_("Support for the `%s' packet "
1229                          "is auto-detected, currently %s.\n"),
1230                        config->name, support);
1231       break;
1232     case AUTO_BOOLEAN_TRUE:
1233     case AUTO_BOOLEAN_FALSE:
1234       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1235                        config->name, support);
1236       break;
1237     }
1238 }
1239
1240 static void
1241 add_packet_config_cmd (struct packet_config *config, const char *name,
1242                        const char *title, int legacy)
1243 {
1244   char *set_doc;
1245   char *show_doc;
1246   char *cmd_name;
1247
1248   config->name = name;
1249   config->title = title;
1250   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1251                         name, title);
1252   show_doc = xstrprintf ("Show current use of remote "
1253                          "protocol `%s' (%s) packet",
1254                          name, title);
1255   /* set/show TITLE-packet {auto,on,off} */
1256   cmd_name = xstrprintf ("%s-packet", title);
1257   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1258                                 &config->detect, set_doc,
1259                                 show_doc, NULL, /* help_doc */
1260                                 NULL,
1261                                 show_remote_protocol_packet_cmd,
1262                                 &remote_set_cmdlist, &remote_show_cmdlist);
1263   /* The command code copies the documentation strings.  */
1264   xfree (set_doc);
1265   xfree (show_doc);
1266   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1267   if (legacy)
1268     {
1269       char *legacy_name;
1270
1271       legacy_name = xstrprintf ("%s-packet", name);
1272       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1273                      &remote_set_cmdlist);
1274       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1275                      &remote_show_cmdlist);
1276     }
1277 }
1278
1279 static enum packet_result
1280 packet_check_result (const char *buf)
1281 {
1282   if (buf[0] != '\0')
1283     {
1284       /* The stub recognized the packet request.  Check that the
1285          operation succeeded.  */
1286       if (buf[0] == 'E'
1287           && isxdigit (buf[1]) && isxdigit (buf[2])
1288           && buf[3] == '\0')
1289         /* "Enn"  - definitly an error.  */
1290         return PACKET_ERROR;
1291
1292       /* Always treat "E." as an error.  This will be used for
1293          more verbose error messages, such as E.memtypes.  */
1294       if (buf[0] == 'E' && buf[1] == '.')
1295         return PACKET_ERROR;
1296
1297       /* The packet may or may not be OK.  Just assume it is.  */
1298       return PACKET_OK;
1299     }
1300   else
1301     /* The stub does not support the packet.  */
1302     return PACKET_UNKNOWN;
1303 }
1304
1305 static enum packet_result
1306 packet_ok (const char *buf, struct packet_config *config)
1307 {
1308   enum packet_result result;
1309
1310   if (config->detect != AUTO_BOOLEAN_TRUE
1311       && config->support == PACKET_DISABLE)
1312     internal_error (__FILE__, __LINE__,
1313                     _("packet_ok: attempt to use a disabled packet"));
1314
1315   result = packet_check_result (buf);
1316   switch (result)
1317     {
1318     case PACKET_OK:
1319     case PACKET_ERROR:
1320       /* The stub recognized the packet request.  */
1321       if (config->support == PACKET_SUPPORT_UNKNOWN)
1322         {
1323           if (remote_debug)
1324             fprintf_unfiltered (gdb_stdlog,
1325                                 "Packet %s (%s) is supported\n",
1326                                 config->name, config->title);
1327           config->support = PACKET_ENABLE;
1328         }
1329       break;
1330     case PACKET_UNKNOWN:
1331       /* The stub does not support the packet.  */
1332       if (config->detect == AUTO_BOOLEAN_AUTO
1333           && config->support == PACKET_ENABLE)
1334         {
1335           /* If the stub previously indicated that the packet was
1336              supported then there is a protocol error.  */
1337           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1338                  config->name, config->title);
1339         }
1340       else if (config->detect == AUTO_BOOLEAN_TRUE)
1341         {
1342           /* The user set it wrong.  */
1343           error (_("Enabled packet %s (%s) not recognized by stub"),
1344                  config->name, config->title);
1345         }
1346
1347       if (remote_debug)
1348         fprintf_unfiltered (gdb_stdlog,
1349                             "Packet %s (%s) is NOT supported\n",
1350                             config->name, config->title);
1351       config->support = PACKET_DISABLE;
1352       break;
1353     }
1354
1355   return result;
1356 }
1357
1358 enum {
1359   PACKET_vCont = 0,
1360   PACKET_X,
1361   PACKET_qSymbol,
1362   PACKET_P,
1363   PACKET_p,
1364   PACKET_Z0,
1365   PACKET_Z1,
1366   PACKET_Z2,
1367   PACKET_Z3,
1368   PACKET_Z4,
1369   PACKET_vFile_setfs,
1370   PACKET_vFile_open,
1371   PACKET_vFile_pread,
1372   PACKET_vFile_pwrite,
1373   PACKET_vFile_close,
1374   PACKET_vFile_unlink,
1375   PACKET_vFile_readlink,
1376   PACKET_vFile_fstat,
1377   PACKET_qXfer_auxv,
1378   PACKET_qXfer_features,
1379   PACKET_qXfer_exec_file,
1380   PACKET_qXfer_libraries,
1381   PACKET_qXfer_libraries_svr4,
1382   PACKET_qXfer_memory_map,
1383   PACKET_qXfer_spu_read,
1384   PACKET_qXfer_spu_write,
1385   PACKET_qXfer_osdata,
1386   PACKET_qXfer_threads,
1387   PACKET_qXfer_statictrace_read,
1388   PACKET_qXfer_traceframe_info,
1389   PACKET_qXfer_uib,
1390   PACKET_qGetTIBAddr,
1391   PACKET_qGetTLSAddr,
1392   PACKET_qSupported,
1393   PACKET_qTStatus,
1394   PACKET_QPassSignals,
1395   PACKET_QCatchSyscalls,
1396   PACKET_QProgramSignals,
1397   PACKET_qCRC,
1398   PACKET_qSearch_memory,
1399   PACKET_vAttach,
1400   PACKET_vRun,
1401   PACKET_QStartNoAckMode,
1402   PACKET_vKill,
1403   PACKET_qXfer_siginfo_read,
1404   PACKET_qXfer_siginfo_write,
1405   PACKET_qAttached,
1406
1407   /* Support for conditional tracepoints.  */
1408   PACKET_ConditionalTracepoints,
1409
1410   /* Support for target-side breakpoint conditions.  */
1411   PACKET_ConditionalBreakpoints,
1412
1413   /* Support for target-side breakpoint commands.  */
1414   PACKET_BreakpointCommands,
1415
1416   /* Support for fast tracepoints.  */
1417   PACKET_FastTracepoints,
1418
1419   /* Support for static tracepoints.  */
1420   PACKET_StaticTracepoints,
1421
1422   /* Support for installing tracepoints while a trace experiment is
1423      running.  */
1424   PACKET_InstallInTrace,
1425
1426   PACKET_bc,
1427   PACKET_bs,
1428   PACKET_TracepointSource,
1429   PACKET_QAllow,
1430   PACKET_qXfer_fdpic,
1431   PACKET_QDisableRandomization,
1432   PACKET_QAgent,
1433   PACKET_QTBuffer_size,
1434   PACKET_Qbtrace_off,
1435   PACKET_Qbtrace_bts,
1436   PACKET_Qbtrace_pt,
1437   PACKET_qXfer_btrace,
1438
1439   /* Support for the QNonStop packet.  */
1440   PACKET_QNonStop,
1441
1442   /* Support for the QThreadEvents packet.  */
1443   PACKET_QThreadEvents,
1444
1445   /* Support for multi-process extensions.  */
1446   PACKET_multiprocess_feature,
1447
1448   /* Support for enabling and disabling tracepoints while a trace
1449      experiment is running.  */
1450   PACKET_EnableDisableTracepoints_feature,
1451
1452   /* Support for collecting strings using the tracenz bytecode.  */
1453   PACKET_tracenz_feature,
1454
1455   /* Support for continuing to run a trace experiment while GDB is
1456      disconnected.  */
1457   PACKET_DisconnectedTracing_feature,
1458
1459   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1460   PACKET_augmented_libraries_svr4_read_feature,
1461
1462   /* Support for the qXfer:btrace-conf:read packet.  */
1463   PACKET_qXfer_btrace_conf,
1464
1465   /* Support for the Qbtrace-conf:bts:size packet.  */
1466   PACKET_Qbtrace_conf_bts_size,
1467
1468   /* Support for swbreak+ feature.  */
1469   PACKET_swbreak_feature,
1470
1471   /* Support for hwbreak+ feature.  */
1472   PACKET_hwbreak_feature,
1473
1474   /* Support for fork events.  */
1475   PACKET_fork_event_feature,
1476
1477   /* Support for vfork events.  */
1478   PACKET_vfork_event_feature,
1479
1480   /* Support for the Qbtrace-conf:pt:size packet.  */
1481   PACKET_Qbtrace_conf_pt_size,
1482
1483   /* Support for exec events.  */
1484   PACKET_exec_event_feature,
1485
1486   /* Support for query supported vCont actions.  */
1487   PACKET_vContSupported,
1488
1489   /* Support remote CTRL-C.  */
1490   PACKET_vCtrlC,
1491
1492   /* Support TARGET_WAITKIND_NO_RESUMED.  */
1493   PACKET_no_resumed,
1494
1495   PACKET_MAX
1496 };
1497
1498 static struct packet_config remote_protocol_packets[PACKET_MAX];
1499
1500 /* Returns the packet's corresponding "set remote foo-packet" command
1501    state.  See struct packet_config for more details.  */
1502
1503 static enum auto_boolean
1504 packet_set_cmd_state (int packet)
1505 {
1506   return remote_protocol_packets[packet].detect;
1507 }
1508
1509 /* Returns whether a given packet or feature is supported.  This takes
1510    into account the state of the corresponding "set remote foo-packet"
1511    command, which may be used to bypass auto-detection.  */
1512
1513 static enum packet_support
1514 packet_config_support (struct packet_config *config)
1515 {
1516   switch (config->detect)
1517     {
1518     case AUTO_BOOLEAN_TRUE:
1519       return PACKET_ENABLE;
1520     case AUTO_BOOLEAN_FALSE:
1521       return PACKET_DISABLE;
1522     case AUTO_BOOLEAN_AUTO:
1523       return config->support;
1524     default:
1525       gdb_assert_not_reached (_("bad switch"));
1526     }
1527 }
1528
1529 /* Same as packet_config_support, but takes the packet's enum value as
1530    argument.  */
1531
1532 static enum packet_support
1533 packet_support (int packet)
1534 {
1535   struct packet_config *config = &remote_protocol_packets[packet];
1536
1537   return packet_config_support (config);
1538 }
1539
1540 static void
1541 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1542                                  struct cmd_list_element *c,
1543                                  const char *value)
1544 {
1545   struct packet_config *packet;
1546
1547   for (packet = remote_protocol_packets;
1548        packet < &remote_protocol_packets[PACKET_MAX];
1549        packet++)
1550     {
1551       if (&packet->detect == c->var)
1552         {
1553           show_packet_config_cmd (packet);
1554           return;
1555         }
1556     }
1557   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1558                   c->name);
1559 }
1560
1561 /* Should we try one of the 'Z' requests?  */
1562
1563 enum Z_packet_type
1564 {
1565   Z_PACKET_SOFTWARE_BP,
1566   Z_PACKET_HARDWARE_BP,
1567   Z_PACKET_WRITE_WP,
1568   Z_PACKET_READ_WP,
1569   Z_PACKET_ACCESS_WP,
1570   NR_Z_PACKET_TYPES
1571 };
1572
1573 /* For compatibility with older distributions.  Provide a ``set remote
1574    Z-packet ...'' command that updates all the Z packet types.  */
1575
1576 static enum auto_boolean remote_Z_packet_detect;
1577
1578 static void
1579 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1580                                   struct cmd_list_element *c)
1581 {
1582   int i;
1583
1584   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1585     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1586 }
1587
1588 static void
1589 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1590                                    struct cmd_list_element *c,
1591                                    const char *value)
1592 {
1593   int i;
1594
1595   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1596     {
1597       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1598     }
1599 }
1600
1601 /* Returns true if the multi-process extensions are in effect.  */
1602
1603 static int
1604 remote_multi_process_p (struct remote_state *rs)
1605 {
1606   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1607 }
1608
1609 /* Returns true if fork events are supported.  */
1610
1611 static int
1612 remote_fork_event_p (struct remote_state *rs)
1613 {
1614   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1615 }
1616
1617 /* Returns true if vfork events are supported.  */
1618
1619 static int
1620 remote_vfork_event_p (struct remote_state *rs)
1621 {
1622   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1623 }
1624
1625 /* Returns true if exec events are supported.  */
1626
1627 static int
1628 remote_exec_event_p (struct remote_state *rs)
1629 {
1630   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1631 }
1632
1633 /* Insert fork catchpoint target routine.  If fork events are enabled
1634    then return success, nothing more to do.  */
1635
1636 static int
1637 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1638 {
1639   struct remote_state *rs = get_remote_state ();
1640
1641   return !remote_fork_event_p (rs);
1642 }
1643
1644 /* Remove fork catchpoint target routine.  Nothing to do, just
1645    return success.  */
1646
1647 static int
1648 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1649 {
1650   return 0;
1651 }
1652
1653 /* Insert vfork catchpoint target routine.  If vfork events are enabled
1654    then return success, nothing more to do.  */
1655
1656 static int
1657 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1658 {
1659   struct remote_state *rs = get_remote_state ();
1660
1661   return !remote_vfork_event_p (rs);
1662 }
1663
1664 /* Remove vfork catchpoint target routine.  Nothing to do, just
1665    return success.  */
1666
1667 static int
1668 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1669 {
1670   return 0;
1671 }
1672
1673 /* Insert exec catchpoint target routine.  If exec events are
1674    enabled, just return success.  */
1675
1676 static int
1677 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1678 {
1679   struct remote_state *rs = get_remote_state ();
1680
1681   return !remote_exec_event_p (rs);
1682 }
1683
1684 /* Remove exec catchpoint target routine.  Nothing to do, just
1685    return success.  */
1686
1687 static int
1688 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1689 {
1690   return 0;
1691 }
1692
1693 /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
1694 static struct async_signal_handler *async_sigint_remote_twice_token;
1695 static struct async_signal_handler *async_sigint_remote_token;
1696
1697 \f
1698 /* Asynchronous signal handle registered as event loop source for
1699    when we have pending events ready to be passed to the core.  */
1700
1701 static struct async_event_handler *remote_async_inferior_event_token;
1702
1703 \f
1704
1705 static ptid_t magic_null_ptid;
1706 static ptid_t not_sent_ptid;
1707 static ptid_t any_thread_ptid;
1708
1709 /* Find out if the stub attached to PID (and hence GDB should offer to
1710    detach instead of killing it when bailing out).  */
1711
1712 static int
1713 remote_query_attached (int pid)
1714 {
1715   struct remote_state *rs = get_remote_state ();
1716   size_t size = get_remote_packet_size ();
1717
1718   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1719     return 0;
1720
1721   if (remote_multi_process_p (rs))
1722     xsnprintf (rs->buf, size, "qAttached:%x", pid);
1723   else
1724     xsnprintf (rs->buf, size, "qAttached");
1725
1726   putpkt (rs->buf);
1727   getpkt (&rs->buf, &rs->buf_size, 0);
1728
1729   switch (packet_ok (rs->buf,
1730                      &remote_protocol_packets[PACKET_qAttached]))
1731     {
1732     case PACKET_OK:
1733       if (strcmp (rs->buf, "1") == 0)
1734         return 1;
1735       break;
1736     case PACKET_ERROR:
1737       warning (_("Remote failure reply: %s"), rs->buf);
1738       break;
1739     case PACKET_UNKNOWN:
1740       break;
1741     }
1742
1743   return 0;
1744 }
1745
1746 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
1747    has been invented by GDB, instead of reported by the target.  Since
1748    we can be connected to a remote system before before knowing about
1749    any inferior, mark the target with execution when we find the first
1750    inferior.  If ATTACHED is 1, then we had just attached to this
1751    inferior.  If it is 0, then we just created this inferior.  If it
1752    is -1, then try querying the remote stub to find out if it had
1753    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
1754    attempt to open this inferior's executable as the main executable
1755    if no main executable is open already.  */
1756
1757 static struct inferior *
1758 remote_add_inferior (int fake_pid_p, int pid, int attached,
1759                      int try_open_exec)
1760 {
1761   struct inferior *inf;
1762
1763   /* Check whether this process we're learning about is to be
1764      considered attached, or if is to be considered to have been
1765      spawned by the stub.  */
1766   if (attached == -1)
1767     attached = remote_query_attached (pid);
1768
1769   if (gdbarch_has_global_solist (target_gdbarch ()))
1770     {
1771       /* If the target shares code across all inferiors, then every
1772          attach adds a new inferior.  */
1773       inf = add_inferior (pid);
1774
1775       /* ... and every inferior is bound to the same program space.
1776          However, each inferior may still have its own address
1777          space.  */
1778       inf->aspace = maybe_new_address_space ();
1779       inf->pspace = current_program_space;
1780     }
1781   else
1782     {
1783       /* In the traditional debugging scenario, there's a 1-1 match
1784          between program/address spaces.  We simply bind the inferior
1785          to the program space's address space.  */
1786       inf = current_inferior ();
1787       inferior_appeared (inf, pid);
1788     }
1789
1790   inf->attach_flag = attached;
1791   inf->fake_pid_p = fake_pid_p;
1792
1793   /* If no main executable is currently open then attempt to
1794      open the file that was executed to create this inferior.  */
1795   if (try_open_exec && get_exec_file (0) == NULL)
1796     exec_file_locate_attach (pid, 1);
1797
1798   return inf;
1799 }
1800
1801 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1802    according to RUNNING.  */
1803
1804 static void
1805 remote_add_thread (ptid_t ptid, int running)
1806 {
1807   struct remote_state *rs = get_remote_state ();
1808
1809   /* GDB historically didn't pull threads in the initial connection
1810      setup.  If the remote target doesn't even have a concept of
1811      threads (e.g., a bare-metal target), even if internally we
1812      consider that a single-threaded target, mentioning a new thread
1813      might be confusing to the user.  Be silent then, preserving the
1814      age old behavior.  */
1815   if (rs->starting_up)
1816     add_thread_silent (ptid);
1817   else
1818     add_thread (ptid);
1819
1820   set_executing (ptid, running);
1821   set_running (ptid, running);
1822 }
1823
1824 /* Come here when we learn about a thread id from the remote target.
1825    It may be the first time we hear about such thread, so take the
1826    opportunity to add it to GDB's thread list.  In case this is the
1827    first time we're noticing its corresponding inferior, add it to
1828    GDB's inferior list as well.  */
1829
1830 static void
1831 remote_notice_new_inferior (ptid_t currthread, int running)
1832 {
1833   /* If this is a new thread, add it to GDB's thread list.
1834      If we leave it up to WFI to do this, bad things will happen.  */
1835
1836   if (in_thread_list (currthread) && is_exited (currthread))
1837     {
1838       /* We're seeing an event on a thread id we knew had exited.
1839          This has to be a new thread reusing the old id.  Add it.  */
1840       remote_add_thread (currthread, running);
1841       return;
1842     }
1843
1844   if (!in_thread_list (currthread))
1845     {
1846       struct inferior *inf = NULL;
1847       int pid = ptid_get_pid (currthread);
1848
1849       if (ptid_is_pid (inferior_ptid)
1850           && pid == ptid_get_pid (inferior_ptid))
1851         {
1852           /* inferior_ptid has no thread member yet.  This can happen
1853              with the vAttach -> remote_wait,"TAAthread:" path if the
1854              stub doesn't support qC.  This is the first stop reported
1855              after an attach, so this is the main thread.  Update the
1856              ptid in the thread list.  */
1857           if (in_thread_list (pid_to_ptid (pid)))
1858             thread_change_ptid (inferior_ptid, currthread);
1859           else
1860             {
1861               remote_add_thread (currthread, running);
1862               inferior_ptid = currthread;
1863             }
1864           return;
1865         }
1866
1867       if (ptid_equal (magic_null_ptid, inferior_ptid))
1868         {
1869           /* inferior_ptid is not set yet.  This can happen with the
1870              vRun -> remote_wait,"TAAthread:" path if the stub
1871              doesn't support qC.  This is the first stop reported
1872              after an attach, so this is the main thread.  Update the
1873              ptid in the thread list.  */
1874           thread_change_ptid (inferior_ptid, currthread);
1875           return;
1876         }
1877
1878       /* When connecting to a target remote, or to a target
1879          extended-remote which already was debugging an inferior, we
1880          may not know about it yet.  Add it before adding its child
1881          thread, so notifications are emitted in a sensible order.  */
1882       if (!in_inferior_list (ptid_get_pid (currthread)))
1883         {
1884           struct remote_state *rs = get_remote_state ();
1885           int fake_pid_p = !remote_multi_process_p (rs);
1886
1887           inf = remote_add_inferior (fake_pid_p,
1888                                      ptid_get_pid (currthread), -1, 1);
1889         }
1890
1891       /* This is really a new thread.  Add it.  */
1892       remote_add_thread (currthread, running);
1893
1894       /* If we found a new inferior, let the common code do whatever
1895          it needs to with it (e.g., read shared libraries, insert
1896          breakpoints), unless we're just setting up an all-stop
1897          connection.  */
1898       if (inf != NULL)
1899         {
1900           struct remote_state *rs = get_remote_state ();
1901
1902           if (!rs->starting_up)
1903             notice_new_inferior (currthread, running, 0);
1904         }
1905     }
1906 }
1907
1908 /* Return the private thread data, creating it if necessary.  */
1909
1910 static struct private_thread_info *
1911 demand_private_info (ptid_t ptid)
1912 {
1913   struct thread_info *info = find_thread_ptid (ptid);
1914
1915   gdb_assert (info);
1916
1917   if (!info->priv)
1918     {
1919       info->priv = XNEW (struct private_thread_info);
1920       info->private_dtor = free_private_thread_info;
1921       info->priv->core = -1;
1922       info->priv->extra = NULL;
1923       info->priv->name = NULL;
1924     }
1925
1926   return info->priv;
1927 }
1928
1929 /* Call this function as a result of
1930    1) A halt indication (T packet) containing a thread id
1931    2) A direct query of currthread
1932    3) Successful execution of set thread */
1933
1934 static void
1935 record_currthread (struct remote_state *rs, ptid_t currthread)
1936 {
1937   rs->general_thread = currthread;
1938 }
1939
1940 /* If 'QPassSignals' is supported, tell the remote stub what signals
1941    it can simply pass through to the inferior without reporting.  */
1942
1943 static void
1944 remote_pass_signals (struct target_ops *self,
1945                      int numsigs, unsigned char *pass_signals)
1946 {
1947   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1948     {
1949       char *pass_packet, *p;
1950       int count = 0, i;
1951       struct remote_state *rs = get_remote_state ();
1952
1953       gdb_assert (numsigs < 256);
1954       for (i = 0; i < numsigs; i++)
1955         {
1956           if (pass_signals[i])
1957             count++;
1958         }
1959       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1960       strcpy (pass_packet, "QPassSignals:");
1961       p = pass_packet + strlen (pass_packet);
1962       for (i = 0; i < numsigs; i++)
1963         {
1964           if (pass_signals[i])
1965             {
1966               if (i >= 16)
1967                 *p++ = tohex (i >> 4);
1968               *p++ = tohex (i & 15);
1969               if (count)
1970                 *p++ = ';';
1971               else
1972                 break;
1973               count--;
1974             }
1975         }
1976       *p = 0;
1977       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1978         {
1979           putpkt (pass_packet);
1980           getpkt (&rs->buf, &rs->buf_size, 0);
1981           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1982           if (rs->last_pass_packet)
1983             xfree (rs->last_pass_packet);
1984           rs->last_pass_packet = pass_packet;
1985         }
1986       else
1987         xfree (pass_packet);
1988     }
1989 }
1990
1991 /* If 'QCatchSyscalls' is supported, tell the remote stub
1992    to report syscalls to GDB.  */
1993
1994 static int
1995 remote_set_syscall_catchpoint (struct target_ops *self,
1996                                int pid, int needed, int any_count,
1997                                int table_size, int *table)
1998 {
1999   char *catch_packet;
2000   enum packet_result result;
2001   int n_sysno = 0;
2002
2003   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2004     {
2005       /* Not supported.  */
2006       return 1;
2007     }
2008
2009   if (needed && !any_count)
2010     {
2011       int i;
2012
2013       /* Count how many syscalls are to be caught (table[sysno] != 0).  */
2014       for (i = 0; i < table_size; i++)
2015         {
2016           if (table[i] != 0)
2017             n_sysno++;
2018         }
2019     }
2020
2021   if (remote_debug)
2022     {
2023       fprintf_unfiltered (gdb_stdlog,
2024                           "remote_set_syscall_catchpoint "
2025                           "pid %d needed %d any_count %d n_sysno %d\n",
2026                           pid, needed, any_count, n_sysno);
2027     }
2028
2029   if (needed)
2030     {
2031       /* Prepare a packet with the sysno list, assuming max 8+1
2032          characters for a sysno.  If the resulting packet size is too
2033          big, fallback on the non-selective packet.  */
2034       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2035
2036       catch_packet = xmalloc (maxpktsz);
2037       strcpy (catch_packet, "QCatchSyscalls:1");
2038       if (!any_count)
2039         {
2040           int i;
2041           char *p;
2042
2043           p = catch_packet;
2044           p += strlen (p);
2045
2046           /* Add in catch_packet each syscall to be caught (table[i] != 0).  */
2047           for (i = 0; i < table_size; i++)
2048             {
2049               if (table[i] != 0)
2050                 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2051             }
2052         }
2053       if (strlen (catch_packet) > get_remote_packet_size ())
2054         {
2055           /* catch_packet too big.  Fallback to less efficient
2056              non selective mode, with GDB doing the filtering.  */
2057           catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2058         }
2059     }
2060   else
2061     catch_packet = xstrdup ("QCatchSyscalls:0");
2062
2063   {
2064     struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2065     struct remote_state *rs = get_remote_state ();
2066
2067     putpkt (catch_packet);
2068     getpkt (&rs->buf, &rs->buf_size, 0);
2069     result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2070     do_cleanups (old_chain);
2071     if (result == PACKET_OK)
2072       return 0;
2073     else
2074       return -1;
2075   }
2076 }
2077
2078 /* If 'QProgramSignals' is supported, tell the remote stub what
2079    signals it should pass through to the inferior when detaching.  */
2080
2081 static void
2082 remote_program_signals (struct target_ops *self,
2083                         int numsigs, unsigned char *signals)
2084 {
2085   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2086     {
2087       char *packet, *p;
2088       int count = 0, i;
2089       struct remote_state *rs = get_remote_state ();
2090
2091       gdb_assert (numsigs < 256);
2092       for (i = 0; i < numsigs; i++)
2093         {
2094           if (signals[i])
2095             count++;
2096         }
2097       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2098       strcpy (packet, "QProgramSignals:");
2099       p = packet + strlen (packet);
2100       for (i = 0; i < numsigs; i++)
2101         {
2102           if (signal_pass_state (i))
2103             {
2104               if (i >= 16)
2105                 *p++ = tohex (i >> 4);
2106               *p++ = tohex (i & 15);
2107               if (count)
2108                 *p++ = ';';
2109               else
2110                 break;
2111               count--;
2112             }
2113         }
2114       *p = 0;
2115       if (!rs->last_program_signals_packet
2116           || strcmp (rs->last_program_signals_packet, packet) != 0)
2117         {
2118           putpkt (packet);
2119           getpkt (&rs->buf, &rs->buf_size, 0);
2120           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2121           xfree (rs->last_program_signals_packet);
2122           rs->last_program_signals_packet = packet;
2123         }
2124       else
2125         xfree (packet);
2126     }
2127 }
2128
2129 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2130    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2131    thread.  If GEN is set, set the general thread, if not, then set
2132    the step/continue thread.  */
2133 static void
2134 set_thread (struct ptid ptid, int gen)
2135 {
2136   struct remote_state *rs = get_remote_state ();
2137   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2138   char *buf = rs->buf;
2139   char *endbuf = rs->buf + get_remote_packet_size ();
2140
2141   if (ptid_equal (state, ptid))
2142     return;
2143
2144   *buf++ = 'H';
2145   *buf++ = gen ? 'g' : 'c';
2146   if (ptid_equal (ptid, magic_null_ptid))
2147     xsnprintf (buf, endbuf - buf, "0");
2148   else if (ptid_equal (ptid, any_thread_ptid))
2149     xsnprintf (buf, endbuf - buf, "0");
2150   else if (ptid_equal (ptid, minus_one_ptid))
2151     xsnprintf (buf, endbuf - buf, "-1");
2152   else
2153     write_ptid (buf, endbuf, ptid);
2154   putpkt (rs->buf);
2155   getpkt (&rs->buf, &rs->buf_size, 0);
2156   if (gen)
2157     rs->general_thread = ptid;
2158   else
2159     rs->continue_thread = ptid;
2160 }
2161
2162 static void
2163 set_general_thread (struct ptid ptid)
2164 {
2165   set_thread (ptid, 1);
2166 }
2167
2168 static void
2169 set_continue_thread (struct ptid ptid)
2170 {
2171   set_thread (ptid, 0);
2172 }
2173
2174 /* Change the remote current process.  Which thread within the process
2175    ends up selected isn't important, as long as it is the same process
2176    as what INFERIOR_PTID points to.
2177
2178    This comes from that fact that there is no explicit notion of
2179    "selected process" in the protocol.  The selected process for
2180    general operations is the process the selected general thread
2181    belongs to.  */
2182
2183 static void
2184 set_general_process (void)
2185 {
2186   struct remote_state *rs = get_remote_state ();
2187
2188   /* If the remote can't handle multiple processes, don't bother.  */
2189   if (!remote_multi_process_p (rs))
2190     return;
2191
2192   /* We only need to change the remote current thread if it's pointing
2193      at some other process.  */
2194   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2195     set_general_thread (inferior_ptid);
2196 }
2197
2198 \f
2199 /* Return nonzero if this is the main thread that we made up ourselves
2200    to model non-threaded targets as single-threaded.  */
2201
2202 static int
2203 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2204 {
2205   struct remote_state *rs = get_remote_state ();
2206   char *p, *endp;
2207
2208   if (ptid_equal (ptid, magic_null_ptid))
2209     /* The main thread is always alive.  */
2210     return 1;
2211
2212   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2213     /* The main thread is always alive.  This can happen after a
2214        vAttach, if the remote side doesn't support
2215        multi-threading.  */
2216     return 1;
2217
2218   return 0;
2219 }
2220
2221 /* Return nonzero if the thread PTID is still alive on the remote
2222    system.  */
2223
2224 static int
2225 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2226 {
2227   struct remote_state *rs = get_remote_state ();
2228   char *p, *endp;
2229
2230   /* Check if this is a thread that we made up ourselves to model
2231      non-threaded targets as single-threaded.  */
2232   if (remote_thread_always_alive (ops, ptid))
2233     return 1;
2234
2235   p = rs->buf;
2236   endp = rs->buf + get_remote_packet_size ();
2237
2238   *p++ = 'T';
2239   write_ptid (p, endp, ptid);
2240
2241   putpkt (rs->buf);
2242   getpkt (&rs->buf, &rs->buf_size, 0);
2243   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2244 }
2245
2246 /* Return a pointer to a thread name if we know it and NULL otherwise.
2247    The thread_info object owns the memory for the name.  */
2248
2249 static const char *
2250 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2251 {
2252   if (info->priv != NULL)
2253     return info->priv->name;
2254
2255   return NULL;
2256 }
2257
2258 /* About these extended threadlist and threadinfo packets.  They are
2259    variable length packets but, the fields within them are often fixed
2260    length.  They are redundent enough to send over UDP as is the
2261    remote protocol in general.  There is a matching unit test module
2262    in libstub.  */
2263
2264 /* WARNING: This threadref data structure comes from the remote O.S.,
2265    libstub protocol encoding, and remote.c.  It is not particularly
2266    changable.  */
2267
2268 /* Right now, the internal structure is int. We want it to be bigger.
2269    Plan to fix this.  */
2270
2271 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2272
2273 /* gdb_ext_thread_info is an internal GDB data structure which is
2274    equivalent to the reply of the remote threadinfo packet.  */
2275
2276 struct gdb_ext_thread_info
2277   {
2278     threadref threadid;         /* External form of thread reference.  */
2279     int active;                 /* Has state interesting to GDB?
2280                                    regs, stack.  */
2281     char display[256];          /* Brief state display, name,
2282                                    blocked/suspended.  */
2283     char shortname[32];         /* To be used to name threads.  */
2284     char more_display[256];     /* Long info, statistics, queue depth,
2285                                    whatever.  */
2286   };
2287
2288 /* The volume of remote transfers can be limited by submitting
2289    a mask containing bits specifying the desired information.
2290    Use a union of these values as the 'selection' parameter to
2291    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2292
2293 #define TAG_THREADID 1
2294 #define TAG_EXISTS 2
2295 #define TAG_DISPLAY 4
2296 #define TAG_THREADNAME 8
2297 #define TAG_MOREDISPLAY 16
2298
2299 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2300
2301 static char *unpack_nibble (char *buf, int *val);
2302
2303 static char *unpack_byte (char *buf, int *value);
2304
2305 static char *pack_int (char *buf, int value);
2306
2307 static char *unpack_int (char *buf, int *value);
2308
2309 static char *unpack_string (char *src, char *dest, int length);
2310
2311 static char *pack_threadid (char *pkt, threadref *id);
2312
2313 static char *unpack_threadid (char *inbuf, threadref *id);
2314
2315 void int_to_threadref (threadref *id, int value);
2316
2317 static int threadref_to_int (threadref *ref);
2318
2319 static void copy_threadref (threadref *dest, threadref *src);
2320
2321 static int threadmatch (threadref *dest, threadref *src);
2322
2323 static char *pack_threadinfo_request (char *pkt, int mode,
2324                                       threadref *id);
2325
2326 static int remote_unpack_thread_info_response (char *pkt,
2327                                                threadref *expectedref,
2328                                                struct gdb_ext_thread_info
2329                                                *info);
2330
2331
2332 static int remote_get_threadinfo (threadref *threadid,
2333                                   int fieldset, /*TAG mask */
2334                                   struct gdb_ext_thread_info *info);
2335
2336 static char *pack_threadlist_request (char *pkt, int startflag,
2337                                       int threadcount,
2338                                       threadref *nextthread);
2339
2340 static int parse_threadlist_response (char *pkt,
2341                                       int result_limit,
2342                                       threadref *original_echo,
2343                                       threadref *resultlist,
2344                                       int *doneflag);
2345
2346 static int remote_get_threadlist (int startflag,
2347                                   threadref *nextthread,
2348                                   int result_limit,
2349                                   int *done,
2350                                   int *result_count,
2351                                   threadref *threadlist);
2352
2353 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2354
2355 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2356                                        void *context, int looplimit);
2357
2358 static int remote_newthread_step (threadref *ref, void *context);
2359
2360
2361 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2362    buffer we're allowed to write to.  Returns
2363    BUF+CHARACTERS_WRITTEN.  */
2364
2365 static char *
2366 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2367 {
2368   int pid, tid;
2369   struct remote_state *rs = get_remote_state ();
2370
2371   if (remote_multi_process_p (rs))
2372     {
2373       pid = ptid_get_pid (ptid);
2374       if (pid < 0)
2375         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2376       else
2377         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2378     }
2379   tid = ptid_get_lwp (ptid);
2380   if (tid < 0)
2381     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2382   else
2383     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2384
2385   return buf;
2386 }
2387
2388 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
2389    passed the last parsed char.  Returns null_ptid on error.  */
2390
2391 static ptid_t
2392 read_ptid (char *buf, char **obuf)
2393 {
2394   char *p = buf;
2395   char *pp;
2396   ULONGEST pid = 0, tid = 0;
2397
2398   if (*p == 'p')
2399     {
2400       /* Multi-process ptid.  */
2401       pp = unpack_varlen_hex (p + 1, &pid);
2402       if (*pp != '.')
2403         error (_("invalid remote ptid: %s"), p);
2404
2405       p = pp;
2406       pp = unpack_varlen_hex (p + 1, &tid);
2407       if (obuf)
2408         *obuf = pp;
2409       return ptid_build (pid, tid, 0);
2410     }
2411
2412   /* No multi-process.  Just a tid.  */
2413   pp = unpack_varlen_hex (p, &tid);
2414
2415   /* Return null_ptid when no thread id is found.  */
2416   if (p == pp)
2417     {
2418       if (obuf)
2419         *obuf = pp;
2420       return null_ptid;
2421     }
2422
2423   /* Since the stub is not sending a process id, then default to
2424      what's in inferior_ptid, unless it's null at this point.  If so,
2425      then since there's no way to know the pid of the reported
2426      threads, use the magic number.  */
2427   if (ptid_equal (inferior_ptid, null_ptid))
2428     pid = ptid_get_pid (magic_null_ptid);
2429   else
2430     pid = ptid_get_pid (inferior_ptid);
2431
2432   if (obuf)
2433     *obuf = pp;
2434   return ptid_build (pid, tid, 0);
2435 }
2436
2437 static int
2438 stubhex (int ch)
2439 {
2440   if (ch >= 'a' && ch <= 'f')
2441     return ch - 'a' + 10;
2442   if (ch >= '0' && ch <= '9')
2443     return ch - '0';
2444   if (ch >= 'A' && ch <= 'F')
2445     return ch - 'A' + 10;
2446   return -1;
2447 }
2448
2449 static int
2450 stub_unpack_int (char *buff, int fieldlength)
2451 {
2452   int nibble;
2453   int retval = 0;
2454
2455   while (fieldlength)
2456     {
2457       nibble = stubhex (*buff++);
2458       retval |= nibble;
2459       fieldlength--;
2460       if (fieldlength)
2461         retval = retval << 4;
2462     }
2463   return retval;
2464 }
2465
2466 static char *
2467 unpack_nibble (char *buf, int *val)
2468 {
2469   *val = fromhex (*buf++);
2470   return buf;
2471 }
2472
2473 static char *
2474 unpack_byte (char *buf, int *value)
2475 {
2476   *value = stub_unpack_int (buf, 2);
2477   return buf + 2;
2478 }
2479
2480 static char *
2481 pack_int (char *buf, int value)
2482 {
2483   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2484   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2485   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2486   buf = pack_hex_byte (buf, (value & 0xff));
2487   return buf;
2488 }
2489
2490 static char *
2491 unpack_int (char *buf, int *value)
2492 {
2493   *value = stub_unpack_int (buf, 8);
2494   return buf + 8;
2495 }
2496
2497 #if 0                   /* Currently unused, uncomment when needed.  */
2498 static char *pack_string (char *pkt, char *string);
2499
2500 static char *
2501 pack_string (char *pkt, char *string)
2502 {
2503   char ch;
2504   int len;
2505
2506   len = strlen (string);
2507   if (len > 200)
2508     len = 200;          /* Bigger than most GDB packets, junk???  */
2509   pkt = pack_hex_byte (pkt, len);
2510   while (len-- > 0)
2511     {
2512       ch = *string++;
2513       if ((ch == '\0') || (ch == '#'))
2514         ch = '*';               /* Protect encapsulation.  */
2515       *pkt++ = ch;
2516     }
2517   return pkt;
2518 }
2519 #endif /* 0 (unused) */
2520
2521 static char *
2522 unpack_string (char *src, char *dest, int length)
2523 {
2524   while (length--)
2525     *dest++ = *src++;
2526   *dest = '\0';
2527   return src;
2528 }
2529
2530 static char *
2531 pack_threadid (char *pkt, threadref *id)
2532 {
2533   char *limit;
2534   unsigned char *altid;
2535
2536   altid = (unsigned char *) id;
2537   limit = pkt + BUF_THREAD_ID_SIZE;
2538   while (pkt < limit)
2539     pkt = pack_hex_byte (pkt, *altid++);
2540   return pkt;
2541 }
2542
2543
2544 static char *
2545 unpack_threadid (char *inbuf, threadref *id)
2546 {
2547   char *altref;
2548   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2549   int x, y;
2550
2551   altref = (char *) id;
2552
2553   while (inbuf < limit)
2554     {
2555       x = stubhex (*inbuf++);
2556       y = stubhex (*inbuf++);
2557       *altref++ = (x << 4) | y;
2558     }
2559   return inbuf;
2560 }
2561
2562 /* Externally, threadrefs are 64 bits but internally, they are still
2563    ints.  This is due to a mismatch of specifications.  We would like
2564    to use 64bit thread references internally.  This is an adapter
2565    function.  */
2566
2567 void
2568 int_to_threadref (threadref *id, int value)
2569 {
2570   unsigned char *scan;
2571
2572   scan = (unsigned char *) id;
2573   {
2574     int i = 4;
2575     while (i--)
2576       *scan++ = 0;
2577   }
2578   *scan++ = (value >> 24) & 0xff;
2579   *scan++ = (value >> 16) & 0xff;
2580   *scan++ = (value >> 8) & 0xff;
2581   *scan++ = (value & 0xff);
2582 }
2583
2584 static int
2585 threadref_to_int (threadref *ref)
2586 {
2587   int i, value = 0;
2588   unsigned char *scan;
2589
2590   scan = *ref;
2591   scan += 4;
2592   i = 4;
2593   while (i-- > 0)
2594     value = (value << 8) | ((*scan++) & 0xff);
2595   return value;
2596 }
2597
2598 static void
2599 copy_threadref (threadref *dest, threadref *src)
2600 {
2601   int i;
2602   unsigned char *csrc, *cdest;
2603
2604   csrc = (unsigned char *) src;
2605   cdest = (unsigned char *) dest;
2606   i = 8;
2607   while (i--)
2608     *cdest++ = *csrc++;
2609 }
2610
2611 static int
2612 threadmatch (threadref *dest, threadref *src)
2613 {
2614   /* Things are broken right now, so just assume we got a match.  */
2615 #if 0
2616   unsigned char *srcp, *destp;
2617   int i, result;
2618   srcp = (char *) src;
2619   destp = (char *) dest;
2620
2621   result = 1;
2622   while (i-- > 0)
2623     result &= (*srcp++ == *destp++) ? 1 : 0;
2624   return result;
2625 #endif
2626   return 1;
2627 }
2628
2629 /*
2630    threadid:1,        # always request threadid
2631    context_exists:2,
2632    display:4,
2633    unique_name:8,
2634    more_display:16
2635  */
2636
2637 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2638
2639 static char *
2640 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2641 {
2642   *pkt++ = 'q';                         /* Info Query */
2643   *pkt++ = 'P';                         /* process or thread info */
2644   pkt = pack_int (pkt, mode);           /* mode */
2645   pkt = pack_threadid (pkt, id);        /* threadid */
2646   *pkt = '\0';                          /* terminate */
2647   return pkt;
2648 }
2649
2650 /* These values tag the fields in a thread info response packet.  */
2651 /* Tagging the fields allows us to request specific fields and to
2652    add more fields as time goes by.  */
2653
2654 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2655 #define TAG_EXISTS 2            /* Is this process defined enough to
2656                                    fetch registers and its stack?  */
2657 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2658 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2659 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2660                                    the process.  */
2661
2662 static int
2663 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2664                                     struct gdb_ext_thread_info *info)
2665 {
2666   struct remote_state *rs = get_remote_state ();
2667   int mask, length;
2668   int tag;
2669   threadref ref;
2670   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2671   int retval = 1;
2672
2673   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2674   info->active = 0;
2675   info->display[0] = '\0';
2676   info->shortname[0] = '\0';
2677   info->more_display[0] = '\0';
2678
2679   /* Assume the characters indicating the packet type have been
2680      stripped.  */
2681   pkt = unpack_int (pkt, &mask);        /* arg mask */
2682   pkt = unpack_threadid (pkt, &ref);
2683
2684   if (mask == 0)
2685     warning (_("Incomplete response to threadinfo request."));
2686   if (!threadmatch (&ref, expectedref))
2687     {                   /* This is an answer to a different request.  */
2688       warning (_("ERROR RMT Thread info mismatch."));
2689       return 0;
2690     }
2691   copy_threadref (&info->threadid, &ref);
2692
2693   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
2694
2695   /* Packets are terminated with nulls.  */
2696   while ((pkt < limit) && mask && *pkt)
2697     {
2698       pkt = unpack_int (pkt, &tag);     /* tag */
2699       pkt = unpack_byte (pkt, &length); /* length */
2700       if (!(tag & mask))                /* Tags out of synch with mask.  */
2701         {
2702           warning (_("ERROR RMT: threadinfo tag mismatch."));
2703           retval = 0;
2704           break;
2705         }
2706       if (tag == TAG_THREADID)
2707         {
2708           if (length != 16)
2709             {
2710               warning (_("ERROR RMT: length of threadid is not 16."));
2711               retval = 0;
2712               break;
2713             }
2714           pkt = unpack_threadid (pkt, &ref);
2715           mask = mask & ~TAG_THREADID;
2716           continue;
2717         }
2718       if (tag == TAG_EXISTS)
2719         {
2720           info->active = stub_unpack_int (pkt, length);
2721           pkt += length;
2722           mask = mask & ~(TAG_EXISTS);
2723           if (length > 8)
2724             {
2725               warning (_("ERROR RMT: 'exists' length too long."));
2726               retval = 0;
2727               break;
2728             }
2729           continue;
2730         }
2731       if (tag == TAG_THREADNAME)
2732         {
2733           pkt = unpack_string (pkt, &info->shortname[0], length);
2734           mask = mask & ~TAG_THREADNAME;
2735           continue;
2736         }
2737       if (tag == TAG_DISPLAY)
2738         {
2739           pkt = unpack_string (pkt, &info->display[0], length);
2740           mask = mask & ~TAG_DISPLAY;
2741           continue;
2742         }
2743       if (tag == TAG_MOREDISPLAY)
2744         {
2745           pkt = unpack_string (pkt, &info->more_display[0], length);
2746           mask = mask & ~TAG_MOREDISPLAY;
2747           continue;
2748         }
2749       warning (_("ERROR RMT: unknown thread info tag."));
2750       break;                    /* Not a tag we know about.  */
2751     }
2752   return retval;
2753 }
2754
2755 static int
2756 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2757                        struct gdb_ext_thread_info *info)
2758 {
2759   struct remote_state *rs = get_remote_state ();
2760   int result;
2761
2762   pack_threadinfo_request (rs->buf, fieldset, threadid);
2763   putpkt (rs->buf);
2764   getpkt (&rs->buf, &rs->buf_size, 0);
2765
2766   if (rs->buf[0] == '\0')
2767     return 0;
2768
2769   result = remote_unpack_thread_info_response (rs->buf + 2,
2770                                                threadid, info);
2771   return result;
2772 }
2773
2774 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2775
2776 static char *
2777 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2778                          threadref *nextthread)
2779 {
2780   *pkt++ = 'q';                 /* info query packet */
2781   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2782   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2783   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2784   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2785   *pkt = '\0';
2786   return pkt;
2787 }
2788
2789 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2790
2791 static int
2792 parse_threadlist_response (char *pkt, int result_limit,
2793                            threadref *original_echo, threadref *resultlist,
2794                            int *doneflag)
2795 {
2796   struct remote_state *rs = get_remote_state ();
2797   char *limit;
2798   int count, resultcount, done;
2799
2800   resultcount = 0;
2801   /* Assume the 'q' and 'M chars have been stripped.  */
2802   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2803   /* done parse past here */
2804   pkt = unpack_byte (pkt, &count);      /* count field */
2805   pkt = unpack_nibble (pkt, &done);
2806   /* The first threadid is the argument threadid.  */
2807   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2808   while ((count-- > 0) && (pkt < limit))
2809     {
2810       pkt = unpack_threadid (pkt, resultlist++);
2811       if (resultcount++ >= result_limit)
2812         break;
2813     }
2814   if (doneflag)
2815     *doneflag = done;
2816   return resultcount;
2817 }
2818
2819 /* Fetch the next batch of threads from the remote.  Returns -1 if the
2820    qL packet is not supported, 0 on error and 1 on success.  */
2821
2822 static int
2823 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2824                        int *done, int *result_count, threadref *threadlist)
2825 {
2826   struct remote_state *rs = get_remote_state ();
2827   int result = 1;
2828
2829   /* Trancate result limit to be smaller than the packet size.  */
2830   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2831       >= get_remote_packet_size ())
2832     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2833
2834   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2835   putpkt (rs->buf);
2836   getpkt (&rs->buf, &rs->buf_size, 0);
2837   if (*rs->buf == '\0')
2838     {
2839       /* Packet not supported.  */
2840       return -1;
2841     }
2842
2843   *result_count =
2844     parse_threadlist_response (rs->buf + 2, result_limit,
2845                                &rs->echo_nextthread, threadlist, done);
2846
2847   if (!threadmatch (&rs->echo_nextthread, nextthread))
2848     {
2849       /* FIXME: This is a good reason to drop the packet.  */
2850       /* Possably, there is a duplicate response.  */
2851       /* Possabilities :
2852          retransmit immediatly - race conditions
2853          retransmit after timeout - yes
2854          exit
2855          wait for packet, then exit
2856        */
2857       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2858       return 0;                 /* I choose simply exiting.  */
2859     }
2860   if (*result_count <= 0)
2861     {
2862       if (*done != 1)
2863         {
2864           warning (_("RMT ERROR : failed to get remote thread list."));
2865           result = 0;
2866         }
2867       return result;            /* break; */
2868     }
2869   if (*result_count > result_limit)
2870     {
2871       *result_count = 0;
2872       warning (_("RMT ERROR: threadlist response longer than requested."));
2873       return 0;
2874     }
2875   return result;
2876 }
2877
2878 /* Fetch the list of remote threads, with the qL packet, and call
2879    STEPFUNCTION for each thread found.  Stops iterating and returns 1
2880    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
2881    STEPFUNCTION returns false.  If the packet is not supported,
2882    returns -1.  */
2883
2884 static int
2885 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2886                             int looplimit)
2887 {
2888   struct remote_state *rs = get_remote_state ();
2889   int done, i, result_count;
2890   int startflag = 1;
2891   int result = 1;
2892   int loopcount = 0;
2893
2894   done = 0;
2895   while (!done)
2896     {
2897       if (loopcount++ > looplimit)
2898         {
2899           result = 0;
2900           warning (_("Remote fetch threadlist -infinite loop-."));
2901           break;
2902         }
2903       result = remote_get_threadlist (startflag, &rs->nextthread,
2904                                       MAXTHREADLISTRESULTS,
2905                                       &done, &result_count,
2906                                       rs->resultthreadlist);
2907       if (result <= 0)
2908         break;
2909       /* Clear for later iterations.  */
2910       startflag = 0;
2911       /* Setup to resume next batch of thread references, set nextthread.  */
2912       if (result_count >= 1)
2913         copy_threadref (&rs->nextthread,
2914                         &rs->resultthreadlist[result_count - 1]);
2915       i = 0;
2916       while (result_count--)
2917         {
2918           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2919             {
2920               result = 0;
2921               break;
2922             }
2923         }
2924     }
2925   return result;
2926 }
2927
2928 /* A thread found on the remote target.  */
2929
2930 typedef struct thread_item
2931 {
2932   /* The thread's PTID.  */
2933   ptid_t ptid;
2934
2935   /* The thread's extra info.  May be NULL.  */
2936   char *extra;
2937
2938   /* The thread's name.  May be NULL.  */
2939   char *name;
2940
2941   /* The core the thread was running on.  -1 if not known.  */
2942   int core;
2943 } thread_item_t;
2944 DEF_VEC_O(thread_item_t);
2945
2946 /* Context passed around to the various methods listing remote
2947    threads.  As new threads are found, they're added to the ITEMS
2948    vector.  */
2949
2950 struct threads_listing_context
2951 {
2952   /* The threads found on the remote target.  */
2953   VEC (thread_item_t) *items;
2954 };
2955
2956 /* Discard the contents of the constructed thread listing context.  */
2957
2958 static void
2959 clear_threads_listing_context (void *p)
2960 {
2961   struct threads_listing_context *context
2962     = (struct threads_listing_context *) p;
2963   int i;
2964   struct thread_item *item;
2965
2966   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2967     {
2968       xfree (item->extra);
2969       xfree (item->name);
2970     }
2971
2972   VEC_free (thread_item_t, context->items);
2973 }
2974
2975 /* Remove the thread specified as the related_pid field of WS
2976    from the CONTEXT list.  */
2977
2978 static void
2979 threads_listing_context_remove (struct target_waitstatus *ws,
2980                                 struct threads_listing_context *context)
2981 {
2982   struct thread_item *item;
2983   int i;
2984   ptid_t child_ptid = ws->value.related_pid;
2985
2986   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2987     {
2988       if (ptid_equal (item->ptid, child_ptid))
2989         {
2990           VEC_ordered_remove (thread_item_t, context->items, i);
2991           break;
2992         }
2993     }
2994 }
2995
2996 static int
2997 remote_newthread_step (threadref *ref, void *data)
2998 {
2999   struct threads_listing_context *context
3000     = (struct threads_listing_context *) data;
3001   struct thread_item item;
3002   int pid = ptid_get_pid (inferior_ptid);
3003
3004   item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3005   item.core = -1;
3006   item.name = NULL;
3007   item.extra = NULL;
3008
3009   VEC_safe_push (thread_item_t, context->items, &item);
3010
3011   return 1;                     /* continue iterator */
3012 }
3013
3014 #define CRAZY_MAX_THREADS 1000
3015
3016 static ptid_t
3017 remote_current_thread (ptid_t oldpid)
3018 {
3019   struct remote_state *rs = get_remote_state ();
3020
3021   putpkt ("qC");
3022   getpkt (&rs->buf, &rs->buf_size, 0);
3023   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3024     {
3025       char *obuf;
3026       ptid_t result;
3027
3028       result = read_ptid (&rs->buf[2], &obuf);
3029       if (*obuf != '\0' && remote_debug)
3030         fprintf_unfiltered (gdb_stdlog,
3031                             "warning: garbage in qC reply\n");
3032
3033       return result;
3034     }
3035   else
3036     return oldpid;
3037 }
3038
3039 /* List remote threads using the deprecated qL packet.  */
3040
3041 static int
3042 remote_get_threads_with_ql (struct target_ops *ops,
3043                             struct threads_listing_context *context)
3044 {
3045   if (remote_threadlist_iterator (remote_newthread_step, context,
3046                                   CRAZY_MAX_THREADS) >= 0)
3047     return 1;
3048
3049   return 0;
3050 }
3051
3052 #if defined(HAVE_LIBEXPAT)
3053
3054 static void
3055 start_thread (struct gdb_xml_parser *parser,
3056               const struct gdb_xml_element *element,
3057               void *user_data, VEC(gdb_xml_value_s) *attributes)
3058 {
3059   struct threads_listing_context *data
3060     = (struct threads_listing_context *) user_data;
3061
3062   struct thread_item item;
3063   char *id;
3064   struct gdb_xml_value *attr;
3065
3066   id = (char *) xml_find_attribute (attributes, "id")->value;
3067   item.ptid = read_ptid (id, NULL);
3068
3069   attr = xml_find_attribute (attributes, "core");
3070   if (attr != NULL)
3071     item.core = *(ULONGEST *) attr->value;
3072   else
3073     item.core = -1;
3074
3075   attr = xml_find_attribute (attributes, "name");
3076   item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3077
3078   item.extra = 0;
3079
3080   VEC_safe_push (thread_item_t, data->items, &item);
3081 }
3082
3083 static void
3084 end_thread (struct gdb_xml_parser *parser,
3085             const struct gdb_xml_element *element,
3086             void *user_data, const char *body_text)
3087 {
3088   struct threads_listing_context *data
3089     = (struct threads_listing_context *) user_data;
3090
3091   if (body_text && *body_text)
3092     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3093 }
3094
3095 const struct gdb_xml_attribute thread_attributes[] = {
3096   { "id", GDB_XML_AF_NONE, NULL, NULL },
3097   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3098   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3099   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3100 };
3101
3102 const struct gdb_xml_element thread_children[] = {
3103   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3104 };
3105
3106 const struct gdb_xml_element threads_children[] = {
3107   { "thread", thread_attributes, thread_children,
3108     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3109     start_thread, end_thread },
3110   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3111 };
3112
3113 const struct gdb_xml_element threads_elements[] = {
3114   { "threads", NULL, threads_children,
3115     GDB_XML_EF_NONE, NULL, NULL },
3116   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3117 };
3118
3119 #endif
3120
3121 /* List remote threads using qXfer:threads:read.  */
3122
3123 static int
3124 remote_get_threads_with_qxfer (struct target_ops *ops,
3125                                struct threads_listing_context *context)
3126 {
3127 #if defined(HAVE_LIBEXPAT)
3128   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3129     {
3130       char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3131       struct cleanup *back_to = make_cleanup (xfree, xml);
3132
3133       if (xml != NULL && *xml != '\0')
3134         {
3135           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3136                                threads_elements, xml, context);
3137         }
3138
3139       do_cleanups (back_to);
3140       return 1;
3141     }
3142 #endif
3143
3144   return 0;
3145 }
3146
3147 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3148
3149 static int
3150 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3151                                      struct threads_listing_context *context)
3152 {
3153   struct remote_state *rs = get_remote_state ();
3154
3155   if (rs->use_threadinfo_query)
3156     {
3157       char *bufp;
3158
3159       putpkt ("qfThreadInfo");
3160       getpkt (&rs->buf, &rs->buf_size, 0);
3161       bufp = rs->buf;
3162       if (bufp[0] != '\0')              /* q packet recognized */
3163         {
3164           while (*bufp++ == 'm')        /* reply contains one or more TID */
3165             {
3166               do
3167                 {
3168                   struct thread_item item;
3169
3170                   item.ptid = read_ptid (bufp, &bufp);
3171                   item.core = -1;
3172                   item.name = NULL;
3173                   item.extra = NULL;
3174
3175                   VEC_safe_push (thread_item_t, context->items, &item);
3176                 }
3177               while (*bufp++ == ',');   /* comma-separated list */
3178               putpkt ("qsThreadInfo");
3179               getpkt (&rs->buf, &rs->buf_size, 0);
3180               bufp = rs->buf;
3181             }
3182           return 1;
3183         }
3184       else
3185         {
3186           /* Packet not recognized.  */
3187           rs->use_threadinfo_query = 0;
3188         }
3189     }
3190
3191   return 0;
3192 }
3193
3194 /* Implement the to_update_thread_list function for the remote
3195    targets.  */
3196
3197 static void
3198 remote_update_thread_list (struct target_ops *ops)
3199 {
3200   struct remote_state *rs = get_remote_state ();
3201   struct threads_listing_context context;
3202   struct cleanup *old_chain;
3203   int got_list = 0;
3204
3205   context.items = NULL;
3206   old_chain = make_cleanup (clear_threads_listing_context, &context);
3207
3208   /* We have a few different mechanisms to fetch the thread list.  Try
3209      them all, starting with the most preferred one first, falling
3210      back to older methods.  */
3211   if (remote_get_threads_with_qxfer (ops, &context)
3212       || remote_get_threads_with_qthreadinfo (ops, &context)
3213       || remote_get_threads_with_ql (ops, &context))
3214     {
3215       int i;
3216       struct thread_item *item;
3217       struct thread_info *tp, *tmp;
3218
3219       got_list = 1;
3220
3221       if (VEC_empty (thread_item_t, context.items)
3222           && remote_thread_always_alive (ops, inferior_ptid))
3223         {
3224           /* Some targets don't really support threads, but still
3225              reply an (empty) thread list in response to the thread
3226              listing packets, instead of replying "packet not
3227              supported".  Exit early so we don't delete the main
3228              thread.  */
3229           do_cleanups (old_chain);
3230           return;
3231         }
3232
3233       /* CONTEXT now holds the current thread list on the remote
3234          target end.  Delete GDB-side threads no longer found on the
3235          target.  */
3236       ALL_THREADS_SAFE (tp, tmp)
3237         {
3238           for (i = 0;
3239                VEC_iterate (thread_item_t, context.items, i, item);
3240                ++i)
3241             {
3242               if (ptid_equal (item->ptid, tp->ptid))
3243                 break;
3244             }
3245
3246           if (i == VEC_length (thread_item_t, context.items))
3247             {
3248               /* Not found.  */
3249               delete_thread (tp->ptid);
3250             }
3251         }
3252
3253       /* Remove any unreported fork child threads from CONTEXT so
3254          that we don't interfere with follow fork, which is where
3255          creation of such threads is handled.  */
3256       remove_new_fork_children (&context);
3257
3258       /* And now add threads we don't know about yet to our list.  */
3259       for (i = 0;
3260            VEC_iterate (thread_item_t, context.items, i, item);
3261            ++i)
3262         {
3263           if (!ptid_equal (item->ptid, null_ptid))
3264             {
3265               struct private_thread_info *info;
3266               /* In non-stop mode, we assume new found threads are
3267                  running until proven otherwise with a stop reply.  In
3268                  all-stop, we can only get here if all threads are
3269                  stopped.  */
3270               int running = target_is_non_stop_p () ? 1 : 0;
3271
3272               remote_notice_new_inferior (item->ptid, running);
3273
3274               info = demand_private_info (item->ptid);
3275               info->core = item->core;
3276               info->extra = item->extra;
3277               item->extra = NULL;
3278               info->name = item->name;
3279               item->name = NULL;
3280             }
3281         }
3282     }
3283
3284   if (!got_list)
3285     {
3286       /* If no thread listing method is supported, then query whether
3287          each known thread is alive, one by one, with the T packet.
3288          If the target doesn't support threads at all, then this is a
3289          no-op.  See remote_thread_alive.  */
3290       prune_threads ();
3291     }
3292
3293   do_cleanups (old_chain);
3294 }
3295
3296 /*
3297  * Collect a descriptive string about the given thread.
3298  * The target may say anything it wants to about the thread
3299  * (typically info about its blocked / runnable state, name, etc.).
3300  * This string will appear in the info threads display.
3301  *
3302  * Optional: targets are not required to implement this function.
3303  */
3304
3305 static char *
3306 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3307 {
3308   struct remote_state *rs = get_remote_state ();
3309   int result;
3310   int set;
3311   threadref id;
3312   struct gdb_ext_thread_info threadinfo;
3313   static char display_buf[100]; /* arbitrary...  */
3314   int n = 0;                    /* position in display_buf */
3315
3316   if (rs->remote_desc == 0)             /* paranoia */
3317     internal_error (__FILE__, __LINE__,
3318                     _("remote_threads_extra_info"));
3319
3320   if (ptid_equal (tp->ptid, magic_null_ptid)
3321       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3322     /* This is the main thread which was added by GDB.  The remote
3323        server doesn't know about it.  */
3324     return NULL;
3325
3326   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3327     {
3328       struct thread_info *info = find_thread_ptid (tp->ptid);
3329
3330       if (info && info->priv)
3331         return info->priv->extra;
3332       else
3333         return NULL;
3334     }
3335
3336   if (rs->use_threadextra_query)
3337     {
3338       char *b = rs->buf;
3339       char *endb = rs->buf + get_remote_packet_size ();
3340
3341       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3342       b += strlen (b);
3343       write_ptid (b, endb, tp->ptid);
3344
3345       putpkt (rs->buf);
3346       getpkt (&rs->buf, &rs->buf_size, 0);
3347       if (rs->buf[0] != 0)
3348         {
3349           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3350           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3351           display_buf [result] = '\0';
3352           return display_buf;
3353         }
3354     }
3355
3356   /* If the above query fails, fall back to the old method.  */
3357   rs->use_threadextra_query = 0;
3358   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3359     | TAG_MOREDISPLAY | TAG_DISPLAY;
3360   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3361   if (remote_get_threadinfo (&id, set, &threadinfo))
3362     if (threadinfo.active)
3363       {
3364         if (*threadinfo.shortname)
3365           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3366                           " Name: %s,", threadinfo.shortname);
3367         if (*threadinfo.display)
3368           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3369                           " State: %s,", threadinfo.display);
3370         if (*threadinfo.more_display)
3371           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3372                           " Priority: %s", threadinfo.more_display);
3373
3374         if (n > 0)
3375           {
3376             /* For purely cosmetic reasons, clear up trailing commas.  */
3377             if (',' == display_buf[n-1])
3378               display_buf[n-1] = ' ';
3379             return display_buf;
3380           }
3381       }
3382   return NULL;
3383 }
3384 \f
3385
3386 static int
3387 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3388                                     struct static_tracepoint_marker *marker)
3389 {
3390   struct remote_state *rs = get_remote_state ();
3391   char *p = rs->buf;
3392
3393   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3394   p += strlen (p);
3395   p += hexnumstr (p, addr);
3396   putpkt (rs->buf);
3397   getpkt (&rs->buf, &rs->buf_size, 0);
3398   p = rs->buf;
3399
3400   if (*p == 'E')
3401     error (_("Remote failure reply: %s"), p);
3402
3403   if (*p++ == 'm')
3404     {
3405       parse_static_tracepoint_marker_definition (p, &p, marker);
3406       return 1;
3407     }
3408
3409   return 0;
3410 }
3411
3412 static VEC(static_tracepoint_marker_p) *
3413 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3414                                            const char *strid)
3415 {
3416   struct remote_state *rs = get_remote_state ();
3417   VEC(static_tracepoint_marker_p) *markers = NULL;
3418   struct static_tracepoint_marker *marker = NULL;
3419   struct cleanup *old_chain;
3420   char *p;
3421
3422   /* Ask for a first packet of static tracepoint marker
3423      definition.  */
3424   putpkt ("qTfSTM");
3425   getpkt (&rs->buf, &rs->buf_size, 0);
3426   p = rs->buf;
3427   if (*p == 'E')
3428     error (_("Remote failure reply: %s"), p);
3429
3430   old_chain = make_cleanup (free_current_marker, &marker);
3431
3432   while (*p++ == 'm')
3433     {
3434       if (marker == NULL)
3435         marker = XCNEW (struct static_tracepoint_marker);
3436
3437       do
3438         {
3439           parse_static_tracepoint_marker_definition (p, &p, marker);
3440
3441           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3442             {
3443               VEC_safe_push (static_tracepoint_marker_p,
3444                              markers, marker);
3445               marker = NULL;
3446             }
3447           else
3448             {
3449               release_static_tracepoint_marker (marker);
3450               memset (marker, 0, sizeof (*marker));
3451             }
3452         }
3453       while (*p++ == ',');      /* comma-separated list */
3454       /* Ask for another packet of static tracepoint definition.  */
3455       putpkt ("qTsSTM");
3456       getpkt (&rs->buf, &rs->buf_size, 0);
3457       p = rs->buf;
3458     }
3459
3460   do_cleanups (old_chain);
3461   return markers;
3462 }
3463
3464 \f
3465 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3466
3467 static ptid_t
3468 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3469 {
3470   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3471 }
3472 \f
3473
3474 /* Restart the remote side; this is an extended protocol operation.  */
3475
3476 static void
3477 extended_remote_restart (void)
3478 {
3479   struct remote_state *rs = get_remote_state ();
3480
3481   /* Send the restart command; for reasons I don't understand the
3482      remote side really expects a number after the "R".  */
3483   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3484   putpkt (rs->buf);
3485
3486   remote_fileio_reset ();
3487 }
3488 \f
3489 /* Clean up connection to a remote debugger.  */
3490
3491 static void
3492 remote_close (struct target_ops *self)
3493 {
3494   struct remote_state *rs = get_remote_state ();
3495
3496   if (rs->remote_desc == NULL)
3497     return; /* already closed */
3498
3499   /* Make sure we leave stdin registered in the event loop, and we
3500      don't leave the async SIGINT signal handler installed.  */
3501   remote_terminal_ours (self);
3502
3503   serial_close (rs->remote_desc);
3504   rs->remote_desc = NULL;
3505
3506   /* We don't have a connection to the remote stub anymore.  Get rid
3507      of all the inferiors and their threads we were controlling.
3508      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3509      will be unable to find the thread corresponding to (pid, 0, 0).  */
3510   inferior_ptid = null_ptid;
3511   discard_all_inferiors ();
3512
3513   /* We are closing the remote target, so we should discard
3514      everything of this target.  */
3515   discard_pending_stop_replies_in_queue (rs);
3516
3517   if (remote_async_inferior_event_token)
3518     delete_async_event_handler (&remote_async_inferior_event_token);
3519
3520   remote_notif_state_xfree (rs->notif_state);
3521
3522   trace_reset_local_state ();
3523 }
3524
3525 /* Query the remote side for the text, data and bss offsets.  */
3526
3527 static void
3528 get_offsets (void)
3529 {
3530   struct remote_state *rs = get_remote_state ();
3531   char *buf;
3532   char *ptr;
3533   int lose, num_segments = 0, do_sections, do_segments;
3534   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3535   struct section_offsets *offs;
3536   struct symfile_segment_data *data;
3537
3538   if (symfile_objfile == NULL)
3539     return;
3540
3541   putpkt ("qOffsets");
3542   getpkt (&rs->buf, &rs->buf_size, 0);
3543   buf = rs->buf;
3544
3545   if (buf[0] == '\000')
3546     return;                     /* Return silently.  Stub doesn't support
3547                                    this command.  */
3548   if (buf[0] == 'E')
3549     {
3550       warning (_("Remote failure reply: %s"), buf);
3551       return;
3552     }
3553
3554   /* Pick up each field in turn.  This used to be done with scanf, but
3555      scanf will make trouble if CORE_ADDR size doesn't match
3556      conversion directives correctly.  The following code will work
3557      with any size of CORE_ADDR.  */
3558   text_addr = data_addr = bss_addr = 0;
3559   ptr = buf;
3560   lose = 0;
3561
3562   if (startswith (ptr, "Text="))
3563     {
3564       ptr += 5;
3565       /* Don't use strtol, could lose on big values.  */
3566       while (*ptr && *ptr != ';')
3567         text_addr = (text_addr << 4) + fromhex (*ptr++);
3568
3569       if (startswith (ptr, ";Data="))
3570         {
3571           ptr += 6;
3572           while (*ptr && *ptr != ';')
3573             data_addr = (data_addr << 4) + fromhex (*ptr++);
3574         }
3575       else
3576         lose = 1;
3577
3578       if (!lose && startswith (ptr, ";Bss="))
3579         {
3580           ptr += 5;
3581           while (*ptr && *ptr != ';')
3582             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3583
3584           if (bss_addr != data_addr)
3585             warning (_("Target reported unsupported offsets: %s"), buf);
3586         }
3587       else
3588         lose = 1;
3589     }
3590   else if (startswith (ptr, "TextSeg="))
3591     {
3592       ptr += 8;
3593       /* Don't use strtol, could lose on big values.  */
3594       while (*ptr && *ptr != ';')
3595         text_addr = (text_addr << 4) + fromhex (*ptr++);
3596       num_segments = 1;
3597
3598       if (startswith (ptr, ";DataSeg="))
3599         {
3600           ptr += 9;
3601           while (*ptr && *ptr != ';')
3602             data_addr = (data_addr << 4) + fromhex (*ptr++);
3603           num_segments++;
3604         }
3605     }
3606   else
3607     lose = 1;
3608
3609   if (lose)
3610     error (_("Malformed response to offset query, %s"), buf);
3611   else if (*ptr != '\0')
3612     warning (_("Target reported unsupported offsets: %s"), buf);
3613
3614   offs = ((struct section_offsets *)
3615           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3616   memcpy (offs, symfile_objfile->section_offsets,
3617           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3618
3619   data = get_symfile_segment_data (symfile_objfile->obfd);
3620   do_segments = (data != NULL);
3621   do_sections = num_segments == 0;
3622
3623   if (num_segments > 0)
3624     {
3625       segments[0] = text_addr;
3626       segments[1] = data_addr;
3627     }
3628   /* If we have two segments, we can still try to relocate everything
3629      by assuming that the .text and .data offsets apply to the whole
3630      text and data segments.  Convert the offsets given in the packet
3631      to base addresses for symfile_map_offsets_to_segments.  */
3632   else if (data && data->num_segments == 2)
3633     {
3634       segments[0] = data->segment_bases[0] + text_addr;
3635       segments[1] = data->segment_bases[1] + data_addr;
3636       num_segments = 2;
3637     }
3638   /* If the object file has only one segment, assume that it is text
3639      rather than data; main programs with no writable data are rare,
3640      but programs with no code are useless.  Of course the code might
3641      have ended up in the data segment... to detect that we would need
3642      the permissions here.  */
3643   else if (data && data->num_segments == 1)
3644     {
3645       segments[0] = data->segment_bases[0] + text_addr;
3646       num_segments = 1;
3647     }
3648   /* There's no way to relocate by segment.  */
3649   else
3650     do_segments = 0;
3651
3652   if (do_segments)
3653     {
3654       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3655                                                  offs, num_segments, segments);
3656
3657       if (ret == 0 && !do_sections)
3658         error (_("Can not handle qOffsets TextSeg "
3659                  "response with this symbol file"));
3660
3661       if (ret > 0)
3662         do_sections = 0;
3663     }
3664
3665   if (data)
3666     free_symfile_segment_data (data);
3667
3668   if (do_sections)
3669     {
3670       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3671
3672       /* This is a temporary kludge to force data and bss to use the
3673          same offsets because that's what nlmconv does now.  The real
3674          solution requires changes to the stub and remote.c that I
3675          don't have time to do right now.  */
3676
3677       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3678       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3679     }
3680
3681   objfile_relocate (symfile_objfile, offs);
3682 }
3683
3684 /* Send interrupt_sequence to remote target.  */
3685 static void
3686 send_interrupt_sequence (void)
3687 {
3688   struct remote_state *rs = get_remote_state ();
3689
3690   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3691     remote_serial_write ("\x03", 1);
3692   else if (interrupt_sequence_mode == interrupt_sequence_break)
3693     serial_send_break (rs->remote_desc);
3694   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3695     {
3696       serial_send_break (rs->remote_desc);
3697       remote_serial_write ("g", 1);
3698     }
3699   else
3700     internal_error (__FILE__, __LINE__,
3701                     _("Invalid value for interrupt_sequence_mode: %s."),
3702                     interrupt_sequence_mode);
3703 }
3704
3705
3706 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3707    and extract the PTID.  Returns NULL_PTID if not found.  */
3708
3709 static ptid_t
3710 stop_reply_extract_thread (char *stop_reply)
3711 {
3712   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3713     {
3714       char *p;
3715
3716       /* Txx r:val ; r:val (...)  */
3717       p = &stop_reply[3];
3718
3719       /* Look for "register" named "thread".  */
3720       while (*p != '\0')
3721         {
3722           char *p1;
3723
3724           p1 = strchr (p, ':');
3725           if (p1 == NULL)
3726             return null_ptid;
3727
3728           if (strncmp (p, "thread", p1 - p) == 0)
3729             return read_ptid (++p1, &p);
3730
3731           p1 = strchr (p, ';');
3732           if (p1 == NULL)
3733             return null_ptid;
3734           p1++;
3735
3736           p = p1;
3737         }
3738     }
3739
3740   return null_ptid;
3741 }
3742
3743 /* Determine the remote side's current thread.  If we have a stop
3744    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3745    "thread" register we can extract the current thread from.  If not,
3746    ask the remote which is the current thread with qC.  The former
3747    method avoids a roundtrip.  */
3748
3749 static ptid_t
3750 get_current_thread (char *wait_status)
3751 {
3752   ptid_t ptid = null_ptid;
3753
3754   /* Note we don't use remote_parse_stop_reply as that makes use of
3755      the target architecture, which we haven't yet fully determined at
3756      this point.  */
3757   if (wait_status != NULL)
3758     ptid = stop_reply_extract_thread (wait_status);
3759   if (ptid_equal (ptid, null_ptid))
3760     ptid = remote_current_thread (inferior_ptid);
3761
3762   return ptid;
3763 }
3764
3765 /* Query the remote target for which is the current thread/process,
3766    add it to our tables, and update INFERIOR_PTID.  The caller is
3767    responsible for setting the state such that the remote end is ready
3768    to return the current thread.
3769
3770    This function is called after handling the '?' or 'vRun' packets,
3771    whose response is a stop reply from which we can also try
3772    extracting the thread.  If the target doesn't support the explicit
3773    qC query, we infer the current thread from that stop reply, passed
3774    in in WAIT_STATUS, which may be NULL.  */
3775
3776 static void
3777 add_current_inferior_and_thread (char *wait_status)
3778 {
3779   struct remote_state *rs = get_remote_state ();
3780   int fake_pid_p = 0;
3781   ptid_t ptid;
3782
3783   inferior_ptid = null_ptid;
3784
3785   /* Now, if we have thread information, update inferior_ptid.  */
3786   ptid = get_current_thread (wait_status);
3787
3788   if (!ptid_equal (ptid, null_ptid))
3789     {
3790       if (!remote_multi_process_p (rs))
3791         fake_pid_p = 1;
3792
3793       inferior_ptid = ptid;
3794     }
3795   else
3796     {
3797       /* Without this, some commands which require an active target
3798          (such as kill) won't work.  This variable serves (at least)
3799          double duty as both the pid of the target process (if it has
3800          such), and as a flag indicating that a target is active.  */
3801       inferior_ptid = magic_null_ptid;
3802       fake_pid_p = 1;
3803     }
3804
3805   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3806
3807   /* Add the main thread.  */
3808   add_thread_silent (inferior_ptid);
3809 }
3810
3811 /* Print info about a thread that was found already stopped on
3812    connection.  */
3813
3814 static void
3815 print_one_stopped_thread (struct thread_info *thread)
3816 {
3817   struct target_waitstatus *ws = &thread->suspend.waitstatus;
3818
3819   switch_to_thread (thread->ptid);
3820   stop_pc = get_frame_pc (get_current_frame ());
3821   set_current_sal_from_frame (get_current_frame ());
3822
3823   thread->suspend.waitstatus_pending_p = 0;
3824
3825   if (ws->kind == TARGET_WAITKIND_STOPPED)
3826     {
3827       enum gdb_signal sig = ws->value.sig;
3828
3829       if (signal_print_state (sig))
3830         observer_notify_signal_received (sig);
3831     }
3832   observer_notify_normal_stop (NULL, 1);
3833 }
3834
3835 /* Process all initial stop replies the remote side sent in response
3836    to the ? packet.  These indicate threads that were already stopped
3837    on initial connection.  We mark these threads as stopped and print
3838    their current frame before giving the user the prompt.  */
3839
3840 static void
3841 process_initial_stop_replies (int from_tty)
3842 {
3843   int pending_stop_replies = stop_reply_queue_length ();
3844   struct inferior *inf;
3845   struct thread_info *thread;
3846   struct thread_info *selected = NULL;
3847   struct thread_info *lowest_stopped = NULL;
3848   struct thread_info *first = NULL;
3849
3850   /* Consume the initial pending events.  */
3851   while (pending_stop_replies-- > 0)
3852     {
3853       ptid_t waiton_ptid = minus_one_ptid;
3854       ptid_t event_ptid;
3855       struct target_waitstatus ws;
3856       int ignore_event = 0;
3857       struct thread_info *thread;
3858
3859       memset (&ws, 0, sizeof (ws));
3860       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3861       if (remote_debug)
3862         print_target_wait_results (waiton_ptid, event_ptid, &ws);
3863
3864       switch (ws.kind)
3865         {
3866         case TARGET_WAITKIND_IGNORE:
3867         case TARGET_WAITKIND_NO_RESUMED:
3868         case TARGET_WAITKIND_SIGNALLED:
3869         case TARGET_WAITKIND_EXITED:
3870           /* We shouldn't see these, but if we do, just ignore.  */
3871           if (remote_debug)
3872             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3873           ignore_event = 1;
3874           break;
3875
3876         case TARGET_WAITKIND_EXECD:
3877           xfree (ws.value.execd_pathname);
3878           break;
3879         default:
3880           break;
3881         }
3882
3883       if (ignore_event)
3884         continue;
3885
3886       thread = find_thread_ptid (event_ptid);
3887
3888       if (ws.kind == TARGET_WAITKIND_STOPPED)
3889         {
3890           enum gdb_signal sig = ws.value.sig;
3891
3892           /* Stubs traditionally report SIGTRAP as initial signal,
3893              instead of signal 0.  Suppress it.  */
3894           if (sig == GDB_SIGNAL_TRAP)
3895             sig = GDB_SIGNAL_0;
3896           thread->suspend.stop_signal = sig;
3897           ws.value.sig = sig;
3898         }
3899
3900       thread->suspend.waitstatus = ws;
3901
3902       if (ws.kind != TARGET_WAITKIND_STOPPED
3903           || ws.value.sig != GDB_SIGNAL_0)
3904         thread->suspend.waitstatus_pending_p = 1;
3905
3906       set_executing (event_ptid, 0);
3907       set_running (event_ptid, 0);
3908     }
3909
3910   /* "Notice" the new inferiors before anything related to
3911      registers/memory.  */
3912   ALL_INFERIORS (inf)
3913     {
3914       if (inf->pid == 0)
3915         continue;
3916
3917       inf->needs_setup = 1;
3918
3919       if (non_stop)
3920         {
3921           thread = any_live_thread_of_process (inf->pid);
3922           notice_new_inferior (thread->ptid,
3923                                thread->state == THREAD_RUNNING,
3924                                from_tty);
3925         }
3926     }
3927
3928   /* If all-stop on top of non-stop, pause all threads.  Note this
3929      records the threads' stop pc, so must be done after "noticing"
3930      the inferiors.  */
3931   if (!non_stop)
3932     {
3933       stop_all_threads ();
3934
3935       /* If all threads of an inferior were already stopped, we
3936          haven't setup the inferior yet.  */
3937       ALL_INFERIORS (inf)
3938         {
3939           if (inf->pid == 0)
3940             continue;
3941
3942           if (inf->needs_setup)
3943             {
3944               thread = any_live_thread_of_process (inf->pid);
3945               switch_to_thread_no_regs (thread);
3946               setup_inferior (0);
3947             }
3948         }
3949     }
3950
3951   /* Now go over all threads that are stopped, and print their current
3952      frame.  If all-stop, then if there's a signalled thread, pick
3953      that as current.  */
3954   ALL_NON_EXITED_THREADS (thread)
3955     {
3956       struct target_waitstatus *ws;
3957
3958       if (first == NULL)
3959         first = thread;
3960
3961       if (!non_stop)
3962         set_running (thread->ptid, 0);
3963       else if (thread->state != THREAD_STOPPED)
3964         continue;
3965
3966       ws = &thread->suspend.waitstatus;
3967
3968       if (selected == NULL
3969           && thread->suspend.waitstatus_pending_p)
3970         selected = thread;
3971
3972       if (lowest_stopped == NULL || thread->num < lowest_stopped->num)
3973         lowest_stopped = thread;
3974
3975       if (non_stop)
3976         print_one_stopped_thread (thread);
3977     }
3978
3979   /* In all-stop, we only print the status of one thread, and leave
3980      others with their status pending.  */
3981   if (!non_stop)
3982     {
3983       thread = selected;
3984       if (thread == NULL)
3985         thread = lowest_stopped;
3986       if (thread == NULL)
3987         thread = first;
3988
3989       print_one_stopped_thread (thread);
3990     }
3991
3992   /* For "info program".  */
3993   thread = inferior_thread ();
3994   if (thread->state == THREAD_STOPPED)
3995     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
3996 }
3997
3998 static void
3999 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4000 {
4001   struct remote_state *rs = get_remote_state ();
4002   struct packet_config *noack_config;
4003   char *wait_status = NULL;
4004
4005   immediate_quit++;             /* Allow user to interrupt it.  */
4006   QUIT;
4007
4008   if (interrupt_on_connect)
4009     send_interrupt_sequence ();
4010
4011   /* Ack any packet which the remote side has already sent.  */
4012   serial_write (rs->remote_desc, "+", 1);
4013
4014   /* Signal other parts that we're going through the initial setup,
4015      and so things may not be stable yet.  */
4016   rs->starting_up = 1;
4017
4018   /* The first packet we send to the target is the optional "supported
4019      packets" request.  If the target can answer this, it will tell us
4020      which later probes to skip.  */
4021   remote_query_supported ();
4022
4023   /* If the stub wants to get a QAllow, compose one and send it.  */
4024   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4025     remote_set_permissions (target);
4026
4027   /* Next, we possibly activate noack mode.
4028
4029      If the QStartNoAckMode packet configuration is set to AUTO,
4030      enable noack mode if the stub reported a wish for it with
4031      qSupported.
4032
4033      If set to TRUE, then enable noack mode even if the stub didn't
4034      report it in qSupported.  If the stub doesn't reply OK, the
4035      session ends with an error.
4036
4037      If FALSE, then don't activate noack mode, regardless of what the
4038      stub claimed should be the default with qSupported.  */
4039
4040   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4041   if (packet_config_support (noack_config) != PACKET_DISABLE)
4042     {
4043       putpkt ("QStartNoAckMode");
4044       getpkt (&rs->buf, &rs->buf_size, 0);
4045       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4046         rs->noack_mode = 1;
4047     }
4048
4049   if (extended_p)
4050     {
4051       /* Tell the remote that we are using the extended protocol.  */
4052       putpkt ("!");
4053       getpkt (&rs->buf, &rs->buf_size, 0);
4054     }
4055
4056   /* Let the target know which signals it is allowed to pass down to
4057      the program.  */
4058   update_signals_program_target ();
4059
4060   /* Next, if the target can specify a description, read it.  We do
4061      this before anything involving memory or registers.  */
4062   target_find_description ();
4063
4064   /* Next, now that we know something about the target, update the
4065      address spaces in the program spaces.  */
4066   update_address_spaces ();
4067
4068   /* On OSs where the list of libraries is global to all
4069      processes, we fetch them early.  */
4070   if (gdbarch_has_global_solist (target_gdbarch ()))
4071     solib_add (NULL, from_tty, target, auto_solib_add);
4072
4073   if (target_is_non_stop_p ())
4074     {
4075       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4076         error (_("Non-stop mode requested, but remote "
4077                  "does not support non-stop"));
4078
4079       putpkt ("QNonStop:1");
4080       getpkt (&rs->buf, &rs->buf_size, 0);
4081
4082       if (strcmp (rs->buf, "OK") != 0)
4083         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4084
4085       /* Find about threads and processes the stub is already
4086          controlling.  We default to adding them in the running state.
4087          The '?' query below will then tell us about which threads are
4088          stopped.  */
4089       remote_update_thread_list (target);
4090     }
4091   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4092     {
4093       /* Don't assume that the stub can operate in all-stop mode.
4094          Request it explicitly.  */
4095       putpkt ("QNonStop:0");
4096       getpkt (&rs->buf, &rs->buf_size, 0);
4097
4098       if (strcmp (rs->buf, "OK") != 0)
4099         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4100     }
4101
4102   /* Upload TSVs regardless of whether the target is running or not.  The
4103      remote stub, such as GDBserver, may have some predefined or builtin
4104      TSVs, even if the target is not running.  */
4105   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4106     {
4107       struct uploaded_tsv *uploaded_tsvs = NULL;
4108
4109       remote_upload_trace_state_variables (target, &uploaded_tsvs);
4110       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4111     }
4112
4113   /* Check whether the target is running now.  */
4114   putpkt ("?");
4115   getpkt (&rs->buf, &rs->buf_size, 0);
4116
4117   if (!target_is_non_stop_p ())
4118     {
4119       ptid_t ptid;
4120       int fake_pid_p = 0;
4121       struct inferior *inf;
4122
4123       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4124         {
4125           if (!extended_p)
4126             error (_("The target is not running (try extended-remote?)"));
4127
4128           /* We're connected, but not running.  Drop out before we
4129              call start_remote.  */
4130           rs->starting_up = 0;
4131           return;
4132         }
4133       else
4134         {
4135           /* Save the reply for later.  */
4136           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4137           strcpy (wait_status, rs->buf);
4138         }
4139
4140       /* Fetch thread list.  */
4141       target_update_thread_list ();
4142
4143       /* Let the stub know that we want it to return the thread.  */
4144       set_continue_thread (minus_one_ptid);
4145
4146       if (thread_count () == 0)
4147         {
4148           /* Target has no concept of threads at all.  GDB treats
4149              non-threaded target as single-threaded; add a main
4150              thread.  */
4151           add_current_inferior_and_thread (wait_status);
4152         }
4153       else
4154         {
4155           /* We have thread information; select the thread the target
4156              says should be current.  If we're reconnecting to a
4157              multi-threaded program, this will ideally be the thread
4158              that last reported an event before GDB disconnected.  */
4159           inferior_ptid = get_current_thread (wait_status);
4160           if (ptid_equal (inferior_ptid, null_ptid))
4161             {
4162               /* Odd... The target was able to list threads, but not
4163                  tell us which thread was current (no "thread"
4164                  register in T stop reply?).  Just pick the first
4165                  thread in the thread list then.  */
4166               
4167               if (remote_debug)
4168                 fprintf_unfiltered (gdb_stdlog,
4169                                     "warning: couldn't determine remote "
4170                                     "current thread; picking first in list.\n");
4171
4172               inferior_ptid = thread_list->ptid;
4173             }
4174         }
4175
4176       /* init_wait_for_inferior should be called before get_offsets in order
4177          to manage `inserted' flag in bp loc in a correct state.
4178          breakpoint_init_inferior, called from init_wait_for_inferior, set
4179          `inserted' flag to 0, while before breakpoint_re_set, called from
4180          start_remote, set `inserted' flag to 1.  In the initialization of
4181          inferior, breakpoint_init_inferior should be called first, and then
4182          breakpoint_re_set can be called.  If this order is broken, state of
4183          `inserted' flag is wrong, and cause some problems on breakpoint
4184          manipulation.  */
4185       init_wait_for_inferior ();
4186
4187       get_offsets ();           /* Get text, data & bss offsets.  */
4188
4189       /* If we could not find a description using qXfer, and we know
4190          how to do it some other way, try again.  This is not
4191          supported for non-stop; it could be, but it is tricky if
4192          there are no stopped threads when we connect.  */
4193       if (remote_read_description_p (target)
4194           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4195         {
4196           target_clear_description ();
4197           target_find_description ();
4198         }
4199
4200       /* Use the previously fetched status.  */
4201       gdb_assert (wait_status != NULL);
4202       strcpy (rs->buf, wait_status);
4203       rs->cached_wait_status = 1;
4204
4205       immediate_quit--;
4206       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4207     }
4208   else
4209     {
4210       /* Clear WFI global state.  Do this before finding about new
4211          threads and inferiors, and setting the current inferior.
4212          Otherwise we would clear the proceed status of the current
4213          inferior when we want its stop_soon state to be preserved
4214          (see notice_new_inferior).  */
4215       init_wait_for_inferior ();
4216
4217       /* In non-stop, we will either get an "OK", meaning that there
4218          are no stopped threads at this time; or, a regular stop
4219          reply.  In the latter case, there may be more than one thread
4220          stopped --- we pull them all out using the vStopped
4221          mechanism.  */
4222       if (strcmp (rs->buf, "OK") != 0)
4223         {
4224           struct notif_client *notif = &notif_client_stop;
4225
4226           /* remote_notif_get_pending_replies acks this one, and gets
4227              the rest out.  */
4228           rs->notif_state->pending_event[notif_client_stop.id]
4229             = remote_notif_parse (notif, rs->buf);
4230           remote_notif_get_pending_events (notif);
4231         }
4232
4233       if (thread_count () == 0)
4234         {
4235           if (!extended_p)
4236             error (_("The target is not running (try extended-remote?)"));
4237
4238           /* We're connected, but not running.  Drop out before we
4239              call start_remote.  */
4240           rs->starting_up = 0;
4241           return;
4242         }
4243
4244       /* In non-stop mode, any cached wait status will be stored in
4245          the stop reply queue.  */
4246       gdb_assert (wait_status == NULL);
4247
4248       /* Report all signals during attach/startup.  */
4249       remote_pass_signals (target, 0, NULL);
4250
4251       /* If there are already stopped threads, mark them stopped and
4252          report their stops before giving the prompt to the user.  */
4253       process_initial_stop_replies (from_tty);
4254
4255       if (target_can_async_p ())
4256         target_async (1);
4257     }
4258
4259   /* If we connected to a live target, do some additional setup.  */
4260   if (target_has_execution)
4261     {
4262       if (symfile_objfile)      /* No use without a symbol-file.  */
4263         remote_check_symbols ();
4264     }
4265
4266   /* Possibly the target has been engaged in a trace run started
4267      previously; find out where things are at.  */
4268   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4269     {
4270       struct uploaded_tp *uploaded_tps = NULL;
4271
4272       if (current_trace_status ()->running)
4273         printf_filtered (_("Trace is already running on the target.\n"));
4274
4275       remote_upload_tracepoints (target, &uploaded_tps);
4276
4277       merge_uploaded_tracepoints (&uploaded_tps);
4278     }
4279
4280   /* The thread and inferior lists are now synchronized with the
4281      target, our symbols have been relocated, and we're merged the
4282      target's tracepoints with ours.  We're done with basic start
4283      up.  */
4284   rs->starting_up = 0;
4285
4286   /* Maybe breakpoints are global and need to be inserted now.  */
4287   if (breakpoints_should_be_inserted_now ())
4288     insert_breakpoints ();
4289 }
4290
4291 /* Open a connection to a remote debugger.
4292    NAME is the filename used for communication.  */
4293
4294 static void
4295 remote_open (const char *name, int from_tty)
4296 {
4297   remote_open_1 (name, from_tty, &remote_ops, 0);
4298 }
4299
4300 /* Open a connection to a remote debugger using the extended
4301    remote gdb protocol.  NAME is the filename used for communication.  */
4302
4303 static void
4304 extended_remote_open (const char *name, int from_tty)
4305 {
4306   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4307 }
4308
4309 /* Reset all packets back to "unknown support".  Called when opening a
4310    new connection to a remote target.  */
4311
4312 static void
4313 reset_all_packet_configs_support (void)
4314 {
4315   int i;
4316
4317   for (i = 0; i < PACKET_MAX; i++)
4318     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4319 }
4320
4321 /* Initialize all packet configs.  */
4322
4323 static void
4324 init_all_packet_configs (void)
4325 {
4326   int i;
4327
4328   for (i = 0; i < PACKET_MAX; i++)
4329     {
4330       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4331       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4332     }
4333 }
4334
4335 /* Symbol look-up.  */
4336
4337 static void
4338 remote_check_symbols (void)
4339 {
4340   struct remote_state *rs = get_remote_state ();
4341   char *msg, *reply, *tmp;
4342   struct bound_minimal_symbol sym;
4343   int end;
4344   struct cleanup *old_chain;
4345
4346   /* The remote side has no concept of inferiors that aren't running
4347      yet, it only knows about running processes.  If we're connected
4348      but our current inferior is not running, we should not invite the
4349      remote target to request symbol lookups related to its
4350      (unrelated) current process.  */
4351   if (!target_has_execution)
4352     return;
4353
4354   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4355     return;
4356
4357   /* Make sure the remote is pointing at the right process.  Note
4358      there's no way to select "no process".  */
4359   set_general_process ();
4360
4361   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4362      because we need both at the same time.  */
4363   msg = (char *) xmalloc (get_remote_packet_size ());
4364   old_chain = make_cleanup (xfree, msg);
4365
4366   /* Invite target to request symbol lookups.  */
4367
4368   putpkt ("qSymbol::");
4369   getpkt (&rs->buf, &rs->buf_size, 0);
4370   packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4371   reply = rs->buf;
4372
4373   while (startswith (reply, "qSymbol:"))
4374     {
4375       struct bound_minimal_symbol sym;
4376
4377       tmp = &reply[8];
4378       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4379       msg[end] = '\0';
4380       sym = lookup_minimal_symbol (msg, NULL, NULL);
4381       if (sym.minsym == NULL)
4382         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4383       else
4384         {
4385           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4386           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4387
4388           /* If this is a function address, return the start of code
4389              instead of any data function descriptor.  */
4390           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4391                                                          sym_addr,
4392                                                          &current_target);
4393
4394           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4395                      phex_nz (sym_addr, addr_size), &reply[8]);
4396         }
4397   
4398       putpkt (msg);
4399       getpkt (&rs->buf, &rs->buf_size, 0);
4400       reply = rs->buf;
4401     }
4402
4403   do_cleanups (old_chain);
4404 }
4405
4406 static struct serial *
4407 remote_serial_open (const char *name)
4408 {
4409   static int udp_warning = 0;
4410
4411   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4412      of in ser-tcp.c, because it is the remote protocol assuming that the
4413      serial connection is reliable and not the serial connection promising
4414      to be.  */
4415   if (!udp_warning && startswith (name, "udp:"))
4416     {
4417       warning (_("The remote protocol may be unreliable over UDP.\n"
4418                  "Some events may be lost, rendering further debugging "
4419                  "impossible."));
4420       udp_warning = 1;
4421     }
4422
4423   return serial_open (name);
4424 }
4425
4426 /* Inform the target of our permission settings.  The permission flags
4427    work without this, but if the target knows the settings, it can do
4428    a couple things.  First, it can add its own check, to catch cases
4429    that somehow manage to get by the permissions checks in target
4430    methods.  Second, if the target is wired to disallow particular
4431    settings (for instance, a system in the field that is not set up to
4432    be able to stop at a breakpoint), it can object to any unavailable
4433    permissions.  */
4434
4435 void
4436 remote_set_permissions (struct target_ops *self)
4437 {
4438   struct remote_state *rs = get_remote_state ();
4439
4440   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4441              "WriteReg:%x;WriteMem:%x;"
4442              "InsertBreak:%x;InsertTrace:%x;"
4443              "InsertFastTrace:%x;Stop:%x",
4444              may_write_registers, may_write_memory,
4445              may_insert_breakpoints, may_insert_tracepoints,
4446              may_insert_fast_tracepoints, may_stop);
4447   putpkt (rs->buf);
4448   getpkt (&rs->buf, &rs->buf_size, 0);
4449
4450   /* If the target didn't like the packet, warn the user.  Do not try
4451      to undo the user's settings, that would just be maddening.  */
4452   if (strcmp (rs->buf, "OK") != 0)
4453     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4454 }
4455
4456 /* This type describes each known response to the qSupported
4457    packet.  */
4458 struct protocol_feature
4459 {
4460   /* The name of this protocol feature.  */
4461   const char *name;
4462
4463   /* The default for this protocol feature.  */
4464   enum packet_support default_support;
4465
4466   /* The function to call when this feature is reported, or after
4467      qSupported processing if the feature is not supported.
4468      The first argument points to this structure.  The second
4469      argument indicates whether the packet requested support be
4470      enabled, disabled, or probed (or the default, if this function
4471      is being called at the end of processing and this feature was
4472      not reported).  The third argument may be NULL; if not NULL, it
4473      is a NUL-terminated string taken from the packet following
4474      this feature's name and an equals sign.  */
4475   void (*func) (const struct protocol_feature *, enum packet_support,
4476                 const char *);
4477
4478   /* The corresponding packet for this feature.  Only used if
4479      FUNC is remote_supported_packet.  */
4480   int packet;
4481 };
4482
4483 static void
4484 remote_supported_packet (const struct protocol_feature *feature,
4485                          enum packet_support support,
4486                          const char *argument)
4487 {
4488   if (argument)
4489     {
4490       warning (_("Remote qSupported response supplied an unexpected value for"
4491                  " \"%s\"."), feature->name);
4492       return;
4493     }
4494
4495   remote_protocol_packets[feature->packet].support = support;
4496 }
4497
4498 static void
4499 remote_packet_size (const struct protocol_feature *feature,
4500                     enum packet_support support, const char *value)
4501 {
4502   struct remote_state *rs = get_remote_state ();
4503
4504   int packet_size;
4505   char *value_end;
4506
4507   if (support != PACKET_ENABLE)
4508     return;
4509
4510   if (value == NULL || *value == '\0')
4511     {
4512       warning (_("Remote target reported \"%s\" without a size."),
4513                feature->name);
4514       return;
4515     }
4516
4517   errno = 0;
4518   packet_size = strtol (value, &value_end, 16);
4519   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4520     {
4521       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4522                feature->name, value);
4523       return;
4524     }
4525
4526   /* Record the new maximum packet size.  */
4527   rs->explicit_packet_size = packet_size;
4528 }
4529
4530 static const struct protocol_feature remote_protocol_features[] = {
4531   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4532   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4533     PACKET_qXfer_auxv },
4534   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4535     PACKET_qXfer_exec_file },
4536   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4537     PACKET_qXfer_features },
4538   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4539     PACKET_qXfer_libraries },
4540   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4541     PACKET_qXfer_libraries_svr4 },
4542   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4543     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4544   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4545     PACKET_qXfer_memory_map },
4546   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4547     PACKET_qXfer_spu_read },
4548   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4549     PACKET_qXfer_spu_write },
4550   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4551     PACKET_qXfer_osdata },
4552   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4553     PACKET_qXfer_threads },
4554   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4555     PACKET_qXfer_traceframe_info },
4556   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4557     PACKET_QPassSignals },
4558   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4559     PACKET_QCatchSyscalls },
4560   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4561     PACKET_QProgramSignals },
4562   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4563     PACKET_QStartNoAckMode },
4564   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4565     PACKET_multiprocess_feature },
4566   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4567   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4568     PACKET_qXfer_siginfo_read },
4569   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4570     PACKET_qXfer_siginfo_write },
4571   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4572     PACKET_ConditionalTracepoints },
4573   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4574     PACKET_ConditionalBreakpoints },
4575   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4576     PACKET_BreakpointCommands },
4577   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4578     PACKET_FastTracepoints },
4579   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4580     PACKET_StaticTracepoints },
4581   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4582    PACKET_InstallInTrace},
4583   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4584     PACKET_DisconnectedTracing_feature },
4585   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4586     PACKET_bc },
4587   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4588     PACKET_bs },
4589   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4590     PACKET_TracepointSource },
4591   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4592     PACKET_QAllow },
4593   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4594     PACKET_EnableDisableTracepoints_feature },
4595   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4596     PACKET_qXfer_fdpic },
4597   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4598     PACKET_qXfer_uib },
4599   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4600     PACKET_QDisableRandomization },
4601   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4602   { "QTBuffer:size", PACKET_DISABLE,
4603     remote_supported_packet, PACKET_QTBuffer_size},
4604   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4605   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4606   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4607   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4608   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4609     PACKET_qXfer_btrace },
4610   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4611     PACKET_qXfer_btrace_conf },
4612   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4613     PACKET_Qbtrace_conf_bts_size },
4614   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4615   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4616   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4617     PACKET_fork_event_feature },
4618   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4619     PACKET_vfork_event_feature },
4620   { "exec-events", PACKET_DISABLE, remote_supported_packet,
4621     PACKET_exec_event_feature },
4622   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4623     PACKET_Qbtrace_conf_pt_size },
4624   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4625   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4626   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4627 };
4628
4629 static char *remote_support_xml;
4630
4631 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4632
4633 void
4634 register_remote_support_xml (const char *xml)
4635 {
4636 #if defined(HAVE_LIBEXPAT)
4637   if (remote_support_xml == NULL)
4638     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4639   else
4640     {
4641       char *copy = xstrdup (remote_support_xml + 13);
4642       char *p = strtok (copy, ",");
4643
4644       do
4645         {
4646           if (strcmp (p, xml) == 0)
4647             {
4648               /* already there */
4649               xfree (copy);
4650               return;
4651             }
4652         }
4653       while ((p = strtok (NULL, ",")) != NULL);
4654       xfree (copy);
4655
4656       remote_support_xml = reconcat (remote_support_xml,
4657                                      remote_support_xml, ",", xml,
4658                                      (char *) NULL);
4659     }
4660 #endif
4661 }
4662
4663 static char *
4664 remote_query_supported_append (char *msg, const char *append)
4665 {
4666   if (msg)
4667     return reconcat (msg, msg, ";", append, (char *) NULL);
4668   else
4669     return xstrdup (append);
4670 }
4671
4672 static void
4673 remote_query_supported (void)
4674 {
4675   struct remote_state *rs = get_remote_state ();
4676   char *next;
4677   int i;
4678   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4679
4680   /* The packet support flags are handled differently for this packet
4681      than for most others.  We treat an error, a disabled packet, and
4682      an empty response identically: any features which must be reported
4683      to be used will be automatically disabled.  An empty buffer
4684      accomplishes this, since that is also the representation for a list
4685      containing no features.  */
4686
4687   rs->buf[0] = 0;
4688   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4689     {
4690       char *q = NULL;
4691       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4692
4693       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4694         q = remote_query_supported_append (q, "multiprocess+");
4695
4696       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4697         q = remote_query_supported_append (q, "swbreak+");
4698       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4699         q = remote_query_supported_append (q, "hwbreak+");
4700
4701       q = remote_query_supported_append (q, "qRelocInsn+");
4702
4703       if (packet_set_cmd_state (PACKET_fork_event_feature)
4704           != AUTO_BOOLEAN_FALSE)
4705         q = remote_query_supported_append (q, "fork-events+");
4706       if (packet_set_cmd_state (PACKET_vfork_event_feature)
4707           != AUTO_BOOLEAN_FALSE)
4708         q = remote_query_supported_append (q, "vfork-events+");
4709       if (packet_set_cmd_state (PACKET_exec_event_feature)
4710           != AUTO_BOOLEAN_FALSE)
4711         q = remote_query_supported_append (q, "exec-events+");
4712
4713       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4714         q = remote_query_supported_append (q, "vContSupported+");
4715
4716       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4717         q = remote_query_supported_append (q, "QThreadEvents+");
4718
4719       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4720         q = remote_query_supported_append (q, "no-resumed+");
4721
4722       /* Keep this one last to work around a gdbserver <= 7.10 bug in
4723          the qSupported:xmlRegisters=i386 handling.  */
4724       if (remote_support_xml != NULL)
4725         q = remote_query_supported_append (q, remote_support_xml);
4726
4727       q = reconcat (q, "qSupported:", q, (char *) NULL);
4728       putpkt (q);
4729
4730       do_cleanups (old_chain);
4731
4732       getpkt (&rs->buf, &rs->buf_size, 0);
4733
4734       /* If an error occured, warn, but do not return - just reset the
4735          buffer to empty and go on to disable features.  */
4736       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4737           == PACKET_ERROR)
4738         {
4739           warning (_("Remote failure reply: %s"), rs->buf);
4740           rs->buf[0] = 0;
4741         }
4742     }
4743
4744   memset (seen, 0, sizeof (seen));
4745
4746   next = rs->buf;
4747   while (*next)
4748     {
4749       enum packet_support is_supported;
4750       char *p, *end, *name_end, *value;
4751
4752       /* First separate out this item from the rest of the packet.  If
4753          there's another item after this, we overwrite the separator
4754          (terminated strings are much easier to work with).  */
4755       p = next;
4756       end = strchr (p, ';');
4757       if (end == NULL)
4758         {
4759           end = p + strlen (p);
4760           next = end;
4761         }
4762       else
4763         {
4764           *end = '\0';
4765           next = end + 1;
4766
4767           if (end == p)
4768             {
4769               warning (_("empty item in \"qSupported\" response"));
4770               continue;
4771             }
4772         }
4773
4774       name_end = strchr (p, '=');
4775       if (name_end)
4776         {
4777           /* This is a name=value entry.  */
4778           is_supported = PACKET_ENABLE;
4779           value = name_end + 1;
4780           *name_end = '\0';
4781         }
4782       else
4783         {
4784           value = NULL;
4785           switch (end[-1])
4786             {
4787             case '+':
4788               is_supported = PACKET_ENABLE;
4789               break;
4790
4791             case '-':
4792               is_supported = PACKET_DISABLE;
4793               break;
4794
4795             case '?':
4796               is_supported = PACKET_SUPPORT_UNKNOWN;
4797               break;
4798
4799             default:
4800               warning (_("unrecognized item \"%s\" "
4801                          "in \"qSupported\" response"), p);
4802               continue;
4803             }
4804           end[-1] = '\0';
4805         }
4806
4807       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4808         if (strcmp (remote_protocol_features[i].name, p) == 0)
4809           {
4810             const struct protocol_feature *feature;
4811
4812             seen[i] = 1;
4813             feature = &remote_protocol_features[i];
4814             feature->func (feature, is_supported, value);
4815             break;
4816           }
4817     }
4818
4819   /* If we increased the packet size, make sure to increase the global
4820      buffer size also.  We delay this until after parsing the entire
4821      qSupported packet, because this is the same buffer we were
4822      parsing.  */
4823   if (rs->buf_size < rs->explicit_packet_size)
4824     {
4825       rs->buf_size = rs->explicit_packet_size;
4826       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4827     }
4828
4829   /* Handle the defaults for unmentioned features.  */
4830   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4831     if (!seen[i])
4832       {
4833         const struct protocol_feature *feature;
4834
4835         feature = &remote_protocol_features[i];
4836         feature->func (feature, feature->default_support, NULL);
4837       }
4838 }
4839
4840 /* Remove any of the remote.c targets from target stack.  Upper targets depend
4841    on it so remove them first.  */
4842
4843 static void
4844 remote_unpush_target (void)
4845 {
4846   pop_all_targets_at_and_above (process_stratum);
4847 }
4848
4849 static void
4850 remote_open_1 (const char *name, int from_tty,
4851                struct target_ops *target, int extended_p)
4852 {
4853   struct remote_state *rs = get_remote_state ();
4854
4855   if (name == 0)
4856     error (_("To open a remote debug connection, you need to specify what\n"
4857            "serial device is attached to the remote system\n"
4858            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4859
4860   /* See FIXME above.  */
4861   if (!target_async_permitted)
4862     wait_forever_enabled_p = 1;
4863
4864   /* If we're connected to a running target, target_preopen will kill it.
4865      Ask this question first, before target_preopen has a chance to kill
4866      anything.  */
4867   if (rs->remote_desc != NULL && !have_inferiors ())
4868     {
4869       if (from_tty
4870           && !query (_("Already connected to a remote target.  Disconnect? ")))
4871         error (_("Still connected."));
4872     }
4873
4874   /* Here the possibly existing remote target gets unpushed.  */
4875   target_preopen (from_tty);
4876
4877   /* Make sure we send the passed signals list the next time we resume.  */
4878   xfree (rs->last_pass_packet);
4879   rs->last_pass_packet = NULL;
4880
4881   /* Make sure we send the program signals list the next time we
4882      resume.  */
4883   xfree (rs->last_program_signals_packet);
4884   rs->last_program_signals_packet = NULL;
4885
4886   remote_fileio_reset ();
4887   reopen_exec_file ();
4888   reread_symbols ();
4889
4890   rs->remote_desc = remote_serial_open (name);
4891   if (!rs->remote_desc)
4892     perror_with_name (name);
4893
4894   if (baud_rate != -1)
4895     {
4896       if (serial_setbaudrate (rs->remote_desc, baud_rate))
4897         {
4898           /* The requested speed could not be set.  Error out to
4899              top level after closing remote_desc.  Take care to
4900              set remote_desc to NULL to avoid closing remote_desc
4901              more than once.  */
4902           serial_close (rs->remote_desc);
4903           rs->remote_desc = NULL;
4904           perror_with_name (name);
4905         }
4906     }
4907
4908   serial_setparity (rs->remote_desc, serial_parity);
4909   serial_raw (rs->remote_desc);
4910
4911   /* If there is something sitting in the buffer we might take it as a
4912      response to a command, which would be bad.  */
4913   serial_flush_input (rs->remote_desc);
4914
4915   if (from_tty)
4916     {
4917       puts_filtered ("Remote debugging using ");
4918       puts_filtered (name);
4919       puts_filtered ("\n");
4920     }
4921   push_target (target);         /* Switch to using remote target now.  */
4922
4923   /* Register extra event sources in the event loop.  */
4924   remote_async_inferior_event_token
4925     = create_async_event_handler (remote_async_inferior_event_handler,
4926                                   NULL);
4927   rs->notif_state = remote_notif_state_allocate ();
4928
4929   /* Reset the target state; these things will be queried either by
4930      remote_query_supported or as they are needed.  */
4931   reset_all_packet_configs_support ();
4932   rs->cached_wait_status = 0;
4933   rs->explicit_packet_size = 0;
4934   rs->noack_mode = 0;
4935   rs->extended = extended_p;
4936   rs->waiting_for_stop_reply = 0;
4937   rs->ctrlc_pending_p = 0;
4938
4939   rs->general_thread = not_sent_ptid;
4940   rs->continue_thread = not_sent_ptid;
4941   rs->remote_traceframe_number = -1;
4942
4943   /* Probe for ability to use "ThreadInfo" query, as required.  */
4944   rs->use_threadinfo_query = 1;
4945   rs->use_threadextra_query = 1;
4946
4947   readahead_cache_invalidate ();
4948
4949   if (target_async_permitted)
4950     {
4951       /* With this target we start out by owning the terminal.  */
4952       remote_async_terminal_ours_p = 1;
4953
4954       /* FIXME: cagney/1999-09-23: During the initial connection it is
4955          assumed that the target is already ready and able to respond to
4956          requests.  Unfortunately remote_start_remote() eventually calls
4957          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
4958          around this.  Eventually a mechanism that allows
4959          wait_for_inferior() to expect/get timeouts will be
4960          implemented.  */
4961       wait_forever_enabled_p = 0;
4962     }
4963
4964   /* First delete any symbols previously loaded from shared libraries.  */
4965   no_shared_libraries (NULL, 0);
4966
4967   /* Start afresh.  */
4968   init_thread_list ();
4969
4970   /* Start the remote connection.  If error() or QUIT, discard this
4971      target (we'd otherwise be in an inconsistent state) and then
4972      propogate the error on up the exception chain.  This ensures that
4973      the caller doesn't stumble along blindly assuming that the
4974      function succeeded.  The CLI doesn't have this problem but other
4975      UI's, such as MI do.
4976
4977      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4978      this function should return an error indication letting the
4979      caller restore the previous state.  Unfortunately the command
4980      ``target remote'' is directly wired to this function making that
4981      impossible.  On a positive note, the CLI side of this problem has
4982      been fixed - the function set_cmd_context() makes it possible for
4983      all the ``target ....'' commands to share a common callback
4984      function.  See cli-dump.c.  */
4985   {
4986
4987     TRY
4988       {
4989         remote_start_remote (from_tty, target, extended_p);
4990       }
4991     CATCH (ex, RETURN_MASK_ALL)
4992       {
4993         /* Pop the partially set up target - unless something else did
4994            already before throwing the exception.  */
4995         if (rs->remote_desc != NULL)
4996           remote_unpush_target ();
4997         if (target_async_permitted)
4998           wait_forever_enabled_p = 1;
4999         throw_exception (ex);
5000       }
5001     END_CATCH
5002   }
5003
5004   remote_btrace_reset ();
5005
5006   if (target_async_permitted)
5007     wait_forever_enabled_p = 1;
5008 }
5009
5010 /* Detach the specified process.  */
5011
5012 static void
5013 remote_detach_pid (int pid)
5014 {
5015   struct remote_state *rs = get_remote_state ();
5016
5017   if (remote_multi_process_p (rs))
5018     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5019   else
5020     strcpy (rs->buf, "D");
5021
5022   putpkt (rs->buf);
5023   getpkt (&rs->buf, &rs->buf_size, 0);
5024
5025   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5026     ;
5027   else if (rs->buf[0] == '\0')
5028     error (_("Remote doesn't know how to detach"));
5029   else
5030     error (_("Can't detach process."));
5031 }
5032
5033 /* This detaches a program to which we previously attached, using
5034    inferior_ptid to identify the process.  After this is done, GDB
5035    can be used to debug some other program.  We better not have left
5036    any breakpoints in the target program or it'll die when it hits
5037    one.  */
5038
5039 static void
5040 remote_detach_1 (const char *args, int from_tty)
5041 {
5042   int pid = ptid_get_pid (inferior_ptid);
5043   struct remote_state *rs = get_remote_state ();
5044   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5045   int is_fork_parent;
5046
5047   if (args)
5048     error (_("Argument given to \"detach\" when remotely debugging."));
5049
5050   if (!target_has_execution)
5051     error (_("No process to detach from."));
5052
5053   if (from_tty)
5054     {
5055       char *exec_file = get_exec_file (0);
5056       if (exec_file == NULL)
5057         exec_file = "";
5058       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
5059                          target_pid_to_str (pid_to_ptid (pid)));
5060       gdb_flush (gdb_stdout);
5061     }
5062
5063   /* Tell the remote target to detach.  */
5064   remote_detach_pid (pid);
5065
5066   /* Exit only if this is the only active inferior.  */
5067   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5068     puts_filtered (_("Ending remote debugging.\n"));
5069
5070   /* Check to see if we are detaching a fork parent.  Note that if we
5071      are detaching a fork child, tp == NULL.  */
5072   is_fork_parent = (tp != NULL
5073                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5074
5075   /* If doing detach-on-fork, we don't mourn, because that will delete
5076      breakpoints that should be available for the followed inferior.  */
5077   if (!is_fork_parent)
5078     target_mourn_inferior ();
5079   else
5080     {
5081       inferior_ptid = null_ptid;
5082       detach_inferior (pid);
5083     }
5084 }
5085
5086 static void
5087 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5088 {
5089   remote_detach_1 (args, from_tty);
5090 }
5091
5092 static void
5093 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5094 {
5095   remote_detach_1 (args, from_tty);
5096 }
5097
5098 /* Target follow-fork function for remote targets.  On entry, and
5099    at return, the current inferior is the fork parent.
5100
5101    Note that although this is currently only used for extended-remote,
5102    it is named remote_follow_fork in anticipation of using it for the
5103    remote target as well.  */
5104
5105 static int
5106 remote_follow_fork (struct target_ops *ops, int follow_child,
5107                     int detach_fork)
5108 {
5109   struct remote_state *rs = get_remote_state ();
5110   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5111
5112   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5113       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5114     {
5115       /* When following the parent and detaching the child, we detach
5116          the child here.  For the case of following the child and
5117          detaching the parent, the detach is done in the target-
5118          independent follow fork code in infrun.c.  We can't use
5119          target_detach when detaching an unfollowed child because
5120          the client side doesn't know anything about the child.  */
5121       if (detach_fork && !follow_child)
5122         {
5123           /* Detach the fork child.  */
5124           ptid_t child_ptid;
5125           pid_t child_pid;
5126
5127           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5128           child_pid = ptid_get_pid (child_ptid);
5129
5130           remote_detach_pid (child_pid);
5131           detach_inferior (child_pid);
5132         }
5133     }
5134   return 0;
5135 }
5136
5137 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5138    in the program space of the new inferior.  On entry and at return the
5139    current inferior is the exec'ing inferior.  INF is the new exec'd
5140    inferior, which may be the same as the exec'ing inferior unless
5141    follow-exec-mode is "new".  */
5142
5143 static void
5144 remote_follow_exec (struct target_ops *ops,
5145                     struct inferior *inf, char *execd_pathname)
5146 {
5147   /* We know that this is a target file name, so if it has the "target:"
5148      prefix we strip it off before saving it in the program space.  */
5149   if (is_target_filename (execd_pathname))
5150     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5151
5152   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5153 }
5154
5155 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5156
5157 static void
5158 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5159 {
5160   if (args)
5161     error (_("Argument given to \"disconnect\" when remotely debugging."));
5162
5163   /* Make sure we unpush even the extended remote targets.  Calling
5164      target_mourn_inferior won't unpush, and remote_mourn won't
5165      unpush if there is more than one inferior left.  */
5166   unpush_target (target);
5167   generic_mourn_inferior ();
5168
5169   if (from_tty)
5170     puts_filtered ("Ending remote debugging.\n");
5171 }
5172
5173 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5174    be chatty about it.  */
5175
5176 static void
5177 extended_remote_attach (struct target_ops *target, const char *args,
5178                         int from_tty)
5179 {
5180   struct remote_state *rs = get_remote_state ();
5181   int pid;
5182   char *wait_status = NULL;
5183
5184   pid = parse_pid_to_attach (args);
5185
5186   /* Remote PID can be freely equal to getpid, do not check it here the same
5187      way as in other targets.  */
5188
5189   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5190     error (_("This target does not support attaching to a process"));
5191
5192   if (from_tty)
5193     {
5194       char *exec_file = get_exec_file (0);
5195
5196       if (exec_file)
5197         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5198                            target_pid_to_str (pid_to_ptid (pid)));
5199       else
5200         printf_unfiltered (_("Attaching to %s\n"),
5201                            target_pid_to_str (pid_to_ptid (pid)));
5202
5203       gdb_flush (gdb_stdout);
5204     }
5205
5206   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5207   putpkt (rs->buf);
5208   getpkt (&rs->buf, &rs->buf_size, 0);
5209
5210   switch (packet_ok (rs->buf,
5211                      &remote_protocol_packets[PACKET_vAttach]))
5212     {
5213     case PACKET_OK:
5214       if (!target_is_non_stop_p ())
5215         {
5216           /* Save the reply for later.  */
5217           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5218           strcpy (wait_status, rs->buf);
5219         }
5220       else if (strcmp (rs->buf, "OK") != 0)
5221         error (_("Attaching to %s failed with: %s"),
5222                target_pid_to_str (pid_to_ptid (pid)),
5223                rs->buf);
5224       break;
5225     case PACKET_UNKNOWN:
5226       error (_("This target does not support attaching to a process"));
5227     default:
5228       error (_("Attaching to %s failed"),
5229              target_pid_to_str (pid_to_ptid (pid)));
5230     }
5231
5232   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5233
5234   inferior_ptid = pid_to_ptid (pid);
5235
5236   if (target_is_non_stop_p ())
5237     {
5238       struct thread_info *thread;
5239
5240       /* Get list of threads.  */
5241       remote_update_thread_list (target);
5242
5243       thread = first_thread_of_process (pid);
5244       if (thread)
5245         inferior_ptid = thread->ptid;
5246       else
5247         inferior_ptid = pid_to_ptid (pid);
5248
5249       /* Invalidate our notion of the remote current thread.  */
5250       record_currthread (rs, minus_one_ptid);
5251     }
5252   else
5253     {
5254       /* Now, if we have thread information, update inferior_ptid.  */
5255       inferior_ptid = remote_current_thread (inferior_ptid);
5256
5257       /* Add the main thread to the thread list.  */
5258       add_thread_silent (inferior_ptid);
5259     }
5260
5261   /* Next, if the target can specify a description, read it.  We do
5262      this before anything involving memory or registers.  */
5263   target_find_description ();
5264
5265   if (!target_is_non_stop_p ())
5266     {
5267       /* Use the previously fetched status.  */
5268       gdb_assert (wait_status != NULL);
5269
5270       if (target_can_async_p ())
5271         {
5272           struct notif_event *reply
5273             =  remote_notif_parse (&notif_client_stop, wait_status);
5274
5275           push_stop_reply ((struct stop_reply *) reply);
5276
5277           target_async (1);
5278         }
5279       else
5280         {
5281           gdb_assert (wait_status != NULL);
5282           strcpy (rs->buf, wait_status);
5283           rs->cached_wait_status = 1;
5284         }
5285     }
5286   else
5287     gdb_assert (wait_status == NULL);
5288 }
5289
5290 /* Implementation of the to_post_attach method.  */
5291
5292 static void
5293 extended_remote_post_attach (struct target_ops *ops, int pid)
5294 {
5295   /* Get text, data & bss offsets.  */
5296   get_offsets ();
5297
5298   /* In certain cases GDB might not have had the chance to start
5299      symbol lookup up until now.  This could happen if the debugged
5300      binary is not using shared libraries, the vsyscall page is not
5301      present (on Linux) and the binary itself hadn't changed since the
5302      debugging process was started.  */
5303   if (symfile_objfile != NULL)
5304     remote_check_symbols();
5305 }
5306
5307 \f
5308 /* Check for the availability of vCont.  This function should also check
5309    the response.  */
5310
5311 static void
5312 remote_vcont_probe (struct remote_state *rs)
5313 {
5314   char *buf;
5315
5316   strcpy (rs->buf, "vCont?");
5317   putpkt (rs->buf);
5318   getpkt (&rs->buf, &rs->buf_size, 0);
5319   buf = rs->buf;
5320
5321   /* Make sure that the features we assume are supported.  */
5322   if (startswith (buf, "vCont"))
5323     {
5324       char *p = &buf[5];
5325       int support_c, support_C;
5326
5327       rs->supports_vCont.s = 0;
5328       rs->supports_vCont.S = 0;
5329       support_c = 0;
5330       support_C = 0;
5331       rs->supports_vCont.t = 0;
5332       rs->supports_vCont.r = 0;
5333       while (p && *p == ';')
5334         {
5335           p++;
5336           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5337             rs->supports_vCont.s = 1;
5338           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5339             rs->supports_vCont.S = 1;
5340           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5341             support_c = 1;
5342           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5343             support_C = 1;
5344           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5345             rs->supports_vCont.t = 1;
5346           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5347             rs->supports_vCont.r = 1;
5348
5349           p = strchr (p, ';');
5350         }
5351
5352       /* If c, and C are not all supported, we can't use vCont.  Clearing
5353          BUF will make packet_ok disable the packet.  */
5354       if (!support_c || !support_C)
5355         buf[0] = 0;
5356     }
5357
5358   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5359 }
5360
5361 /* Helper function for building "vCont" resumptions.  Write a
5362    resumption to P.  ENDP points to one-passed-the-end of the buffer
5363    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5364    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5365    resumed thread should be single-stepped and/or signalled.  If PTID
5366    equals minus_one_ptid, then all threads are resumed; if PTID
5367    represents a process, then all threads of the process are resumed;
5368    the thread to be stepped and/or signalled is given in the global
5369    INFERIOR_PTID.  */
5370
5371 static char *
5372 append_resumption (char *p, char *endp,
5373                    ptid_t ptid, int step, enum gdb_signal siggnal)
5374 {
5375   struct remote_state *rs = get_remote_state ();
5376
5377   if (step && siggnal != GDB_SIGNAL_0)
5378     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5379   else if (step
5380            /* GDB is willing to range step.  */
5381            && use_range_stepping
5382            /* Target supports range stepping.  */
5383            && rs->supports_vCont.r
5384            /* We don't currently support range stepping multiple
5385               threads with a wildcard (though the protocol allows it,
5386               so stubs shouldn't make an active effort to forbid
5387               it).  */
5388            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5389     {
5390       struct thread_info *tp;
5391
5392       if (ptid_equal (ptid, minus_one_ptid))
5393         {
5394           /* If we don't know about the target thread's tid, then
5395              we're resuming magic_null_ptid (see caller).  */
5396           tp = find_thread_ptid (magic_null_ptid);
5397         }
5398       else
5399         tp = find_thread_ptid (ptid);
5400       gdb_assert (tp != NULL);
5401
5402       if (tp->control.may_range_step)
5403         {
5404           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5405
5406           p += xsnprintf (p, endp - p, ";r%s,%s",
5407                           phex_nz (tp->control.step_range_start,
5408                                    addr_size),
5409                           phex_nz (tp->control.step_range_end,
5410                                    addr_size));
5411         }
5412       else
5413         p += xsnprintf (p, endp - p, ";s");
5414     }
5415   else if (step)
5416     p += xsnprintf (p, endp - p, ";s");
5417   else if (siggnal != GDB_SIGNAL_0)
5418     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5419   else
5420     p += xsnprintf (p, endp - p, ";c");
5421
5422   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5423     {
5424       ptid_t nptid;
5425
5426       /* All (-1) threads of process.  */
5427       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5428
5429       p += xsnprintf (p, endp - p, ":");
5430       p = write_ptid (p, endp, nptid);
5431     }
5432   else if (!ptid_equal (ptid, minus_one_ptid))
5433     {
5434       p += xsnprintf (p, endp - p, ":");
5435       p = write_ptid (p, endp, ptid);
5436     }
5437
5438   return p;
5439 }
5440
5441 /* Clear the thread's private info on resume.  */
5442
5443 static void
5444 resume_clear_thread_private_info (struct thread_info *thread)
5445 {
5446   if (thread->priv != NULL)
5447     {
5448       thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5449       thread->priv->watch_data_address = 0;
5450     }
5451 }
5452
5453 /* Append a vCont continue-with-signal action for threads that have a
5454    non-zero stop signal.  */
5455
5456 static char *
5457 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5458 {
5459   struct thread_info *thread;
5460
5461   ALL_NON_EXITED_THREADS (thread)
5462     if (ptid_match (thread->ptid, ptid)
5463         && !ptid_equal (inferior_ptid, thread->ptid)
5464         && thread->suspend.stop_signal != GDB_SIGNAL_0)
5465       {
5466         p = append_resumption (p, endp, thread->ptid,
5467                                0, thread->suspend.stop_signal);
5468         thread->suspend.stop_signal = GDB_SIGNAL_0;
5469         resume_clear_thread_private_info (thread);
5470       }
5471
5472   return p;
5473 }
5474
5475 /* Resume the remote inferior by using a "vCont" packet.  The thread
5476    to be resumed is PTID; STEP and SIGGNAL indicate whether the
5477    resumed thread should be single-stepped and/or signalled.  If PTID
5478    equals minus_one_ptid, then all threads are resumed; the thread to
5479    be stepped and/or signalled is given in the global INFERIOR_PTID.
5480    This function returns non-zero iff it resumes the inferior.
5481
5482    This function issues a strict subset of all possible vCont commands at the
5483    moment.  */
5484
5485 static int
5486 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5487 {
5488   struct remote_state *rs = get_remote_state ();
5489   char *p;
5490   char *endp;
5491
5492   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5493     remote_vcont_probe (rs);
5494
5495   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5496     return 0;
5497
5498   p = rs->buf;
5499   endp = rs->buf + get_remote_packet_size ();
5500
5501   /* If we could generate a wider range of packets, we'd have to worry
5502      about overflowing BUF.  Should there be a generic
5503      "multi-part-packet" packet?  */
5504
5505   p += xsnprintf (p, endp - p, "vCont");
5506
5507   if (ptid_equal (ptid, magic_null_ptid))
5508     {
5509       /* MAGIC_NULL_PTID means that we don't have any active threads,
5510          so we don't have any TID numbers the inferior will
5511          understand.  Make sure to only send forms that do not specify
5512          a TID.  */
5513       append_resumption (p, endp, minus_one_ptid, step, siggnal);
5514     }
5515   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5516     {
5517       /* Resume all threads (of all processes, or of a single
5518          process), with preference for INFERIOR_PTID.  This assumes
5519          inferior_ptid belongs to the set of all threads we are about
5520          to resume.  */
5521       if (step || siggnal != GDB_SIGNAL_0)
5522         {
5523           /* Step inferior_ptid, with or without signal.  */
5524           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5525         }
5526
5527       /* Also pass down any pending signaled resumption for other
5528          threads not the current.  */
5529       p = append_pending_thread_resumptions (p, endp, ptid);
5530
5531       /* And continue others without a signal.  */
5532       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5533     }
5534   else
5535     {
5536       /* Scheduler locking; resume only PTID.  */
5537       append_resumption (p, endp, ptid, step, siggnal);
5538     }
5539
5540   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5541   putpkt (rs->buf);
5542
5543   if (target_is_non_stop_p ())
5544     {
5545       /* In non-stop, the stub replies to vCont with "OK".  The stop
5546          reply will be reported asynchronously by means of a `%Stop'
5547          notification.  */
5548       getpkt (&rs->buf, &rs->buf_size, 0);
5549       if (strcmp (rs->buf, "OK") != 0)
5550         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5551     }
5552
5553   return 1;
5554 }
5555
5556 /* Tell the remote machine to resume.  */
5557
5558 static void
5559 remote_resume (struct target_ops *ops,
5560                ptid_t ptid, int step, enum gdb_signal siggnal)
5561 {
5562   struct remote_state *rs = get_remote_state ();
5563   char *buf;
5564   struct thread_info *thread;
5565
5566   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5567      (explained in remote-notif.c:handle_notification) so
5568      remote_notif_process is not called.  We need find a place where
5569      it is safe to start a 'vNotif' sequence.  It is good to do it
5570      before resuming inferior, because inferior was stopped and no RSP
5571      traffic at that moment.  */
5572   if (!target_is_non_stop_p ())
5573     remote_notif_process (rs->notif_state, &notif_client_stop);
5574
5575   rs->last_sent_signal = siggnal;
5576   rs->last_sent_step = step;
5577
5578   /* The vCont packet doesn't need to specify threads via Hc.  */
5579   /* No reverse support (yet) for vCont.  */
5580   if (execution_direction != EXEC_REVERSE)
5581     if (remote_vcont_resume (ptid, step, siggnal))
5582       goto done;
5583
5584   /* All other supported resume packets do use Hc, so set the continue
5585      thread.  */
5586   if (ptid_equal (ptid, minus_one_ptid))
5587     set_continue_thread (any_thread_ptid);
5588   else
5589     set_continue_thread (ptid);
5590
5591   ALL_NON_EXITED_THREADS (thread)
5592     resume_clear_thread_private_info (thread);
5593
5594   buf = rs->buf;
5595   if (execution_direction == EXEC_REVERSE)
5596     {
5597       /* We don't pass signals to the target in reverse exec mode.  */
5598       if (info_verbose && siggnal != GDB_SIGNAL_0)
5599         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5600                  siggnal);
5601
5602       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5603         error (_("Remote reverse-step not supported."));
5604       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5605         error (_("Remote reverse-continue not supported."));
5606
5607       strcpy (buf, step ? "bs" : "bc");
5608     }
5609   else if (siggnal != GDB_SIGNAL_0)
5610     {
5611       buf[0] = step ? 'S' : 'C';
5612       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5613       buf[2] = tohex (((int) siggnal) & 0xf);
5614       buf[3] = '\0';
5615     }
5616   else
5617     strcpy (buf, step ? "s" : "c");
5618
5619   putpkt (buf);
5620
5621  done:
5622   /* We are about to start executing the inferior, let's register it
5623      with the event loop.  NOTE: this is the one place where all the
5624      execution commands end up.  We could alternatively do this in each
5625      of the execution commands in infcmd.c.  */
5626   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5627      into infcmd.c in order to allow inferior function calls to work
5628      NOT asynchronously.  */
5629   if (target_can_async_p ())
5630     target_async (1);
5631
5632   /* We've just told the target to resume.  The remote server will
5633      wait for the inferior to stop, and then send a stop reply.  In
5634      the mean time, we can't start another command/query ourselves
5635      because the stub wouldn't be ready to process it.  This applies
5636      only to the base all-stop protocol, however.  In non-stop (which
5637      only supports vCont), the stub replies with an "OK", and is
5638      immediate able to process further serial input.  */
5639   if (!target_is_non_stop_p ())
5640     rs->waiting_for_stop_reply = 1;
5641 }
5642 \f
5643
5644 /* Set up the signal handler for SIGINT, while the target is
5645    executing, ovewriting the 'regular' SIGINT signal handler.  */
5646 static void
5647 async_initialize_sigint_signal_handler (void)
5648 {
5649   signal (SIGINT, async_handle_remote_sigint);
5650 }
5651
5652 /* Signal handler for SIGINT, while the target is executing.  */
5653 static void
5654 async_handle_remote_sigint (int sig)
5655 {
5656   signal (sig, async_handle_remote_sigint_twice);
5657   /* Note we need to go through gdb_call_async_signal_handler in order
5658      to wake up the event loop on Windows.  */
5659   gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5660 }
5661
5662 /* Signal handler for SIGINT, installed after SIGINT has already been
5663    sent once.  It will take effect the second time that the user sends
5664    a ^C.  */
5665 static void
5666 async_handle_remote_sigint_twice (int sig)
5667 {
5668   signal (sig, async_handle_remote_sigint);
5669   /* See note in async_handle_remote_sigint.  */
5670   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5671 }
5672
5673 /* Implementation of to_check_pending_interrupt.  */
5674
5675 static void
5676 remote_check_pending_interrupt (struct target_ops *self)
5677 {
5678   struct async_signal_handler *token = async_sigint_remote_twice_token;
5679
5680   if (async_signal_handler_is_marked (token))
5681     {
5682       clear_async_signal_handler (token);
5683       call_async_signal_handler (token);
5684     }
5685 }
5686
5687 /* Perform the real interruption of the target execution, in response
5688    to a ^C.  */
5689 static void
5690 async_remote_interrupt (gdb_client_data arg)
5691 {
5692   if (remote_debug)
5693     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5694
5695   target_interrupt (inferior_ptid);
5696 }
5697
5698 /* Perform interrupt, if the first attempt did not succeed.  Just give
5699    up on the target alltogether.  */
5700 static void
5701 async_remote_interrupt_twice (gdb_client_data arg)
5702 {
5703   if (remote_debug)
5704     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5705
5706   interrupt_query ();
5707 }
5708
5709 /* Reinstall the usual SIGINT handlers, after the target has
5710    stopped.  */
5711 static void
5712 async_cleanup_sigint_signal_handler (void *dummy)
5713 {
5714   signal (SIGINT, handle_sigint);
5715 }
5716
5717 /* Send ^C to target to halt it.  Target will respond, and send us a
5718    packet.  */
5719 static void (*ofunc) (int);
5720
5721 /* The command line interface's interrupt routine.  This function is installed
5722    as a signal handler for SIGINT.  The first time a user requests an
5723    interrupt, we call remote_interrupt to send a break or ^C.  If there is no
5724    response from the target (it didn't stop when the user requested it),
5725    we ask the user if he'd like to detach from the target.  */
5726
5727 static void
5728 sync_remote_interrupt (int signo)
5729 {
5730   /* If this doesn't work, try more severe steps.  */
5731   signal (signo, sync_remote_interrupt_twice);
5732
5733   gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5734 }
5735
5736 /* The user typed ^C twice.  */
5737
5738 static void
5739 sync_remote_interrupt_twice (int signo)
5740 {
5741   signal (signo, ofunc);
5742   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5743   signal (signo, sync_remote_interrupt);
5744 }
5745
5746 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
5747    thread, all threads of a remote process, or all threads of all
5748    processes.  */
5749
5750 static void
5751 remote_stop_ns (ptid_t ptid)
5752 {
5753   struct remote_state *rs = get_remote_state ();
5754   char *p = rs->buf;
5755   char *endp = rs->buf + get_remote_packet_size ();
5756
5757   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5758     remote_vcont_probe (rs);
5759
5760   if (!rs->supports_vCont.t)
5761     error (_("Remote server does not support stopping threads"));
5762
5763   if (ptid_equal (ptid, minus_one_ptid)
5764       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5765     p += xsnprintf (p, endp - p, "vCont;t");
5766   else
5767     {
5768       ptid_t nptid;
5769
5770       p += xsnprintf (p, endp - p, "vCont;t:");
5771
5772       if (ptid_is_pid (ptid))
5773           /* All (-1) threads of process.  */
5774         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5775       else
5776         {
5777           /* Small optimization: if we already have a stop reply for
5778              this thread, no use in telling the stub we want this
5779              stopped.  */
5780           if (peek_stop_reply (ptid))
5781             return;
5782
5783           nptid = ptid;
5784         }
5785
5786       write_ptid (p, endp, nptid);
5787     }
5788
5789   /* In non-stop, we get an immediate OK reply.  The stop reply will
5790      come in asynchronously by notification.  */
5791   putpkt (rs->buf);
5792   getpkt (&rs->buf, &rs->buf_size, 0);
5793   if (strcmp (rs->buf, "OK") != 0)
5794     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5795 }
5796
5797 /* All-stop version of target_interrupt.  Sends a break or a ^C to
5798    interrupt the remote target.  It is undefined which thread of which
5799    process reports the interrupt.  */
5800
5801 static void
5802 remote_interrupt_as (void)
5803 {
5804   struct remote_state *rs = get_remote_state ();
5805
5806   rs->ctrlc_pending_p = 1;
5807
5808   /* If the inferior is stopped already, but the core didn't know
5809      about it yet, just ignore the request.  The cached wait status
5810      will be collected in remote_wait.  */
5811   if (rs->cached_wait_status)
5812     return;
5813
5814   /* Send interrupt_sequence to remote target.  */
5815   send_interrupt_sequence ();
5816 }
5817
5818 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
5819    the remote target.  It is undefined which thread of which process
5820    reports the interrupt.  Returns true if the packet is supported by
5821    the server, false otherwise.  */
5822
5823 static int
5824 remote_interrupt_ns (void)
5825 {
5826   struct remote_state *rs = get_remote_state ();
5827   char *p = rs->buf;
5828   char *endp = rs->buf + get_remote_packet_size ();
5829
5830   xsnprintf (p, endp - p, "vCtrlC");
5831
5832   /* In non-stop, we get an immediate OK reply.  The stop reply will
5833      come in asynchronously by notification.  */
5834   putpkt (rs->buf);
5835   getpkt (&rs->buf, &rs->buf_size, 0);
5836
5837   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5838     {
5839     case PACKET_OK:
5840       break;
5841     case PACKET_UNKNOWN:
5842       return 0;
5843     case PACKET_ERROR:
5844       error (_("Interrupting target failed: %s"), rs->buf);
5845     }
5846
5847   return 1;
5848 }
5849
5850 /* Implement the to_stop function for the remote targets.  */
5851
5852 static void
5853 remote_stop (struct target_ops *self, ptid_t ptid)
5854 {
5855   if (remote_debug)
5856     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5857
5858   if (target_is_non_stop_p ())
5859     remote_stop_ns (ptid);
5860   else
5861     {
5862       /* We don't currently have a way to transparently pause the
5863          remote target in all-stop mode.  Interrupt it instead.  */
5864       remote_interrupt_as ();
5865     }
5866 }
5867
5868 /* Implement the to_interrupt function for the remote targets.  */
5869
5870 static void
5871 remote_interrupt (struct target_ops *self, ptid_t ptid)
5872 {
5873   if (remote_debug)
5874     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5875
5876   if (non_stop)
5877     {
5878       /* In non-stop mode, we always stop with no signal instead.  */
5879       remote_stop_ns (ptid);
5880     }
5881   else
5882     {
5883       /* In all-stop, we emulate ^C-ing the remote target's
5884          terminal.  */
5885       if (target_is_non_stop_p ())
5886         {
5887           if (!remote_interrupt_ns ())
5888             {
5889               /* No support for ^C-ing the remote target.  Stop it
5890                  (with no signal) instead.  */
5891               remote_stop_ns (ptid);
5892             }
5893         }
5894       else
5895         remote_interrupt_as ();
5896     }
5897 }
5898
5899 /* Ask the user what to do when an interrupt is received.  */
5900
5901 static void
5902 interrupt_query (void)
5903 {
5904   struct remote_state *rs = get_remote_state ();
5905   struct cleanup *old_chain;
5906
5907   old_chain = make_cleanup_restore_target_terminal ();
5908   target_terminal_ours ();
5909
5910   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5911     {
5912       if (query (_("The target is not responding to interrupt requests.\n"
5913                    "Stop debugging it? ")))
5914         {
5915           remote_unpush_target ();
5916           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5917         }
5918     }
5919   else
5920     {
5921       if (query (_("Interrupted while waiting for the program.\n"
5922                    "Give up waiting? ")))
5923         quit ();
5924     }
5925
5926   do_cleanups (old_chain);
5927 }
5928
5929 /* Enable/disable target terminal ownership.  Most targets can use
5930    terminal groups to control terminal ownership.  Remote targets are
5931    different in that explicit transfer of ownership to/from GDB/target
5932    is required.  */
5933
5934 static void
5935 remote_terminal_inferior (struct target_ops *self)
5936 {
5937   if (!target_async_permitted)
5938     /* Nothing to do.  */
5939     return;
5940
5941   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5942      idempotent.  The event-loop GDB talking to an asynchronous target
5943      with a synchronous command calls this function from both
5944      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
5945      transfer the terminal to the target when it shouldn't this guard
5946      can go away.  */
5947   if (!remote_async_terminal_ours_p)
5948     return;
5949   delete_file_handler (input_fd);
5950   remote_async_terminal_ours_p = 0;
5951   async_initialize_sigint_signal_handler ();
5952   /* NOTE: At this point we could also register our selves as the
5953      recipient of all input.  Any characters typed could then be
5954      passed on down to the target.  */
5955 }
5956
5957 static void
5958 remote_terminal_ours (struct target_ops *self)
5959 {
5960   if (!target_async_permitted)
5961     /* Nothing to do.  */
5962     return;
5963
5964   /* See FIXME in remote_terminal_inferior.  */
5965   if (remote_async_terminal_ours_p)
5966     return;
5967   async_cleanup_sigint_signal_handler (NULL);
5968   add_file_handler (input_fd, stdin_event_handler, 0);
5969   remote_async_terminal_ours_p = 1;
5970 }
5971
5972 static void
5973 remote_console_output (char *msg)
5974 {
5975   char *p;
5976
5977   for (p = msg; p[0] && p[1]; p += 2)
5978     {
5979       char tb[2];
5980       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5981
5982       tb[0] = c;
5983       tb[1] = 0;
5984       fputs_unfiltered (tb, gdb_stdtarg);
5985     }
5986   gdb_flush (gdb_stdtarg);
5987 }
5988
5989 typedef struct cached_reg
5990 {
5991   int num;
5992   gdb_byte data[MAX_REGISTER_SIZE];
5993 } cached_reg_t;
5994
5995 DEF_VEC_O(cached_reg_t);
5996
5997 typedef struct stop_reply
5998 {
5999   struct notif_event base;
6000
6001   /* The identifier of the thread about this event  */
6002   ptid_t ptid;
6003
6004   /* The remote state this event is associated with.  When the remote
6005      connection, represented by a remote_state object, is closed,
6006      all the associated stop_reply events should be released.  */
6007   struct remote_state *rs;
6008
6009   struct target_waitstatus ws;
6010
6011   /* Expedited registers.  This makes remote debugging a bit more
6012      efficient for those targets that provide critical registers as
6013      part of their normal status mechanism (as another roundtrip to
6014      fetch them is avoided).  */
6015   VEC(cached_reg_t) *regcache;
6016
6017   enum target_stop_reason stop_reason;
6018
6019   CORE_ADDR watch_data_address;
6020
6021   int core;
6022 } *stop_reply_p;
6023
6024 DECLARE_QUEUE_P (stop_reply_p);
6025 DEFINE_QUEUE_P (stop_reply_p);
6026 /* The list of already fetched and acknowledged stop events.  This
6027    queue is used for notification Stop, and other notifications
6028    don't need queue for their events, because the notification events
6029    of Stop can't be consumed immediately, so that events should be
6030    queued first, and be consumed by remote_wait_{ns,as} one per
6031    time.  Other notifications can consume their events immediately,
6032    so queue is not needed for them.  */
6033 static QUEUE (stop_reply_p) *stop_reply_queue;
6034
6035 static void
6036 stop_reply_xfree (struct stop_reply *r)
6037 {
6038   notif_event_xfree ((struct notif_event *) r);
6039 }
6040
6041 /* Return the length of the stop reply queue.  */
6042
6043 static int
6044 stop_reply_queue_length (void)
6045 {
6046   return QUEUE_length (stop_reply_p, stop_reply_queue);
6047 }
6048
6049 static void
6050 remote_notif_stop_parse (struct notif_client *self, char *buf,
6051                          struct notif_event *event)
6052 {
6053   remote_parse_stop_reply (buf, (struct stop_reply *) event);
6054 }
6055
6056 static void
6057 remote_notif_stop_ack (struct notif_client *self, char *buf,
6058                        struct notif_event *event)
6059 {
6060   struct stop_reply *stop_reply = (struct stop_reply *) event;
6061
6062   /* acknowledge */
6063   putpkt ((char *) self->ack_command);
6064
6065   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6066       /* We got an unknown stop reply.  */
6067       error (_("Unknown stop reply"));
6068
6069   push_stop_reply (stop_reply);
6070 }
6071
6072 static int
6073 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6074 {
6075   /* We can't get pending events in remote_notif_process for
6076      notification stop, and we have to do this in remote_wait_ns
6077      instead.  If we fetch all queued events from stub, remote stub
6078      may exit and we have no chance to process them back in
6079      remote_wait_ns.  */
6080   mark_async_event_handler (remote_async_inferior_event_token);
6081   return 0;
6082 }
6083
6084 static void
6085 stop_reply_dtr (struct notif_event *event)
6086 {
6087   struct stop_reply *r = (struct stop_reply *) event;
6088
6089   VEC_free (cached_reg_t, r->regcache);
6090 }
6091
6092 static struct notif_event *
6093 remote_notif_stop_alloc_reply (void)
6094 {
6095   /* We cast to a pointer to the "base class".  */
6096   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6097
6098   r->dtr = stop_reply_dtr;
6099
6100   return r;
6101 }
6102
6103 /* A client of notification Stop.  */
6104
6105 struct notif_client notif_client_stop =
6106 {
6107   "Stop",
6108   "vStopped",
6109   remote_notif_stop_parse,
6110   remote_notif_stop_ack,
6111   remote_notif_stop_can_get_pending_events,
6112   remote_notif_stop_alloc_reply,
6113   REMOTE_NOTIF_STOP,
6114 };
6115
6116 /* A parameter to pass data in and out.  */
6117
6118 struct queue_iter_param
6119 {
6120   void *input;
6121   struct stop_reply *output;
6122 };
6123
6124 /* Determine if THREAD is a pending fork parent thread.  ARG contains
6125    the pid of the process that owns the threads we want to check, or
6126    -1 if we want to check all threads.  */
6127
6128 static int
6129 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6130                         ptid_t thread_ptid)
6131 {
6132   if (ws->kind == TARGET_WAITKIND_FORKED
6133       || ws->kind == TARGET_WAITKIND_VFORKED)
6134     {
6135       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6136         return 1;
6137     }
6138
6139   return 0;
6140 }
6141
6142 /* Check whether EVENT is a fork event, and if it is, remove the
6143    fork child from the context list passed in DATA.  */
6144
6145 static int
6146 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6147                               QUEUE_ITER (stop_reply_p) *iter,
6148                               stop_reply_p event,
6149                               void *data)
6150 {
6151   struct queue_iter_param *param = (struct queue_iter_param *) data;
6152   struct threads_listing_context *context
6153     = (struct threads_listing_context *) param->input;
6154
6155   if (event->ws.kind == TARGET_WAITKIND_FORKED
6156       || event->ws.kind == TARGET_WAITKIND_VFORKED
6157       || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6158     threads_listing_context_remove (&event->ws, context);
6159
6160   return 1;
6161 }
6162
6163 /* If CONTEXT contains any fork child threads that have not been
6164    reported yet, remove them from the CONTEXT list.  If such a
6165    thread exists it is because we are stopped at a fork catchpoint
6166    and have not yet called follow_fork, which will set up the
6167    host-side data structures for the new process.  */
6168
6169 static void
6170 remove_new_fork_children (struct threads_listing_context *context)
6171 {
6172   struct thread_info * thread;
6173   int pid = -1;
6174   struct notif_client *notif = &notif_client_stop;
6175   struct queue_iter_param param;
6176
6177   /* For any threads stopped at a fork event, remove the corresponding
6178      fork child threads from the CONTEXT list.  */
6179   ALL_NON_EXITED_THREADS (thread)
6180     {
6181       struct target_waitstatus *ws = &thread->pending_follow;
6182
6183       if (is_pending_fork_parent (ws, pid, thread->ptid))
6184         {
6185           threads_listing_context_remove (ws, context);
6186         }
6187     }
6188
6189   /* Check for any pending fork events (not reported or processed yet)
6190      in process PID and remove those fork child threads from the
6191      CONTEXT list as well.  */
6192   remote_notif_get_pending_events (notif);
6193   param.input = context;
6194   param.output = NULL;
6195   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6196                  remove_child_of_pending_fork, &param);
6197 }
6198
6199 /* Remove stop replies in the queue if its pid is equal to the given
6200    inferior's pid.  */
6201
6202 static int
6203 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6204                                 QUEUE_ITER (stop_reply_p) *iter,
6205                                 stop_reply_p event,
6206                                 void *data)
6207 {
6208   struct queue_iter_param *param = (struct queue_iter_param *) data;
6209   struct inferior *inf = (struct inferior *) param->input;
6210
6211   if (ptid_get_pid (event->ptid) == inf->pid)
6212     {
6213       stop_reply_xfree (event);
6214       QUEUE_remove_elem (stop_reply_p, q, iter);
6215     }
6216
6217   return 1;
6218 }
6219
6220 /* Discard all pending stop replies of inferior INF.  */
6221
6222 static void
6223 discard_pending_stop_replies (struct inferior *inf)
6224 {
6225   int i;
6226   struct queue_iter_param param;
6227   struct stop_reply *reply;
6228   struct remote_state *rs = get_remote_state ();
6229   struct remote_notif_state *rns = rs->notif_state;
6230
6231   /* This function can be notified when an inferior exists.  When the
6232      target is not remote, the notification state is NULL.  */
6233   if (rs->remote_desc == NULL)
6234     return;
6235
6236   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6237
6238   /* Discard the in-flight notification.  */
6239   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6240     {
6241       stop_reply_xfree (reply);
6242       rns->pending_event[notif_client_stop.id] = NULL;
6243     }
6244
6245   param.input = inf;
6246   param.output = NULL;
6247   /* Discard the stop replies we have already pulled with
6248      vStopped.  */
6249   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6250                  remove_stop_reply_for_inferior, &param);
6251 }
6252
6253 /* If its remote state is equal to the given remote state,
6254    remove EVENT from the stop reply queue.  */
6255
6256 static int
6257 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6258                                    QUEUE_ITER (stop_reply_p) *iter,
6259                                    stop_reply_p event,
6260                                    void *data)
6261 {
6262   struct queue_iter_param *param = (struct queue_iter_param *) data;
6263   struct remote_state *rs = (struct remote_state *) param->input;
6264
6265   if (event->rs == rs)
6266     {
6267       stop_reply_xfree (event);
6268       QUEUE_remove_elem (stop_reply_p, q, iter);
6269     }
6270
6271   return 1;
6272 }
6273
6274 /* Discard the stop replies for RS in stop_reply_queue.  */
6275
6276 static void
6277 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6278 {
6279   struct queue_iter_param param;
6280
6281   param.input = rs;
6282   param.output = NULL;
6283   /* Discard the stop replies we have already pulled with
6284      vStopped.  */
6285   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6286                  remove_stop_reply_of_remote_state, &param);
6287 }
6288
6289 /* A parameter to pass data in and out.  */
6290
6291 static int
6292 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6293                                    QUEUE_ITER (stop_reply_p) *iter,
6294                                    stop_reply_p event,
6295                                    void *data)
6296 {
6297   struct queue_iter_param *param = (struct queue_iter_param *) data;
6298   ptid_t *ptid = (ptid_t *) param->input;
6299
6300   if (ptid_match (event->ptid, *ptid))
6301     {
6302       param->output = event;
6303       QUEUE_remove_elem (stop_reply_p, q, iter);
6304       return 0;
6305     }
6306
6307   return 1;
6308 }
6309
6310 /* Remove the first reply in 'stop_reply_queue' which matches
6311    PTID.  */
6312
6313 static struct stop_reply *
6314 remote_notif_remove_queued_reply (ptid_t ptid)
6315 {
6316   struct queue_iter_param param;
6317
6318   param.input = &ptid;
6319   param.output = NULL;
6320
6321   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6322                  remote_notif_remove_once_on_match, &param);
6323   if (notif_debug)
6324     fprintf_unfiltered (gdb_stdlog,
6325                         "notif: discard queued event: 'Stop' in %s\n",
6326                         target_pid_to_str (ptid));
6327
6328   return param.output;
6329 }
6330
6331 /* Look for a queued stop reply belonging to PTID.  If one is found,
6332    remove it from the queue, and return it.  Returns NULL if none is
6333    found.  If there are still queued events left to process, tell the
6334    event loop to get back to target_wait soon.  */
6335
6336 static struct stop_reply *
6337 queued_stop_reply (ptid_t ptid)
6338 {
6339   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6340
6341   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6342     /* There's still at least an event left.  */
6343     mark_async_event_handler (remote_async_inferior_event_token);
6344
6345   return r;
6346 }
6347
6348 /* Push a fully parsed stop reply in the stop reply queue.  Since we
6349    know that we now have at least one queued event left to pass to the
6350    core side, tell the event loop to get back to target_wait soon.  */
6351
6352 static void
6353 push_stop_reply (struct stop_reply *new_event)
6354 {
6355   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6356
6357   if (notif_debug)
6358     fprintf_unfiltered (gdb_stdlog,
6359                         "notif: push 'Stop' %s to queue %d\n",
6360                         target_pid_to_str (new_event->ptid),
6361                         QUEUE_length (stop_reply_p,
6362                                       stop_reply_queue));
6363
6364   mark_async_event_handler (remote_async_inferior_event_token);
6365 }
6366
6367 static int
6368 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6369                               QUEUE_ITER (stop_reply_p) *iter,
6370                               struct stop_reply *event,
6371                               void *data)
6372 {
6373   ptid_t *ptid = (ptid_t *) data;
6374
6375   return !(ptid_equal (*ptid, event->ptid)
6376            && event->ws.kind == TARGET_WAITKIND_STOPPED);
6377 }
6378
6379 /* Returns true if we have a stop reply for PTID.  */
6380
6381 static int
6382 peek_stop_reply (ptid_t ptid)
6383 {
6384   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6385                          stop_reply_match_ptid_and_ws, &ptid);
6386 }
6387
6388 /* Skip PACKET until the next semi-colon (or end of string).  */
6389
6390 static char *
6391 skip_to_semicolon (char *p)
6392 {
6393   while (*p != '\0' && *p != ';')
6394     p++;
6395   return p;
6396 }
6397
6398 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
6399    starting with P and ending with PEND matches PREFIX.  */
6400
6401 static int
6402 strprefix (const char *p, const char *pend, const char *prefix)
6403 {
6404   for ( ; p < pend; p++, prefix++)
6405     if (*p != *prefix)
6406       return 0;
6407   return *prefix == '\0';
6408 }
6409
6410 /* Parse the stop reply in BUF.  Either the function succeeds, and the
6411    result is stored in EVENT, or throws an error.  */
6412
6413 static void
6414 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6415 {
6416   struct remote_arch_state *rsa = get_remote_arch_state ();
6417   ULONGEST addr;
6418   char *p;
6419   int skipregs = 0;
6420
6421   event->ptid = null_ptid;
6422   event->rs = get_remote_state ();
6423   event->ws.kind = TARGET_WAITKIND_IGNORE;
6424   event->ws.value.integer = 0;
6425   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6426   event->regcache = NULL;
6427   event->core = -1;
6428
6429   switch (buf[0])
6430     {
6431     case 'T':           /* Status with PC, SP, FP, ...  */
6432       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
6433       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
6434             ss = signal number
6435             n... = register number
6436             r... = register contents
6437       */
6438
6439       p = &buf[3];      /* after Txx */
6440       while (*p)
6441         {
6442           char *p1;
6443           int fieldsize;
6444
6445           p1 = strchr (p, ':');
6446           if (p1 == NULL)
6447             error (_("Malformed packet(a) (missing colon): %s\n\
6448 Packet: '%s'\n"),
6449                    p, buf);
6450           if (p == p1)
6451             error (_("Malformed packet(a) (missing register number): %s\n\
6452 Packet: '%s'\n"),
6453                    p, buf);
6454
6455           /* Some "registers" are actually extended stop information.
6456              Note if you're adding a new entry here: GDB 7.9 and
6457              earlier assume that all register "numbers" that start
6458              with an hex digit are real register numbers.  Make sure
6459              the server only sends such a packet if it knows the
6460              client understands it.  */
6461
6462           if (strprefix (p, p1, "thread"))
6463             event->ptid = read_ptid (++p1, &p);
6464           else if (strprefix (p, p1, "syscall_entry"))
6465             {
6466               ULONGEST sysno;
6467
6468               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6469               p = unpack_varlen_hex (++p1, &sysno);
6470               event->ws.value.syscall_number = (int) sysno;
6471             }
6472           else if (strprefix (p, p1, "syscall_return"))
6473             {
6474               ULONGEST sysno;
6475
6476               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6477               p = unpack_varlen_hex (++p1, &sysno);
6478               event->ws.value.syscall_number = (int) sysno;
6479             }
6480           else if (strprefix (p, p1, "watch")
6481                    || strprefix (p, p1, "rwatch")
6482                    || strprefix (p, p1, "awatch"))
6483             {
6484               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6485               p = unpack_varlen_hex (++p1, &addr);
6486               event->watch_data_address = (CORE_ADDR) addr;
6487             }
6488           else if (strprefix (p, p1, "swbreak"))
6489             {
6490               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6491
6492               /* Make sure the stub doesn't forget to indicate support
6493                  with qSupported.  */
6494               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6495                 error (_("Unexpected swbreak stop reason"));
6496
6497               /* The value part is documented as "must be empty",
6498                  though we ignore it, in case we ever decide to make
6499                  use of it in a backward compatible way.  */
6500               p = skip_to_semicolon (p1 + 1);
6501             }
6502           else if (strprefix (p, p1, "hwbreak"))
6503             {
6504               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6505
6506               /* Make sure the stub doesn't forget to indicate support
6507                  with qSupported.  */
6508               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6509                 error (_("Unexpected hwbreak stop reason"));
6510
6511               /* See above.  */
6512               p = skip_to_semicolon (p1 + 1);
6513             }
6514           else if (strprefix (p, p1, "library"))
6515             {
6516               event->ws.kind = TARGET_WAITKIND_LOADED;
6517               p = skip_to_semicolon (p1 + 1);
6518             }
6519           else if (strprefix (p, p1, "replaylog"))
6520             {
6521               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6522               /* p1 will indicate "begin" or "end", but it makes
6523                  no difference for now, so ignore it.  */
6524               p = skip_to_semicolon (p1 + 1);
6525             }
6526           else if (strprefix (p, p1, "core"))
6527             {
6528               ULONGEST c;
6529
6530               p = unpack_varlen_hex (++p1, &c);
6531               event->core = c;
6532             }
6533           else if (strprefix (p, p1, "fork"))
6534             {
6535               event->ws.value.related_pid = read_ptid (++p1, &p);
6536               event->ws.kind = TARGET_WAITKIND_FORKED;
6537             }
6538           else if (strprefix (p, p1, "vfork"))
6539             {
6540               event->ws.value.related_pid = read_ptid (++p1, &p);
6541               event->ws.kind = TARGET_WAITKIND_VFORKED;
6542             }
6543           else if (strprefix (p, p1, "vforkdone"))
6544             {
6545               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6546               p = skip_to_semicolon (p1 + 1);
6547             }
6548           else if (strprefix (p, p1, "exec"))
6549             {
6550               ULONGEST ignored;
6551               char pathname[PATH_MAX];
6552               int pathlen;
6553
6554               /* Determine the length of the execd pathname.  */
6555               p = unpack_varlen_hex (++p1, &ignored);
6556               pathlen = (p - p1) / 2;
6557
6558               /* Save the pathname for event reporting and for
6559                  the next run command.  */
6560               hex2bin (p1, (gdb_byte *) pathname, pathlen);
6561               pathname[pathlen] = '\0';
6562
6563               /* This is freed during event handling.  */
6564               event->ws.value.execd_pathname = xstrdup (pathname);
6565               event->ws.kind = TARGET_WAITKIND_EXECD;
6566
6567               /* Skip the registers included in this packet, since
6568                  they may be for an architecture different from the
6569                  one used by the original program.  */
6570               skipregs = 1;
6571             }
6572           else if (strprefix (p, p1, "create"))
6573             {
6574               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6575               p = skip_to_semicolon (p1 + 1);
6576             }
6577           else
6578             {
6579               ULONGEST pnum;
6580               char *p_temp;
6581
6582               if (skipregs)
6583                 {
6584                   p = skip_to_semicolon (p1 + 1);
6585                   p++;
6586                   continue;
6587                 }
6588
6589               /* Maybe a real ``P'' register number.  */
6590               p_temp = unpack_varlen_hex (p, &pnum);
6591               /* If the first invalid character is the colon, we got a
6592                  register number.  Otherwise, it's an unknown stop
6593                  reason.  */
6594               if (p_temp == p1)
6595                 {
6596                   struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6597                   cached_reg_t cached_reg;
6598
6599                   if (reg == NULL)
6600                     error (_("Remote sent bad register number %s: %s\n\
6601 Packet: '%s'\n"),
6602                            hex_string (pnum), p, buf);
6603
6604                   cached_reg.num = reg->regnum;
6605
6606                   p = p1 + 1;
6607                   fieldsize = hex2bin (p, cached_reg.data,
6608                                        register_size (target_gdbarch (),
6609                                                       reg->regnum));
6610                   p += 2 * fieldsize;
6611                   if (fieldsize < register_size (target_gdbarch (),
6612                                                  reg->regnum))
6613                     warning (_("Remote reply is too short: %s"), buf);
6614
6615                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6616                 }
6617               else
6618                 {
6619                   /* Not a number.  Silently skip unknown optional
6620                      info.  */
6621                   p = skip_to_semicolon (p1 + 1);
6622                 }
6623             }
6624
6625           if (*p != ';')
6626             error (_("Remote register badly formatted: %s\nhere: %s"),
6627                    buf, p);
6628           ++p;
6629         }
6630
6631       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6632         break;
6633
6634       /* fall through */
6635     case 'S':           /* Old style status, just signal only.  */
6636       {
6637         int sig;
6638
6639         event->ws.kind = TARGET_WAITKIND_STOPPED;
6640         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6641         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6642           event->ws.value.sig = (enum gdb_signal) sig;
6643         else
6644           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6645       }
6646       break;
6647     case 'w':           /* Thread exited.  */
6648       {
6649         char *p;
6650         ULONGEST value;
6651
6652         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6653         p = unpack_varlen_hex (&buf[1], &value);
6654         event->ws.value.integer = value;
6655         if (*p != ';')
6656           error (_("stop reply packet badly formatted: %s"), buf);
6657         event->ptid = read_ptid (++p, NULL);
6658         break;
6659       }
6660     case 'W':           /* Target exited.  */
6661     case 'X':
6662       {
6663         char *p;
6664         int pid;
6665         ULONGEST value;
6666
6667         /* GDB used to accept only 2 hex chars here.  Stubs should
6668            only send more if they detect GDB supports multi-process
6669            support.  */
6670         p = unpack_varlen_hex (&buf[1], &value);
6671
6672         if (buf[0] == 'W')
6673           {
6674             /* The remote process exited.  */
6675             event->ws.kind = TARGET_WAITKIND_EXITED;
6676             event->ws.value.integer = value;
6677           }
6678         else
6679           {
6680             /* The remote process exited with a signal.  */
6681             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6682             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6683               event->ws.value.sig = (enum gdb_signal) value;
6684             else
6685               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6686           }
6687
6688         /* If no process is specified, assume inferior_ptid.  */
6689         pid = ptid_get_pid (inferior_ptid);
6690         if (*p == '\0')
6691           ;
6692         else if (*p == ';')
6693           {
6694             p++;
6695
6696             if (*p == '\0')
6697               ;
6698             else if (startswith (p, "process:"))
6699               {
6700                 ULONGEST upid;
6701
6702                 p += sizeof ("process:") - 1;
6703                 unpack_varlen_hex (p, &upid);
6704                 pid = upid;
6705               }
6706             else
6707               error (_("unknown stop reply packet: %s"), buf);
6708           }
6709         else
6710           error (_("unknown stop reply packet: %s"), buf);
6711         event->ptid = pid_to_ptid (pid);
6712       }
6713       break;
6714     case 'N':
6715       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6716       event->ptid = minus_one_ptid;
6717       break;
6718     }
6719
6720   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6721     error (_("No process or thread specified in stop reply: %s"), buf);
6722 }
6723
6724 /* When the stub wants to tell GDB about a new notification reply, it
6725    sends a notification (%Stop, for example).  Those can come it at
6726    any time, hence, we have to make sure that any pending
6727    putpkt/getpkt sequence we're making is finished, before querying
6728    the stub for more events with the corresponding ack command
6729    (vStopped, for example).  E.g., if we started a vStopped sequence
6730    immediately upon receiving the notification, something like this
6731    could happen:
6732
6733     1.1) --> Hg 1
6734     1.2) <-- OK
6735     1.3) --> g
6736     1.4) <-- %Stop
6737     1.5) --> vStopped
6738     1.6) <-- (registers reply to step #1.3)
6739
6740    Obviously, the reply in step #1.6 would be unexpected to a vStopped
6741    query.
6742
6743    To solve this, whenever we parse a %Stop notification successfully,
6744    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6745    doing whatever we were doing:
6746
6747     2.1) --> Hg 1
6748     2.2) <-- OK
6749     2.3) --> g
6750     2.4) <-- %Stop
6751       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6752     2.5) <-- (registers reply to step #2.3)
6753
6754    Eventualy after step #2.5, we return to the event loop, which
6755    notices there's an event on the
6756    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6757    associated callback --- the function below.  At this point, we're
6758    always safe to start a vStopped sequence. :
6759
6760     2.6) --> vStopped
6761     2.7) <-- T05 thread:2
6762     2.8) --> vStopped
6763     2.9) --> OK
6764 */
6765
6766 void
6767 remote_notif_get_pending_events (struct notif_client *nc)
6768 {
6769   struct remote_state *rs = get_remote_state ();
6770
6771   if (rs->notif_state->pending_event[nc->id] != NULL)
6772     {
6773       if (notif_debug)
6774         fprintf_unfiltered (gdb_stdlog,
6775                             "notif: process: '%s' ack pending event\n",
6776                             nc->name);
6777
6778       /* acknowledge */
6779       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6780       rs->notif_state->pending_event[nc->id] = NULL;
6781
6782       while (1)
6783         {
6784           getpkt (&rs->buf, &rs->buf_size, 0);
6785           if (strcmp (rs->buf, "OK") == 0)
6786             break;
6787           else
6788             remote_notif_ack (nc, rs->buf);
6789         }
6790     }
6791   else
6792     {
6793       if (notif_debug)
6794         fprintf_unfiltered (gdb_stdlog,
6795                             "notif: process: '%s' no pending reply\n",
6796                             nc->name);
6797     }
6798 }
6799
6800 /* Called when it is decided that STOP_REPLY holds the info of the
6801    event that is to be returned to the core.  This function always
6802    destroys STOP_REPLY.  */
6803
6804 static ptid_t
6805 process_stop_reply (struct stop_reply *stop_reply,
6806                     struct target_waitstatus *status)
6807 {
6808   ptid_t ptid;
6809
6810   *status = stop_reply->ws;
6811   ptid = stop_reply->ptid;
6812
6813   /* If no thread/process was reported by the stub, assume the current
6814      inferior.  */
6815   if (ptid_equal (ptid, null_ptid))
6816     ptid = inferior_ptid;
6817
6818   if (status->kind != TARGET_WAITKIND_EXITED
6819       && status->kind != TARGET_WAITKIND_SIGNALLED
6820       && status->kind != TARGET_WAITKIND_NO_RESUMED)
6821     {
6822       struct remote_state *rs = get_remote_state ();
6823       struct private_thread_info *remote_thr;
6824
6825       /* Expedited registers.  */
6826       if (stop_reply->regcache)
6827         {
6828           struct regcache *regcache
6829             = get_thread_arch_regcache (ptid, target_gdbarch ());
6830           cached_reg_t *reg;
6831           int ix;
6832
6833           for (ix = 0;
6834                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6835                ix++)
6836             regcache_raw_supply (regcache, reg->num, reg->data);
6837           VEC_free (cached_reg_t, stop_reply->regcache);
6838         }
6839
6840       remote_notice_new_inferior (ptid, 0);
6841       remote_thr = demand_private_info (ptid);
6842       remote_thr->core = stop_reply->core;
6843       remote_thr->stop_reason = stop_reply->stop_reason;
6844       remote_thr->watch_data_address = stop_reply->watch_data_address;
6845     }
6846
6847   stop_reply_xfree (stop_reply);
6848   return ptid;
6849 }
6850
6851 /* The non-stop mode version of target_wait.  */
6852
6853 static ptid_t
6854 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6855 {
6856   struct remote_state *rs = get_remote_state ();
6857   struct stop_reply *stop_reply;
6858   int ret;
6859   int is_notif = 0;
6860
6861   /* If in non-stop mode, get out of getpkt even if a
6862      notification is received.  */
6863
6864   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6865                               0 /* forever */, &is_notif);
6866   while (1)
6867     {
6868       if (ret != -1 && !is_notif)
6869         switch (rs->buf[0])
6870           {
6871           case 'E':             /* Error of some sort.  */
6872             /* We're out of sync with the target now.  Did it continue
6873                or not?  We can't tell which thread it was in non-stop,
6874                so just ignore this.  */
6875             warning (_("Remote failure reply: %s"), rs->buf);
6876             break;
6877           case 'O':             /* Console output.  */
6878             remote_console_output (rs->buf + 1);
6879             break;
6880           default:
6881             warning (_("Invalid remote reply: %s"), rs->buf);
6882             break;
6883           }
6884
6885       /* Acknowledge a pending stop reply that may have arrived in the
6886          mean time.  */
6887       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6888         remote_notif_get_pending_events (&notif_client_stop);
6889
6890       /* If indeed we noticed a stop reply, we're done.  */
6891       stop_reply = queued_stop_reply (ptid);
6892       if (stop_reply != NULL)
6893         return process_stop_reply (stop_reply, status);
6894
6895       /* Still no event.  If we're just polling for an event, then
6896          return to the event loop.  */
6897       if (options & TARGET_WNOHANG)
6898         {
6899           status->kind = TARGET_WAITKIND_IGNORE;
6900           return minus_one_ptid;
6901         }
6902
6903       /* Otherwise do a blocking wait.  */
6904       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6905                                   1 /* forever */, &is_notif);
6906     }
6907 }
6908
6909 /* Wait until the remote machine stops, then return, storing status in
6910    STATUS just as `wait' would.  */
6911
6912 static ptid_t
6913 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6914 {
6915   struct remote_state *rs = get_remote_state ();
6916   ptid_t event_ptid = null_ptid;
6917   char *buf;
6918   struct stop_reply *stop_reply;
6919
6920  again:
6921
6922   status->kind = TARGET_WAITKIND_IGNORE;
6923   status->value.integer = 0;
6924
6925   stop_reply = queued_stop_reply (ptid);
6926   if (stop_reply != NULL)
6927     return process_stop_reply (stop_reply, status);
6928
6929   if (rs->cached_wait_status)
6930     /* Use the cached wait status, but only once.  */
6931     rs->cached_wait_status = 0;
6932   else
6933     {
6934       int ret;
6935       int is_notif;
6936       int forever = ((options & TARGET_WNOHANG) == 0
6937                      && wait_forever_enabled_p);
6938
6939       if (!rs->waiting_for_stop_reply)
6940         {
6941           status->kind = TARGET_WAITKIND_NO_RESUMED;
6942           return minus_one_ptid;
6943         }
6944
6945       if (!target_is_async_p ())
6946         {
6947           ofunc = signal (SIGINT, sync_remote_interrupt);
6948           /* If the user hit C-c before this packet, or between packets,
6949              pretend that it was hit right here.  */
6950           if (check_quit_flag ())
6951             {
6952               clear_quit_flag ();
6953               sync_remote_interrupt (SIGINT);
6954             }
6955         }
6956
6957       /* FIXME: cagney/1999-09-27: If we're in async mode we should
6958          _never_ wait for ever -> test on target_is_async_p().
6959          However, before we do that we need to ensure that the caller
6960          knows how to take the target into/out of async mode.  */
6961       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6962                                   forever, &is_notif);
6963
6964       if (!target_is_async_p ())
6965         signal (SIGINT, ofunc);
6966
6967       /* GDB gets a notification.  Return to core as this event is
6968          not interesting.  */
6969       if (ret != -1 && is_notif)
6970         return minus_one_ptid;
6971
6972       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6973         return minus_one_ptid;
6974     }
6975
6976   buf = rs->buf;
6977
6978   /* Assume that the target has acknowledged Ctrl-C unless we receive
6979      an 'F' or 'O' packet.  */
6980   if (buf[0] != 'F' && buf[0] != 'O')
6981     rs->ctrlc_pending_p = 0;
6982
6983   switch (buf[0])
6984     {
6985     case 'E':           /* Error of some sort.  */
6986       /* We're out of sync with the target now.  Did it continue or
6987          not?  Not is more likely, so report a stop.  */
6988       rs->waiting_for_stop_reply = 0;
6989
6990       warning (_("Remote failure reply: %s"), buf);
6991       status->kind = TARGET_WAITKIND_STOPPED;
6992       status->value.sig = GDB_SIGNAL_0;
6993       break;
6994     case 'F':           /* File-I/O request.  */
6995       remote_fileio_request (buf, rs->ctrlc_pending_p);
6996       rs->ctrlc_pending_p = 0;
6997       break;
6998     case 'N': case 'T': case 'S': case 'X': case 'W':
6999       {
7000         struct stop_reply *stop_reply;
7001
7002         /* There is a stop reply to handle.  */
7003         rs->waiting_for_stop_reply = 0;
7004
7005         stop_reply
7006           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7007                                                       rs->buf);
7008
7009         event_ptid = process_stop_reply (stop_reply, status);
7010         break;
7011       }
7012     case 'O':           /* Console output.  */
7013       remote_console_output (buf + 1);
7014       break;
7015     case '\0':
7016       if (rs->last_sent_signal != GDB_SIGNAL_0)
7017         {
7018           /* Zero length reply means that we tried 'S' or 'C' and the
7019              remote system doesn't support it.  */
7020           target_terminal_ours_for_output ();
7021           printf_filtered
7022             ("Can't send signals to this remote system.  %s not sent.\n",
7023              gdb_signal_to_name (rs->last_sent_signal));
7024           rs->last_sent_signal = GDB_SIGNAL_0;
7025           target_terminal_inferior ();
7026
7027           strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
7028           putpkt ((char *) buf);
7029           break;
7030         }
7031       /* else fallthrough */
7032     default:
7033       warning (_("Invalid remote reply: %s"), buf);
7034       break;
7035     }
7036
7037   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7038     return minus_one_ptid;
7039   else if (status->kind == TARGET_WAITKIND_IGNORE)
7040     {
7041       /* Nothing interesting happened.  If we're doing a non-blocking
7042          poll, we're done.  Otherwise, go back to waiting.  */
7043       if (options & TARGET_WNOHANG)
7044         return minus_one_ptid;
7045       else
7046         goto again;
7047     }
7048   else if (status->kind != TARGET_WAITKIND_EXITED
7049            && status->kind != TARGET_WAITKIND_SIGNALLED)
7050     {
7051       if (!ptid_equal (event_ptid, null_ptid))
7052         record_currthread (rs, event_ptid);
7053       else
7054         event_ptid = inferior_ptid;
7055     }
7056   else
7057     /* A process exit.  Invalidate our notion of current thread.  */
7058     record_currthread (rs, minus_one_ptid);
7059
7060   return event_ptid;
7061 }
7062
7063 /* Wait until the remote machine stops, then return, storing status in
7064    STATUS just as `wait' would.  */
7065
7066 static ptid_t
7067 remote_wait (struct target_ops *ops,
7068              ptid_t ptid, struct target_waitstatus *status, int options)
7069 {
7070   ptid_t event_ptid;
7071
7072   if (target_is_non_stop_p ())
7073     event_ptid = remote_wait_ns (ptid, status, options);
7074   else
7075     event_ptid = remote_wait_as (ptid, status, options);
7076
7077   if (target_is_async_p ())
7078     {
7079       /* If there are are events left in the queue tell the event loop
7080          to return here.  */
7081       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7082         mark_async_event_handler (remote_async_inferior_event_token);
7083     }
7084
7085   return event_ptid;
7086 }
7087
7088 /* Fetch a single register using a 'p' packet.  */
7089
7090 static int
7091 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7092 {
7093   struct remote_state *rs = get_remote_state ();
7094   char *buf, *p;
7095   char regp[MAX_REGISTER_SIZE];
7096   int i;
7097
7098   if (packet_support (PACKET_p) == PACKET_DISABLE)
7099     return 0;
7100
7101   if (reg->pnum == -1)
7102     return 0;
7103
7104   p = rs->buf;
7105   *p++ = 'p';
7106   p += hexnumstr (p, reg->pnum);
7107   *p++ = '\0';
7108   putpkt (rs->buf);
7109   getpkt (&rs->buf, &rs->buf_size, 0);
7110
7111   buf = rs->buf;
7112
7113   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7114     {
7115     case PACKET_OK:
7116       break;
7117     case PACKET_UNKNOWN:
7118       return 0;
7119     case PACKET_ERROR:
7120       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7121              gdbarch_register_name (get_regcache_arch (regcache), 
7122                                     reg->regnum), 
7123              buf);
7124     }
7125
7126   /* If this register is unfetchable, tell the regcache.  */
7127   if (buf[0] == 'x')
7128     {
7129       regcache_raw_supply (regcache, reg->regnum, NULL);
7130       return 1;
7131     }
7132
7133   /* Otherwise, parse and supply the value.  */
7134   p = buf;
7135   i = 0;
7136   while (p[0] != 0)
7137     {
7138       if (p[1] == 0)
7139         error (_("fetch_register_using_p: early buf termination"));
7140
7141       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7142       p += 2;
7143     }
7144   regcache_raw_supply (regcache, reg->regnum, regp);
7145   return 1;
7146 }
7147
7148 /* Fetch the registers included in the target's 'g' packet.  */
7149
7150 static int
7151 send_g_packet (void)
7152 {
7153   struct remote_state *rs = get_remote_state ();
7154   int buf_len;
7155
7156   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7157   remote_send (&rs->buf, &rs->buf_size);
7158
7159   /* We can get out of synch in various cases.  If the first character
7160      in the buffer is not a hex character, assume that has happened
7161      and try to fetch another packet to read.  */
7162   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7163          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7164          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7165          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
7166     {
7167       if (remote_debug)
7168         fprintf_unfiltered (gdb_stdlog,
7169                             "Bad register packet; fetching a new packet\n");
7170       getpkt (&rs->buf, &rs->buf_size, 0);
7171     }
7172
7173   buf_len = strlen (rs->buf);
7174
7175   /* Sanity check the received packet.  */
7176   if (buf_len % 2 != 0)
7177     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7178
7179   return buf_len / 2;
7180 }
7181
7182 static void
7183 process_g_packet (struct regcache *regcache)
7184 {
7185   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7186   struct remote_state *rs = get_remote_state ();
7187   struct remote_arch_state *rsa = get_remote_arch_state ();
7188   int i, buf_len;
7189   char *p;
7190   char *regs;
7191
7192   buf_len = strlen (rs->buf);
7193
7194   /* Further sanity checks, with knowledge of the architecture.  */
7195   if (buf_len > 2 * rsa->sizeof_g_packet)
7196     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7197
7198   /* Save the size of the packet sent to us by the target.  It is used
7199      as a heuristic when determining the max size of packets that the
7200      target can safely receive.  */
7201   if (rsa->actual_register_packet_size == 0)
7202     rsa->actual_register_packet_size = buf_len;
7203
7204   /* If this is smaller than we guessed the 'g' packet would be,
7205      update our records.  A 'g' reply that doesn't include a register's
7206      value implies either that the register is not available, or that
7207      the 'p' packet must be used.  */
7208   if (buf_len < 2 * rsa->sizeof_g_packet)
7209     {
7210       rsa->sizeof_g_packet = buf_len / 2;
7211
7212       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7213         {
7214           if (rsa->regs[i].pnum == -1)
7215             continue;
7216
7217           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7218             rsa->regs[i].in_g_packet = 0;
7219           else
7220             rsa->regs[i].in_g_packet = 1;
7221         }
7222     }
7223
7224   regs = (char *) alloca (rsa->sizeof_g_packet);
7225
7226   /* Unimplemented registers read as all bits zero.  */
7227   memset (regs, 0, rsa->sizeof_g_packet);
7228
7229   /* Reply describes registers byte by byte, each byte encoded as two
7230      hex characters.  Suck them all up, then supply them to the
7231      register cacheing/storage mechanism.  */
7232
7233   p = rs->buf;
7234   for (i = 0; i < rsa->sizeof_g_packet; i++)
7235     {
7236       if (p[0] == 0 || p[1] == 0)
7237         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
7238         internal_error (__FILE__, __LINE__,
7239                         _("unexpected end of 'g' packet reply"));
7240
7241       if (p[0] == 'x' && p[1] == 'x')
7242         regs[i] = 0;            /* 'x' */
7243       else
7244         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7245       p += 2;
7246     }
7247
7248   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7249     {
7250       struct packet_reg *r = &rsa->regs[i];
7251
7252       if (r->in_g_packet)
7253         {
7254           if (r->offset * 2 >= strlen (rs->buf))
7255             /* This shouldn't happen - we adjusted in_g_packet above.  */
7256             internal_error (__FILE__, __LINE__,
7257                             _("unexpected end of 'g' packet reply"));
7258           else if (rs->buf[r->offset * 2] == 'x')
7259             {
7260               gdb_assert (r->offset * 2 < strlen (rs->buf));
7261               /* The register isn't available, mark it as such (at
7262                  the same time setting the value to zero).  */
7263               regcache_raw_supply (regcache, r->regnum, NULL);
7264             }
7265           else
7266             regcache_raw_supply (regcache, r->regnum,
7267                                  regs + r->offset);
7268         }
7269     }
7270 }
7271
7272 static void
7273 fetch_registers_using_g (struct regcache *regcache)
7274 {
7275   send_g_packet ();
7276   process_g_packet (regcache);
7277 }
7278
7279 /* Make the remote selected traceframe match GDB's selected
7280    traceframe.  */
7281
7282 static void
7283 set_remote_traceframe (void)
7284 {
7285   int newnum;
7286   struct remote_state *rs = get_remote_state ();
7287
7288   if (rs->remote_traceframe_number == get_traceframe_number ())
7289     return;
7290
7291   /* Avoid recursion, remote_trace_find calls us again.  */
7292   rs->remote_traceframe_number = get_traceframe_number ();
7293
7294   newnum = target_trace_find (tfind_number,
7295                               get_traceframe_number (), 0, 0, NULL);
7296
7297   /* Should not happen.  If it does, all bets are off.  */
7298   if (newnum != get_traceframe_number ())
7299     warning (_("could not set remote traceframe"));
7300 }
7301
7302 static void
7303 remote_fetch_registers (struct target_ops *ops,
7304                         struct regcache *regcache, int regnum)
7305 {
7306   struct remote_arch_state *rsa = get_remote_arch_state ();
7307   int i;
7308
7309   set_remote_traceframe ();
7310   set_general_thread (inferior_ptid);
7311
7312   if (regnum >= 0)
7313     {
7314       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7315
7316       gdb_assert (reg != NULL);
7317
7318       /* If this register might be in the 'g' packet, try that first -
7319          we are likely to read more than one register.  If this is the
7320          first 'g' packet, we might be overly optimistic about its
7321          contents, so fall back to 'p'.  */
7322       if (reg->in_g_packet)
7323         {
7324           fetch_registers_using_g (regcache);
7325           if (reg->in_g_packet)
7326             return;
7327         }
7328
7329       if (fetch_register_using_p (regcache, reg))
7330         return;
7331
7332       /* This register is not available.  */
7333       regcache_raw_supply (regcache, reg->regnum, NULL);
7334
7335       return;
7336     }
7337
7338   fetch_registers_using_g (regcache);
7339
7340   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7341     if (!rsa->regs[i].in_g_packet)
7342       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7343         {
7344           /* This register is not available.  */
7345           regcache_raw_supply (regcache, i, NULL);
7346         }
7347 }
7348
7349 /* Prepare to store registers.  Since we may send them all (using a
7350    'G' request), we have to read out the ones we don't want to change
7351    first.  */
7352
7353 static void
7354 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7355 {
7356   struct remote_arch_state *rsa = get_remote_arch_state ();
7357   int i;
7358   gdb_byte buf[MAX_REGISTER_SIZE];
7359
7360   /* Make sure the entire registers array is valid.  */
7361   switch (packet_support (PACKET_P))
7362     {
7363     case PACKET_DISABLE:
7364     case PACKET_SUPPORT_UNKNOWN:
7365       /* Make sure all the necessary registers are cached.  */
7366       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7367         if (rsa->regs[i].in_g_packet)
7368           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7369       break;
7370     case PACKET_ENABLE:
7371       break;
7372     }
7373 }
7374
7375 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
7376    packet was not recognized.  */
7377
7378 static int
7379 store_register_using_P (const struct regcache *regcache, 
7380                         struct packet_reg *reg)
7381 {
7382   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7383   struct remote_state *rs = get_remote_state ();
7384   /* Try storing a single register.  */
7385   char *buf = rs->buf;
7386   gdb_byte regp[MAX_REGISTER_SIZE];
7387   char *p;
7388
7389   if (packet_support (PACKET_P) == PACKET_DISABLE)
7390     return 0;
7391
7392   if (reg->pnum == -1)
7393     return 0;
7394
7395   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7396   p = buf + strlen (buf);
7397   regcache_raw_collect (regcache, reg->regnum, regp);
7398   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7399   putpkt (rs->buf);
7400   getpkt (&rs->buf, &rs->buf_size, 0);
7401
7402   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7403     {
7404     case PACKET_OK:
7405       return 1;
7406     case PACKET_ERROR:
7407       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7408              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7409     case PACKET_UNKNOWN:
7410       return 0;
7411     default:
7412       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7413     }
7414 }
7415
7416 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7417    contents of the register cache buffer.  FIXME: ignores errors.  */
7418
7419 static void
7420 store_registers_using_G (const struct regcache *regcache)
7421 {
7422   struct remote_state *rs = get_remote_state ();
7423   struct remote_arch_state *rsa = get_remote_arch_state ();
7424   gdb_byte *regs;
7425   char *p;
7426
7427   /* Extract all the registers in the regcache copying them into a
7428      local buffer.  */
7429   {
7430     int i;
7431
7432     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7433     memset (regs, 0, rsa->sizeof_g_packet);
7434     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7435       {
7436         struct packet_reg *r = &rsa->regs[i];
7437
7438         if (r->in_g_packet)
7439           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7440       }
7441   }
7442
7443   /* Command describes registers byte by byte,
7444      each byte encoded as two hex characters.  */
7445   p = rs->buf;
7446   *p++ = 'G';
7447   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7448      updated.  */
7449   bin2hex (regs, p, rsa->sizeof_g_packet);
7450   putpkt (rs->buf);
7451   getpkt (&rs->buf, &rs->buf_size, 0);
7452   if (packet_check_result (rs->buf) == PACKET_ERROR)
7453     error (_("Could not write registers; remote failure reply '%s'"), 
7454            rs->buf);
7455 }
7456
7457 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7458    of the register cache buffer.  FIXME: ignores errors.  */
7459
7460 static void
7461 remote_store_registers (struct target_ops *ops,
7462                         struct regcache *regcache, int regnum)
7463 {
7464   struct remote_arch_state *rsa = get_remote_arch_state ();
7465   int i;
7466
7467   set_remote_traceframe ();
7468   set_general_thread (inferior_ptid);
7469
7470   if (regnum >= 0)
7471     {
7472       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7473
7474       gdb_assert (reg != NULL);
7475
7476       /* Always prefer to store registers using the 'P' packet if
7477          possible; we often change only a small number of registers.
7478          Sometimes we change a larger number; we'd need help from a
7479          higher layer to know to use 'G'.  */
7480       if (store_register_using_P (regcache, reg))
7481         return;
7482
7483       /* For now, don't complain if we have no way to write the
7484          register.  GDB loses track of unavailable registers too
7485          easily.  Some day, this may be an error.  We don't have
7486          any way to read the register, either...  */
7487       if (!reg->in_g_packet)
7488         return;
7489
7490       store_registers_using_G (regcache);
7491       return;
7492     }
7493
7494   store_registers_using_G (regcache);
7495
7496   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7497     if (!rsa->regs[i].in_g_packet)
7498       if (!store_register_using_P (regcache, &rsa->regs[i]))
7499         /* See above for why we do not issue an error here.  */
7500         continue;
7501 }
7502 \f
7503
7504 /* Return the number of hex digits in num.  */
7505
7506 static int
7507 hexnumlen (ULONGEST num)
7508 {
7509   int i;
7510
7511   for (i = 0; num != 0; i++)
7512     num >>= 4;
7513
7514   return max (i, 1);
7515 }
7516
7517 /* Set BUF to the minimum number of hex digits representing NUM.  */
7518
7519 static int
7520 hexnumstr (char *buf, ULONGEST num)
7521 {
7522   int len = hexnumlen (num);
7523
7524   return hexnumnstr (buf, num, len);
7525 }
7526
7527
7528 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
7529
7530 static int
7531 hexnumnstr (char *buf, ULONGEST num, int width)
7532 {
7533   int i;
7534
7535   buf[width] = '\0';
7536
7537   for (i = width - 1; i >= 0; i--)
7538     {
7539       buf[i] = "0123456789abcdef"[(num & 0xf)];
7540       num >>= 4;
7541     }
7542
7543   return width;
7544 }
7545
7546 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
7547
7548 static CORE_ADDR
7549 remote_address_masked (CORE_ADDR addr)
7550 {
7551   unsigned int address_size = remote_address_size;
7552
7553   /* If "remoteaddresssize" was not set, default to target address size.  */
7554   if (!address_size)
7555     address_size = gdbarch_addr_bit (target_gdbarch ());
7556
7557   if (address_size > 0
7558       && address_size < (sizeof (ULONGEST) * 8))
7559     {
7560       /* Only create a mask when that mask can safely be constructed
7561          in a ULONGEST variable.  */
7562       ULONGEST mask = 1;
7563
7564       mask = (mask << address_size) - 1;
7565       addr &= mask;
7566     }
7567   return addr;
7568 }
7569
7570 /* Determine whether the remote target supports binary downloading.
7571    This is accomplished by sending a no-op memory write of zero length
7572    to the target at the specified address. It does not suffice to send
7573    the whole packet, since many stubs strip the eighth bit and
7574    subsequently compute a wrong checksum, which causes real havoc with
7575    remote_write_bytes.
7576
7577    NOTE: This can still lose if the serial line is not eight-bit
7578    clean.  In cases like this, the user should clear "remote
7579    X-packet".  */
7580
7581 static void
7582 check_binary_download (CORE_ADDR addr)
7583 {
7584   struct remote_state *rs = get_remote_state ();
7585
7586   switch (packet_support (PACKET_X))
7587     {
7588     case PACKET_DISABLE:
7589       break;
7590     case PACKET_ENABLE:
7591       break;
7592     case PACKET_SUPPORT_UNKNOWN:
7593       {
7594         char *p;
7595
7596         p = rs->buf;
7597         *p++ = 'X';
7598         p += hexnumstr (p, (ULONGEST) addr);
7599         *p++ = ',';
7600         p += hexnumstr (p, (ULONGEST) 0);
7601         *p++ = ':';
7602         *p = '\0';
7603
7604         putpkt_binary (rs->buf, (int) (p - rs->buf));
7605         getpkt (&rs->buf, &rs->buf_size, 0);
7606
7607         if (rs->buf[0] == '\0')
7608           {
7609             if (remote_debug)
7610               fprintf_unfiltered (gdb_stdlog,
7611                                   "binary downloading NOT "
7612                                   "supported by target\n");
7613             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7614           }
7615         else
7616           {
7617             if (remote_debug)
7618               fprintf_unfiltered (gdb_stdlog,
7619                                   "binary downloading supported by target\n");
7620             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7621           }
7622         break;
7623       }
7624     }
7625 }
7626
7627 /* Helper function to resize the payload in order to try to get a good
7628    alignment.  We try to write an amount of data such that the next write will
7629    start on an address aligned on REMOTE_ALIGN_WRITES.  */
7630
7631 static int
7632 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7633 {
7634   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7635 }
7636
7637 /* Write memory data directly to the remote machine.
7638    This does not inform the data cache; the data cache uses this.
7639    HEADER is the starting part of the packet.
7640    MEMADDR is the address in the remote memory space.
7641    MYADDR is the address of the buffer in our space.
7642    LEN_UNITS is the number of addressable units to write.
7643    UNIT_SIZE is the length in bytes of an addressable unit.
7644    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7645    should send data as binary ('X'), or hex-encoded ('M').
7646
7647    The function creates packet of the form
7648        <HEADER><ADDRESS>,<LENGTH>:<DATA>
7649
7650    where encoding of <DATA> is terminated by PACKET_FORMAT.
7651
7652    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7653    are omitted.
7654
7655    Return the transferred status, error or OK (an
7656    'enum target_xfer_status' value).  Save the number of addressable units
7657    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
7658
7659    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7660    exchange between gdb and the stub could look like (?? in place of the
7661    checksum):
7662
7663    -> $m1000,4#??
7664    <- aaaabbbbccccdddd
7665
7666    -> $M1000,3:eeeeffffeeee#??
7667    <- OK
7668
7669    -> $m1000,4#??
7670    <- eeeeffffeeeedddd  */
7671
7672 static enum target_xfer_status
7673 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7674                         const gdb_byte *myaddr, ULONGEST len_units,
7675                         int unit_size, ULONGEST *xfered_len_units,
7676                         char packet_format, int use_length)
7677 {
7678   struct remote_state *rs = get_remote_state ();
7679   char *p;
7680   char *plen = NULL;
7681   int plenlen = 0;
7682   int todo_units;
7683   int units_written;
7684   int payload_capacity_bytes;
7685   int payload_length_bytes;
7686
7687   if (packet_format != 'X' && packet_format != 'M')
7688     internal_error (__FILE__, __LINE__,
7689                     _("remote_write_bytes_aux: bad packet format"));
7690
7691   if (len_units == 0)
7692     return TARGET_XFER_EOF;
7693
7694   payload_capacity_bytes = get_memory_write_packet_size ();
7695
7696   /* The packet buffer will be large enough for the payload;
7697      get_memory_packet_size ensures this.  */
7698   rs->buf[0] = '\0';
7699
7700   /* Compute the size of the actual payload by subtracting out the
7701      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
7702
7703   payload_capacity_bytes -= strlen ("$,:#NN");
7704   if (!use_length)
7705     /* The comma won't be used.  */
7706     payload_capacity_bytes += 1;
7707   payload_capacity_bytes -= strlen (header);
7708   payload_capacity_bytes -= hexnumlen (memaddr);
7709
7710   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
7711
7712   strcat (rs->buf, header);
7713   p = rs->buf + strlen (header);
7714
7715   /* Compute a best guess of the number of bytes actually transfered.  */
7716   if (packet_format == 'X')
7717     {
7718       /* Best guess at number of bytes that will fit.  */
7719       todo_units = min (len_units, payload_capacity_bytes / unit_size);
7720       if (use_length)
7721         payload_capacity_bytes -= hexnumlen (todo_units);
7722       todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7723     }
7724   else
7725     {
7726       /* Number of bytes that will fit.  */
7727       todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7728       if (use_length)
7729         payload_capacity_bytes -= hexnumlen (todo_units);
7730       todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7731     }
7732
7733   if (todo_units <= 0)
7734     internal_error (__FILE__, __LINE__,
7735                     _("minimum packet size too small to write data"));
7736
7737   /* If we already need another packet, then try to align the end
7738      of this packet to a useful boundary.  */
7739   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7740     todo_units = align_for_efficient_write (todo_units, memaddr);
7741
7742   /* Append "<memaddr>".  */
7743   memaddr = remote_address_masked (memaddr);
7744   p += hexnumstr (p, (ULONGEST) memaddr);
7745
7746   if (use_length)
7747     {
7748       /* Append ",".  */
7749       *p++ = ',';
7750
7751       /* Append the length and retain its location and size.  It may need to be
7752          adjusted once the packet body has been created.  */
7753       plen = p;
7754       plenlen = hexnumstr (p, (ULONGEST) todo_units);
7755       p += plenlen;
7756     }
7757
7758   /* Append ":".  */
7759   *p++ = ':';
7760   *p = '\0';
7761
7762   /* Append the packet body.  */
7763   if (packet_format == 'X')
7764     {
7765       /* Binary mode.  Send target system values byte by byte, in
7766          increasing byte addresses.  Only escape certain critical
7767          characters.  */
7768       payload_length_bytes =
7769           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7770                                 &units_written, payload_capacity_bytes);
7771
7772       /* If not all TODO units fit, then we'll need another packet.  Make
7773          a second try to keep the end of the packet aligned.  Don't do
7774          this if the packet is tiny.  */
7775       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7776         {
7777           int new_todo_units;
7778
7779           new_todo_units = align_for_efficient_write (units_written, memaddr);
7780
7781           if (new_todo_units != units_written)
7782             payload_length_bytes =
7783                 remote_escape_output (myaddr, new_todo_units, unit_size,
7784                                       (gdb_byte *) p, &units_written,
7785                                       payload_capacity_bytes);
7786         }
7787
7788       p += payload_length_bytes;
7789       if (use_length && units_written < todo_units)
7790         {
7791           /* Escape chars have filled up the buffer prematurely,
7792              and we have actually sent fewer units than planned.
7793              Fix-up the length field of the packet.  Use the same
7794              number of characters as before.  */
7795           plen += hexnumnstr (plen, (ULONGEST) units_written,
7796                               plenlen);
7797           *plen = ':';  /* overwrite \0 from hexnumnstr() */
7798         }
7799     }
7800   else
7801     {
7802       /* Normal mode: Send target system values byte by byte, in
7803          increasing byte addresses.  Each byte is encoded as a two hex
7804          value.  */
7805       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7806       units_written = todo_units;
7807     }
7808
7809   putpkt_binary (rs->buf, (int) (p - rs->buf));
7810   getpkt (&rs->buf, &rs->buf_size, 0);
7811
7812   if (rs->buf[0] == 'E')
7813     return TARGET_XFER_E_IO;
7814
7815   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7816      send fewer units than we'd planned.  */
7817   *xfered_len_units = (ULONGEST) units_written;
7818   return TARGET_XFER_OK;
7819 }
7820
7821 /* Write memory data directly to the remote machine.
7822    This does not inform the data cache; the data cache uses this.
7823    MEMADDR is the address in the remote memory space.
7824    MYADDR is the address of the buffer in our space.
7825    LEN is the number of bytes.
7826
7827    Return the transferred status, error or OK (an
7828    'enum target_xfer_status' value).  Save the number of bytes
7829    transferred in *XFERED_LEN.  Only transfer a single packet.  */
7830
7831 static enum target_xfer_status
7832 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7833                     int unit_size, ULONGEST *xfered_len)
7834 {
7835   char *packet_format = 0;
7836
7837   /* Check whether the target supports binary download.  */
7838   check_binary_download (memaddr);
7839
7840   switch (packet_support (PACKET_X))
7841     {
7842     case PACKET_ENABLE:
7843       packet_format = "X";
7844       break;
7845     case PACKET_DISABLE:
7846       packet_format = "M";
7847       break;
7848     case PACKET_SUPPORT_UNKNOWN:
7849       internal_error (__FILE__, __LINE__,
7850                       _("remote_write_bytes: bad internal state"));
7851     default:
7852       internal_error (__FILE__, __LINE__, _("bad switch"));
7853     }
7854
7855   return remote_write_bytes_aux (packet_format,
7856                                  memaddr, myaddr, len, unit_size, xfered_len,
7857                                  packet_format[0], 1);
7858 }
7859
7860 /* Read memory data directly from the remote machine.
7861    This does not use the data cache; the data cache uses this.
7862    MEMADDR is the address in the remote memory space.
7863    MYADDR is the address of the buffer in our space.
7864    LEN_UNITS is the number of addressable memory units to read..
7865    UNIT_SIZE is the length in bytes of an addressable unit.
7866
7867    Return the transferred status, error or OK (an
7868    'enum target_xfer_status' value).  Save the number of bytes
7869    transferred in *XFERED_LEN_UNITS.
7870
7871    See the comment of remote_write_bytes_aux for an example of
7872    memory read/write exchange between gdb and the stub.  */
7873
7874 static enum target_xfer_status
7875 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7876                      int unit_size, ULONGEST *xfered_len_units)
7877 {
7878   struct remote_state *rs = get_remote_state ();
7879   int buf_size_bytes;           /* Max size of packet output buffer.  */
7880   char *p;
7881   int todo_units;
7882   int decoded_bytes;
7883
7884   buf_size_bytes = get_memory_read_packet_size ();
7885   /* The packet buffer will be large enough for the payload;
7886      get_memory_packet_size ensures this.  */
7887
7888   /* Number of units that will fit.  */
7889   todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7890
7891   /* Construct "m"<memaddr>","<len>".  */
7892   memaddr = remote_address_masked (memaddr);
7893   p = rs->buf;
7894   *p++ = 'm';
7895   p += hexnumstr (p, (ULONGEST) memaddr);
7896   *p++ = ',';
7897   p += hexnumstr (p, (ULONGEST) todo_units);
7898   *p = '\0';
7899   putpkt (rs->buf);
7900   getpkt (&rs->buf, &rs->buf_size, 0);
7901   if (rs->buf[0] == 'E'
7902       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7903       && rs->buf[3] == '\0')
7904     return TARGET_XFER_E_IO;
7905   /* Reply describes memory byte by byte, each byte encoded as two hex
7906      characters.  */
7907   p = rs->buf;
7908   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7909   /* Return what we have.  Let higher layers handle partial reads.  */
7910   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7911   return TARGET_XFER_OK;
7912 }
7913
7914 /* Using the set of read-only target sections of remote, read live
7915    read-only memory.
7916
7917    For interface/parameters/return description see target.h,
7918    to_xfer_partial.  */
7919
7920 static enum target_xfer_status
7921 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7922                                    ULONGEST memaddr, ULONGEST len,
7923                                    int unit_size, ULONGEST *xfered_len)
7924 {
7925   struct target_section *secp;
7926   struct target_section_table *table;
7927
7928   secp = target_section_by_addr (ops, memaddr);
7929   if (secp != NULL
7930       && (bfd_get_section_flags (secp->the_bfd_section->owner,
7931                                  secp->the_bfd_section)
7932           & SEC_READONLY))
7933     {
7934       struct target_section *p;
7935       ULONGEST memend = memaddr + len;
7936
7937       table = target_get_section_table (ops);
7938
7939       for (p = table->sections; p < table->sections_end; p++)
7940         {
7941           if (memaddr >= p->addr)
7942             {
7943               if (memend <= p->endaddr)
7944                 {
7945                   /* Entire transfer is within this section.  */
7946                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7947                                               xfered_len);
7948                 }
7949               else if (memaddr >= p->endaddr)
7950                 {
7951                   /* This section ends before the transfer starts.  */
7952                   continue;
7953                 }
7954               else
7955                 {
7956                   /* This section overlaps the transfer.  Just do half.  */
7957                   len = p->endaddr - memaddr;
7958                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7959                                               xfered_len);
7960                 }
7961             }
7962         }
7963     }
7964
7965   return TARGET_XFER_EOF;
7966 }
7967
7968 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7969    first if the requested memory is unavailable in traceframe.
7970    Otherwise, fall back to remote_read_bytes_1.  */
7971
7972 static enum target_xfer_status
7973 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7974                    gdb_byte *myaddr, ULONGEST len, int unit_size,
7975                    ULONGEST *xfered_len)
7976 {
7977   if (len == 0)
7978     return TARGET_XFER_EOF;
7979
7980   if (get_traceframe_number () != -1)
7981     {
7982       VEC(mem_range_s) *available;
7983
7984       /* If we fail to get the set of available memory, then the
7985          target does not support querying traceframe info, and so we
7986          attempt reading from the traceframe anyway (assuming the
7987          target implements the old QTro packet then).  */
7988       if (traceframe_available_memory (&available, memaddr, len))
7989         {
7990           struct cleanup *old_chain;
7991
7992           old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7993
7994           if (VEC_empty (mem_range_s, available)
7995               || VEC_index (mem_range_s, available, 0)->start != memaddr)
7996             {
7997               enum target_xfer_status res;
7998
7999               /* Don't read into the traceframe's available
8000                  memory.  */
8001               if (!VEC_empty (mem_range_s, available))
8002                 {
8003                   LONGEST oldlen = len;
8004
8005                   len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8006                   gdb_assert (len <= oldlen);
8007                 }
8008
8009               do_cleanups (old_chain);
8010
8011               /* This goes through the topmost target again.  */
8012               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8013                                                        len, unit_size, xfered_len);
8014               if (res == TARGET_XFER_OK)
8015                 return TARGET_XFER_OK;
8016               else
8017                 {
8018                   /* No use trying further, we know some memory starting
8019                      at MEMADDR isn't available.  */
8020                   *xfered_len = len;
8021                   return TARGET_XFER_UNAVAILABLE;
8022                 }
8023             }
8024
8025           /* Don't try to read more than how much is available, in
8026              case the target implements the deprecated QTro packet to
8027              cater for older GDBs (the target's knowledge of read-only
8028              sections may be outdated by now).  */
8029           len = VEC_index (mem_range_s, available, 0)->length;
8030
8031           do_cleanups (old_chain);
8032         }
8033     }
8034
8035   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8036 }
8037
8038 \f
8039
8040 /* Sends a packet with content determined by the printf format string
8041    FORMAT and the remaining arguments, then gets the reply.  Returns
8042    whether the packet was a success, a failure, or unknown.  */
8043
8044 static enum packet_result remote_send_printf (const char *format, ...)
8045   ATTRIBUTE_PRINTF (1, 2);
8046
8047 static enum packet_result
8048 remote_send_printf (const char *format, ...)
8049 {
8050   struct remote_state *rs = get_remote_state ();
8051   int max_size = get_remote_packet_size ();
8052   va_list ap;
8053
8054   va_start (ap, format);
8055
8056   rs->buf[0] = '\0';
8057   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8058     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8059
8060   if (putpkt (rs->buf) < 0)
8061     error (_("Communication problem with target."));
8062
8063   rs->buf[0] = '\0';
8064   getpkt (&rs->buf, &rs->buf_size, 0);
8065
8066   return packet_check_result (rs->buf);
8067 }
8068
8069 static void
8070 restore_remote_timeout (void *p)
8071 {
8072   int value = *(int *)p;
8073
8074   remote_timeout = value;
8075 }
8076
8077 /* Flash writing can take quite some time.  We'll set
8078    effectively infinite timeout for flash operations.
8079    In future, we'll need to decide on a better approach.  */
8080 static const int remote_flash_timeout = 1000;
8081
8082 static void
8083 remote_flash_erase (struct target_ops *ops,
8084                     ULONGEST address, LONGEST length)
8085 {
8086   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8087   int saved_remote_timeout = remote_timeout;
8088   enum packet_result ret;
8089   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8090                                           &saved_remote_timeout);
8091
8092   remote_timeout = remote_flash_timeout;
8093
8094   ret = remote_send_printf ("vFlashErase:%s,%s",
8095                             phex (address, addr_size),
8096                             phex (length, 4));
8097   switch (ret)
8098     {
8099     case PACKET_UNKNOWN:
8100       error (_("Remote target does not support flash erase"));
8101     case PACKET_ERROR:
8102       error (_("Error erasing flash with vFlashErase packet"));
8103     default:
8104       break;
8105     }
8106
8107   do_cleanups (back_to);
8108 }
8109
8110 static enum target_xfer_status
8111 remote_flash_write (struct target_ops *ops, ULONGEST address,
8112                     ULONGEST length, ULONGEST *xfered_len,
8113                     const gdb_byte *data)
8114 {
8115   int saved_remote_timeout = remote_timeout;
8116   enum target_xfer_status ret;
8117   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8118                                           &saved_remote_timeout);
8119
8120   remote_timeout = remote_flash_timeout;
8121   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8122                                 xfered_len,'X', 0);
8123   do_cleanups (back_to);
8124
8125   return ret;
8126 }
8127
8128 static void
8129 remote_flash_done (struct target_ops *ops)
8130 {
8131   int saved_remote_timeout = remote_timeout;
8132   int ret;
8133   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8134                                           &saved_remote_timeout);
8135
8136   remote_timeout = remote_flash_timeout;
8137   ret = remote_send_printf ("vFlashDone");
8138   do_cleanups (back_to);
8139
8140   switch (ret)
8141     {
8142     case PACKET_UNKNOWN:
8143       error (_("Remote target does not support vFlashDone"));
8144     case PACKET_ERROR:
8145       error (_("Error finishing flash operation"));
8146     default:
8147       break;
8148     }
8149 }
8150
8151 static void
8152 remote_files_info (struct target_ops *ignore)
8153 {
8154   puts_filtered ("Debugging a target over a serial line.\n");
8155 }
8156 \f
8157 /* Stuff for dealing with the packets which are part of this protocol.
8158    See comment at top of file for details.  */
8159
8160 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8161    error to higher layers.  Called when a serial error is detected.
8162    The exception message is STRING, followed by a colon and a blank,
8163    the system error message for errno at function entry and final dot
8164    for output compatibility with throw_perror_with_name.  */
8165
8166 static void
8167 unpush_and_perror (const char *string)
8168 {
8169   int saved_errno = errno;
8170
8171   remote_unpush_target ();
8172   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8173                safe_strerror (saved_errno));
8174 }
8175
8176 /* Read a single character from the remote end.  */
8177
8178 static int
8179 readchar (int timeout)
8180 {
8181   int ch;
8182   struct remote_state *rs = get_remote_state ();
8183
8184   ch = serial_readchar (rs->remote_desc, timeout);
8185
8186   if (ch >= 0)
8187     return ch;
8188
8189   switch ((enum serial_rc) ch)
8190     {
8191     case SERIAL_EOF:
8192       remote_unpush_target ();
8193       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8194       /* no return */
8195     case SERIAL_ERROR:
8196       unpush_and_perror (_("Remote communication error.  "
8197                            "Target disconnected."));
8198       /* no return */
8199     case SERIAL_TIMEOUT:
8200       break;
8201     }
8202   return ch;
8203 }
8204
8205 /* Wrapper for serial_write that closes the target and throws if
8206    writing fails.  */
8207
8208 static void
8209 remote_serial_write (const char *str, int len)
8210 {
8211   struct remote_state *rs = get_remote_state ();
8212
8213   if (serial_write (rs->remote_desc, str, len))
8214     {
8215       unpush_and_perror (_("Remote communication error.  "
8216                            "Target disconnected."));
8217     }
8218 }
8219
8220 /* Send the command in *BUF to the remote machine, and read the reply
8221    into *BUF.  Report an error if we get an error reply.  Resize
8222    *BUF using xrealloc if necessary to hold the result, and update
8223    *SIZEOF_BUF.  */
8224
8225 static void
8226 remote_send (char **buf,
8227              long *sizeof_buf)
8228 {
8229   putpkt (*buf);
8230   getpkt (buf, sizeof_buf, 0);
8231
8232   if ((*buf)[0] == 'E')
8233     error (_("Remote failure reply: %s"), *buf);
8234 }
8235
8236 /* Return a pointer to an xmalloc'ed string representing an escaped
8237    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
8238    etc.  The caller is responsible for releasing the returned
8239    memory.  */
8240
8241 static char *
8242 escape_buffer (const char *buf, int n)
8243 {
8244   struct cleanup *old_chain;
8245   struct ui_file *stb;
8246   char *str;
8247
8248   stb = mem_fileopen ();
8249   old_chain = make_cleanup_ui_file_delete (stb);
8250
8251   fputstrn_unfiltered (buf, n, '\\', stb);
8252   str = ui_file_xstrdup (stb, NULL);
8253   do_cleanups (old_chain);
8254   return str;
8255 }
8256
8257 /* Display a null-terminated packet on stdout, for debugging, using C
8258    string notation.  */
8259
8260 static void
8261 print_packet (const char *buf)
8262 {
8263   puts_filtered ("\"");
8264   fputstr_filtered (buf, '"', gdb_stdout);
8265   puts_filtered ("\"");
8266 }
8267
8268 int
8269 putpkt (const char *buf)
8270 {
8271   return putpkt_binary (buf, strlen (buf));
8272 }
8273
8274 /* Send a packet to the remote machine, with error checking.  The data
8275    of the packet is in BUF.  The string in BUF can be at most
8276    get_remote_packet_size () - 5 to account for the $, # and checksum,
8277    and for a possible /0 if we are debugging (remote_debug) and want
8278    to print the sent packet as a string.  */
8279
8280 static int
8281 putpkt_binary (const char *buf, int cnt)
8282 {
8283   struct remote_state *rs = get_remote_state ();
8284   int i;
8285   unsigned char csum = 0;
8286   char *buf2 = (char *) xmalloc (cnt + 6);
8287   struct cleanup *old_chain = make_cleanup (xfree, buf2);
8288
8289   int ch;
8290   int tcount = 0;
8291   char *p;
8292   char *message;
8293
8294   /* Catch cases like trying to read memory or listing threads while
8295      we're waiting for a stop reply.  The remote server wouldn't be
8296      ready to handle this request, so we'd hang and timeout.  We don't
8297      have to worry about this in synchronous mode, because in that
8298      case it's not possible to issue a command while the target is
8299      running.  This is not a problem in non-stop mode, because in that
8300      case, the stub is always ready to process serial input.  */
8301   if (!target_is_non_stop_p ()
8302       && target_is_async_p ()
8303       && rs->waiting_for_stop_reply)
8304     {
8305       error (_("Cannot execute this command while the target is running.\n"
8306                "Use the \"interrupt\" command to stop the target\n"
8307                "and then try again."));
8308     }
8309
8310   /* We're sending out a new packet.  Make sure we don't look at a
8311      stale cached response.  */
8312   rs->cached_wait_status = 0;
8313
8314   /* Copy the packet into buffer BUF2, encapsulating it
8315      and giving it a checksum.  */
8316
8317   p = buf2;
8318   *p++ = '$';
8319
8320   for (i = 0; i < cnt; i++)
8321     {
8322       csum += buf[i];
8323       *p++ = buf[i];
8324     }
8325   *p++ = '#';
8326   *p++ = tohex ((csum >> 4) & 0xf);
8327   *p++ = tohex (csum & 0xf);
8328
8329   /* Send it over and over until we get a positive ack.  */
8330
8331   while (1)
8332     {
8333       int started_error_output = 0;
8334
8335       if (remote_debug)
8336         {
8337           struct cleanup *old_chain;
8338           char *str;
8339
8340           *p = '\0';
8341           str = escape_buffer (buf2, p - buf2);
8342           old_chain = make_cleanup (xfree, str);
8343           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8344           gdb_flush (gdb_stdlog);
8345           do_cleanups (old_chain);
8346         }
8347       remote_serial_write (buf2, p - buf2);
8348
8349       /* If this is a no acks version of the remote protocol, send the
8350          packet and move on.  */
8351       if (rs->noack_mode)
8352         break;
8353
8354       /* Read until either a timeout occurs (-2) or '+' is read.
8355          Handle any notification that arrives in the mean time.  */
8356       while (1)
8357         {
8358           ch = readchar (remote_timeout);
8359
8360           if (remote_debug)
8361             {
8362               switch (ch)
8363                 {
8364                 case '+':
8365                 case '-':
8366                 case SERIAL_TIMEOUT:
8367                 case '$':
8368                 case '%':
8369                   if (started_error_output)
8370                     {
8371                       putchar_unfiltered ('\n');
8372                       started_error_output = 0;
8373                     }
8374                 }
8375             }
8376
8377           switch (ch)
8378             {
8379             case '+':
8380               if (remote_debug)
8381                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8382               do_cleanups (old_chain);
8383               return 1;
8384             case '-':
8385               if (remote_debug)
8386                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8387               /* FALLTHROUGH */
8388             case SERIAL_TIMEOUT:
8389               tcount++;
8390               if (tcount > 3)
8391                 {
8392                   do_cleanups (old_chain);
8393                   return 0;
8394                 }
8395               break;            /* Retransmit buffer.  */
8396             case '$':
8397               {
8398                 if (remote_debug)
8399                   fprintf_unfiltered (gdb_stdlog,
8400                                       "Packet instead of Ack, ignoring it\n");
8401                 /* It's probably an old response sent because an ACK
8402                    was lost.  Gobble up the packet and ack it so it
8403                    doesn't get retransmitted when we resend this
8404                    packet.  */
8405                 skip_frame ();
8406                 remote_serial_write ("+", 1);
8407                 continue;       /* Now, go look for +.  */
8408               }
8409
8410             case '%':
8411               {
8412                 int val;
8413
8414                 /* If we got a notification, handle it, and go back to looking
8415                    for an ack.  */
8416                 /* We've found the start of a notification.  Now
8417                    collect the data.  */
8418                 val = read_frame (&rs->buf, &rs->buf_size);
8419                 if (val >= 0)
8420                   {
8421                     if (remote_debug)
8422                       {
8423                         struct cleanup *old_chain;
8424                         char *str;
8425
8426                         str = escape_buffer (rs->buf, val);
8427                         old_chain = make_cleanup (xfree, str);
8428                         fprintf_unfiltered (gdb_stdlog,
8429                                             "  Notification received: %s\n",
8430                                             str);
8431                         do_cleanups (old_chain);
8432                       }
8433                     handle_notification (rs->notif_state, rs->buf);
8434                     /* We're in sync now, rewait for the ack.  */
8435                     tcount = 0;
8436                   }
8437                 else
8438                   {
8439                     if (remote_debug)
8440                       {
8441                         if (!started_error_output)
8442                           {
8443                             started_error_output = 1;
8444                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8445                           }
8446                         fputc_unfiltered (ch & 0177, gdb_stdlog);
8447                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8448                       }
8449                   }
8450                 continue;
8451               }
8452               /* fall-through */
8453             default:
8454               if (remote_debug)
8455                 {
8456                   if (!started_error_output)
8457                     {
8458                       started_error_output = 1;
8459                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8460                     }
8461                   fputc_unfiltered (ch & 0177, gdb_stdlog);
8462                 }
8463               continue;
8464             }
8465           break;                /* Here to retransmit.  */
8466         }
8467
8468 #if 0
8469       /* This is wrong.  If doing a long backtrace, the user should be
8470          able to get out next time we call QUIT, without anything as
8471          violent as interrupt_query.  If we want to provide a way out of
8472          here without getting to the next QUIT, it should be based on
8473          hitting ^C twice as in remote_wait.  */
8474       if (quit_flag)
8475         {
8476           quit_flag = 0;
8477           interrupt_query ();
8478         }
8479 #endif
8480     }
8481
8482   do_cleanups (old_chain);
8483   return 0;
8484 }
8485
8486 /* Come here after finding the start of a frame when we expected an
8487    ack.  Do our best to discard the rest of this packet.  */
8488
8489 static void
8490 skip_frame (void)
8491 {
8492   int c;
8493
8494   while (1)
8495     {
8496       c = readchar (remote_timeout);
8497       switch (c)
8498         {
8499         case SERIAL_TIMEOUT:
8500           /* Nothing we can do.  */
8501           return;
8502         case '#':
8503           /* Discard the two bytes of checksum and stop.  */
8504           c = readchar (remote_timeout);
8505           if (c >= 0)
8506             c = readchar (remote_timeout);
8507
8508           return;
8509         case '*':               /* Run length encoding.  */
8510           /* Discard the repeat count.  */
8511           c = readchar (remote_timeout);
8512           if (c < 0)
8513             return;
8514           break;
8515         default:
8516           /* A regular character.  */
8517           break;
8518         }
8519     }
8520 }
8521
8522 /* Come here after finding the start of the frame.  Collect the rest
8523    into *BUF, verifying the checksum, length, and handling run-length
8524    compression.  NUL terminate the buffer.  If there is not enough room,
8525    expand *BUF using xrealloc.
8526
8527    Returns -1 on error, number of characters in buffer (ignoring the
8528    trailing NULL) on success. (could be extended to return one of the
8529    SERIAL status indications).  */
8530
8531 static long
8532 read_frame (char **buf_p,
8533             long *sizeof_buf)
8534 {
8535   unsigned char csum;
8536   long bc;
8537   int c;
8538   char *buf = *buf_p;
8539   struct remote_state *rs = get_remote_state ();
8540
8541   csum = 0;
8542   bc = 0;
8543
8544   while (1)
8545     {
8546       c = readchar (remote_timeout);
8547       switch (c)
8548         {
8549         case SERIAL_TIMEOUT:
8550           if (remote_debug)
8551             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8552           return -1;
8553         case '$':
8554           if (remote_debug)
8555             fputs_filtered ("Saw new packet start in middle of old one\n",
8556                             gdb_stdlog);
8557           return -1;            /* Start a new packet, count retries.  */
8558         case '#':
8559           {
8560             unsigned char pktcsum;
8561             int check_0 = 0;
8562             int check_1 = 0;
8563
8564             buf[bc] = '\0';
8565
8566             check_0 = readchar (remote_timeout);
8567             if (check_0 >= 0)
8568               check_1 = readchar (remote_timeout);
8569
8570             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8571               {
8572                 if (remote_debug)
8573                   fputs_filtered ("Timeout in checksum, retrying\n",
8574                                   gdb_stdlog);
8575                 return -1;
8576               }
8577             else if (check_0 < 0 || check_1 < 0)
8578               {
8579                 if (remote_debug)
8580                   fputs_filtered ("Communication error in checksum\n",
8581                                   gdb_stdlog);
8582                 return -1;
8583               }
8584
8585             /* Don't recompute the checksum; with no ack packets we
8586                don't have any way to indicate a packet retransmission
8587                is necessary.  */
8588             if (rs->noack_mode)
8589               return bc;
8590
8591             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8592             if (csum == pktcsum)
8593               return bc;
8594
8595             if (remote_debug)
8596               {
8597                 struct cleanup *old_chain;
8598                 char *str;
8599
8600                 str = escape_buffer (buf, bc);
8601                 old_chain = make_cleanup (xfree, str);
8602                 fprintf_unfiltered (gdb_stdlog,
8603                                     "Bad checksum, sentsum=0x%x, "
8604                                     "csum=0x%x, buf=%s\n",
8605                                     pktcsum, csum, str);
8606                 do_cleanups (old_chain);
8607               }
8608             /* Number of characters in buffer ignoring trailing
8609                NULL.  */
8610             return -1;
8611           }
8612         case '*':               /* Run length encoding.  */
8613           {
8614             int repeat;
8615
8616             csum += c;
8617             c = readchar (remote_timeout);
8618             csum += c;
8619             repeat = c - ' ' + 3;       /* Compute repeat count.  */
8620
8621             /* The character before ``*'' is repeated.  */
8622
8623             if (repeat > 0 && repeat <= 255 && bc > 0)
8624               {
8625                 if (bc + repeat - 1 >= *sizeof_buf - 1)
8626                   {
8627                     /* Make some more room in the buffer.  */
8628                     *sizeof_buf += repeat;
8629                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8630                     buf = *buf_p;
8631                   }
8632
8633                 memset (&buf[bc], buf[bc - 1], repeat);
8634                 bc += repeat;
8635                 continue;
8636               }
8637
8638             buf[bc] = '\0';
8639             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8640             return -1;
8641           }
8642         default:
8643           if (bc >= *sizeof_buf - 1)
8644             {
8645               /* Make some more room in the buffer.  */
8646               *sizeof_buf *= 2;
8647               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8648               buf = *buf_p;
8649             }
8650
8651           buf[bc++] = c;
8652           csum += c;
8653           continue;
8654         }
8655     }
8656 }
8657
8658 /* Read a packet from the remote machine, with error checking, and
8659    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8660    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8661    rather than timing out; this is used (in synchronous mode) to wait
8662    for a target that is is executing user code to stop.  */
8663 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8664    don't have to change all the calls to getpkt to deal with the
8665    return value, because at the moment I don't know what the right
8666    thing to do it for those.  */
8667 void
8668 getpkt (char **buf,
8669         long *sizeof_buf,
8670         int forever)
8671 {
8672   int timed_out;
8673
8674   timed_out = getpkt_sane (buf, sizeof_buf, forever);
8675 }
8676
8677
8678 /* Read a packet from the remote machine, with error checking, and
8679    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8680    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8681    rather than timing out; this is used (in synchronous mode) to wait
8682    for a target that is is executing user code to stop.  If FOREVER ==
8683    0, this function is allowed to time out gracefully and return an
8684    indication of this to the caller.  Otherwise return the number of
8685    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
8686    enough reason to return to the caller.  *IS_NOTIF is an output
8687    boolean that indicates whether *BUF holds a notification or not
8688    (a regular packet).  */
8689
8690 static int
8691 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8692                         int expecting_notif, int *is_notif)
8693 {
8694   struct remote_state *rs = get_remote_state ();
8695   int c;
8696   int tries;
8697   int timeout;
8698   int val = -1;
8699
8700   /* We're reading a new response.  Make sure we don't look at a
8701      previously cached response.  */
8702   rs->cached_wait_status = 0;
8703
8704   strcpy (*buf, "timeout");
8705
8706   if (forever)
8707     timeout = watchdog > 0 ? watchdog : -1;
8708   else if (expecting_notif)
8709     timeout = 0; /* There should already be a char in the buffer.  If
8710                     not, bail out.  */
8711   else
8712     timeout = remote_timeout;
8713
8714 #define MAX_TRIES 3
8715
8716   /* Process any number of notifications, and then return when
8717      we get a packet.  */
8718   for (;;)
8719     {
8720       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8721          times.  */
8722       for (tries = 1; tries <= MAX_TRIES; tries++)
8723         {
8724           /* This can loop forever if the remote side sends us
8725              characters continuously, but if it pauses, we'll get
8726              SERIAL_TIMEOUT from readchar because of timeout.  Then
8727              we'll count that as a retry.
8728
8729              Note that even when forever is set, we will only wait
8730              forever prior to the start of a packet.  After that, we
8731              expect characters to arrive at a brisk pace.  They should
8732              show up within remote_timeout intervals.  */
8733           do
8734             c = readchar (timeout);
8735           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8736
8737           if (c == SERIAL_TIMEOUT)
8738             {
8739               if (expecting_notif)
8740                 return -1; /* Don't complain, it's normal to not get
8741                               anything in this case.  */
8742
8743               if (forever)      /* Watchdog went off?  Kill the target.  */
8744                 {
8745                   QUIT;
8746                   remote_unpush_target ();
8747                   throw_error (TARGET_CLOSE_ERROR,
8748                                _("Watchdog timeout has expired.  "
8749                                  "Target detached."));
8750                 }
8751               if (remote_debug)
8752                 fputs_filtered ("Timed out.\n", gdb_stdlog);
8753             }
8754           else
8755             {
8756               /* We've found the start of a packet or notification.
8757                  Now collect the data.  */
8758               val = read_frame (buf, sizeof_buf);
8759               if (val >= 0)
8760                 break;
8761             }
8762
8763           remote_serial_write ("-", 1);
8764         }
8765
8766       if (tries > MAX_TRIES)
8767         {
8768           /* We have tried hard enough, and just can't receive the
8769              packet/notification.  Give up.  */
8770           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8771
8772           /* Skip the ack char if we're in no-ack mode.  */
8773           if (!rs->noack_mode)
8774             remote_serial_write ("+", 1);
8775           return -1;
8776         }
8777
8778       /* If we got an ordinary packet, return that to our caller.  */
8779       if (c == '$')
8780         {
8781           if (remote_debug)
8782             {
8783              struct cleanup *old_chain;
8784              char *str;
8785
8786              str = escape_buffer (*buf, val);
8787              old_chain = make_cleanup (xfree, str);
8788              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8789              do_cleanups (old_chain);
8790             }
8791
8792           /* Skip the ack char if we're in no-ack mode.  */
8793           if (!rs->noack_mode)
8794             remote_serial_write ("+", 1);
8795           if (is_notif != NULL)
8796             *is_notif = 0;
8797           return val;
8798         }
8799
8800        /* If we got a notification, handle it, and go back to looking
8801          for a packet.  */
8802       else
8803         {
8804           gdb_assert (c == '%');
8805
8806           if (remote_debug)
8807             {
8808               struct cleanup *old_chain;
8809               char *str;
8810
8811               str = escape_buffer (*buf, val);
8812               old_chain = make_cleanup (xfree, str);
8813               fprintf_unfiltered (gdb_stdlog,
8814                                   "  Notification received: %s\n",
8815                                   str);
8816               do_cleanups (old_chain);
8817             }
8818           if (is_notif != NULL)
8819             *is_notif = 1;
8820
8821           handle_notification (rs->notif_state, *buf);
8822
8823           /* Notifications require no acknowledgement.  */
8824
8825           if (expecting_notif)
8826             return val;
8827         }
8828     }
8829 }
8830
8831 static int
8832 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8833 {
8834   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8835 }
8836
8837 static int
8838 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8839                       int *is_notif)
8840 {
8841   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8842                                  is_notif);
8843 }
8844
8845 /* Check whether EVENT is a fork event for the process specified
8846    by the pid passed in DATA, and if it is, kill the fork child.  */
8847
8848 static int
8849 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8850                             QUEUE_ITER (stop_reply_p) *iter,
8851                             stop_reply_p event,
8852                             void *data)
8853 {
8854   struct queue_iter_param *param = (struct queue_iter_param *) data;
8855   int parent_pid = *(int *) param->input;
8856
8857   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8858     {
8859       struct remote_state *rs = get_remote_state ();
8860       int child_pid = ptid_get_pid (event->ws.value.related_pid);
8861       int res;
8862
8863       res = remote_vkill (child_pid, rs);
8864       if (res != 0)
8865         error (_("Can't kill fork child process %d"), child_pid);
8866     }
8867
8868   return 1;
8869 }
8870
8871 /* Kill any new fork children of process PID that haven't been
8872    processed by follow_fork.  */
8873
8874 static void
8875 kill_new_fork_children (int pid, struct remote_state *rs)
8876 {
8877   struct thread_info *thread;
8878   struct notif_client *notif = &notif_client_stop;
8879   struct queue_iter_param param;
8880
8881   /* Kill the fork child threads of any threads in process PID
8882      that are stopped at a fork event.  */
8883   ALL_NON_EXITED_THREADS (thread)
8884     {
8885       struct target_waitstatus *ws = &thread->pending_follow;
8886
8887       if (is_pending_fork_parent (ws, pid, thread->ptid))
8888         {
8889           struct remote_state *rs = get_remote_state ();
8890           int child_pid = ptid_get_pid (ws->value.related_pid);
8891           int res;
8892
8893           res = remote_vkill (child_pid, rs);
8894           if (res != 0)
8895             error (_("Can't kill fork child process %d"), child_pid);
8896         }
8897     }
8898
8899   /* Check for any pending fork events (not reported or processed yet)
8900      in process PID and kill those fork child threads as well.  */
8901   remote_notif_get_pending_events (notif);
8902   param.input = &pid;
8903   param.output = NULL;
8904   QUEUE_iterate (stop_reply_p, stop_reply_queue,
8905                  kill_child_of_pending_fork, &param);
8906 }
8907
8908 \f
8909 /* Target hook to kill the current inferior.  */
8910
8911 static void
8912 remote_kill (struct target_ops *ops)
8913 {
8914   int res = -1;
8915   int pid = ptid_get_pid (inferior_ptid);
8916   struct remote_state *rs = get_remote_state ();
8917
8918   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
8919     {
8920       /* If we're stopped while forking and we haven't followed yet,
8921          kill the child task.  We need to do this before killing the
8922          parent task because if this is a vfork then the parent will
8923          be sleeping.  */
8924       kill_new_fork_children (pid, rs);
8925
8926       res = remote_vkill (pid, rs);
8927       if (res == 0)
8928         {
8929           target_mourn_inferior ();
8930           return;
8931         }
8932     }
8933
8934   /* If we are in 'target remote' mode and we are killing the only
8935      inferior, then we will tell gdbserver to exit and unpush the
8936      target.  */
8937   if (res == -1 && !remote_multi_process_p (rs)
8938       && number_of_live_inferiors () == 1)
8939     {
8940       remote_kill_k ();
8941
8942       /* We've killed the remote end, we get to mourn it.  If we are
8943          not in extended mode, mourning the inferior also unpushes
8944          remote_ops from the target stack, which closes the remote
8945          connection.  */
8946       target_mourn_inferior ();
8947
8948       return;
8949     }
8950
8951   error (_("Can't kill process"));
8952 }
8953
8954 /* Send a kill request to the target using the 'vKill' packet.  */
8955
8956 static int
8957 remote_vkill (int pid, struct remote_state *rs)
8958 {
8959   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8960     return -1;
8961
8962   /* Tell the remote target to detach.  */
8963   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8964   putpkt (rs->buf);
8965   getpkt (&rs->buf, &rs->buf_size, 0);
8966
8967   switch (packet_ok (rs->buf,
8968                      &remote_protocol_packets[PACKET_vKill]))
8969     {
8970     case PACKET_OK:
8971       return 0;
8972     case PACKET_ERROR:
8973       return 1;
8974     case PACKET_UNKNOWN:
8975       return -1;
8976     default:
8977       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8978     }
8979 }
8980
8981 /* Send a kill request to the target using the 'k' packet.  */
8982
8983 static void
8984 remote_kill_k (void)
8985 {
8986   /* Catch errors so the user can quit from gdb even when we
8987      aren't on speaking terms with the remote system.  */
8988   TRY
8989     {
8990       putpkt ("k");
8991     }
8992   CATCH (ex, RETURN_MASK_ERROR)
8993     {
8994       if (ex.error == TARGET_CLOSE_ERROR)
8995         {
8996           /* If we got an (EOF) error that caused the target
8997              to go away, then we're done, that's what we wanted.
8998              "k" is susceptible to cause a premature EOF, given
8999              that the remote server isn't actually required to
9000              reply to "k", and it can happen that it doesn't
9001              even get to reply ACK to the "k".  */
9002           return;
9003         }
9004
9005       /* Otherwise, something went wrong.  We didn't actually kill
9006          the target.  Just propagate the exception, and let the
9007          user or higher layers decide what to do.  */
9008       throw_exception (ex);
9009     }
9010   END_CATCH
9011 }
9012
9013 static void
9014 remote_mourn (struct target_ops *target)
9015 {
9016   struct remote_state *rs = get_remote_state ();
9017
9018   /* In 'target remote' mode with one inferior, we close the connection.  */
9019   if (!rs->extended && number_of_live_inferiors () <= 1)
9020     {
9021       unpush_target (target);
9022
9023       /* remote_close takes care of doing most of the clean up.  */
9024       generic_mourn_inferior ();
9025       return;
9026     }
9027
9028   /* In case we got here due to an error, but we're going to stay
9029      connected.  */
9030   rs->waiting_for_stop_reply = 0;
9031
9032   /* If the current general thread belonged to the process we just
9033      detached from or has exited, the remote side current general
9034      thread becomes undefined.  Considering a case like this:
9035
9036      - We just got here due to a detach.
9037      - The process that we're detaching from happens to immediately
9038        report a global breakpoint being hit in non-stop mode, in the
9039        same thread we had selected before.
9040      - GDB attaches to this process again.
9041      - This event happens to be the next event we handle.
9042
9043      GDB would consider that the current general thread didn't need to
9044      be set on the stub side (with Hg), since for all it knew,
9045      GENERAL_THREAD hadn't changed.
9046
9047      Notice that although in all-stop mode, the remote server always
9048      sets the current thread to the thread reporting the stop event,
9049      that doesn't happen in non-stop mode; in non-stop, the stub *must
9050      not* change the current thread when reporting a breakpoint hit,
9051      due to the decoupling of event reporting and event handling.
9052
9053      To keep things simple, we always invalidate our notion of the
9054      current thread.  */
9055   record_currthread (rs, minus_one_ptid);
9056
9057   /* Call common code to mark the inferior as not running.  */
9058   generic_mourn_inferior ();
9059
9060   if (!have_inferiors ())
9061     {
9062       if (!remote_multi_process_p (rs))
9063         {
9064           /* Check whether the target is running now - some remote stubs
9065              automatically restart after kill.  */
9066           putpkt ("?");
9067           getpkt (&rs->buf, &rs->buf_size, 0);
9068
9069           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9070             {
9071               /* Assume that the target has been restarted.  Set
9072                  inferior_ptid so that bits of core GDB realizes
9073                  there's something here, e.g., so that the user can
9074                  say "kill" again.  */
9075               inferior_ptid = magic_null_ptid;
9076             }
9077         }
9078     }
9079 }
9080
9081 static int
9082 extended_remote_supports_disable_randomization (struct target_ops *self)
9083 {
9084   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9085 }
9086
9087 static void
9088 extended_remote_disable_randomization (int val)
9089 {
9090   struct remote_state *rs = get_remote_state ();
9091   char *reply;
9092
9093   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9094              val);
9095   putpkt (rs->buf);
9096   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9097   if (*reply == '\0')
9098     error (_("Target does not support QDisableRandomization."));
9099   if (strcmp (reply, "OK") != 0)
9100     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9101 }
9102
9103 static int
9104 extended_remote_run (char *args)
9105 {
9106   struct remote_state *rs = get_remote_state ();
9107   int len;
9108   const char *remote_exec_file = get_remote_exec_file ();
9109
9110   /* If the user has disabled vRun support, or we have detected that
9111      support is not available, do not try it.  */
9112   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9113     return -1;
9114
9115   strcpy (rs->buf, "vRun;");
9116   len = strlen (rs->buf);
9117
9118   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9119     error (_("Remote file name too long for run packet"));
9120   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9121                       strlen (remote_exec_file));
9122
9123   gdb_assert (args != NULL);
9124   if (*args)
9125     {
9126       struct cleanup *back_to;
9127       int i;
9128       char **argv;
9129
9130       argv = gdb_buildargv (args);
9131       back_to = make_cleanup_freeargv (argv);
9132       for (i = 0; argv[i] != NULL; i++)
9133         {
9134           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9135             error (_("Argument list too long for run packet"));
9136           rs->buf[len++] = ';';
9137           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9138                               strlen (argv[i]));
9139         }
9140       do_cleanups (back_to);
9141     }
9142
9143   rs->buf[len++] = '\0';
9144
9145   putpkt (rs->buf);
9146   getpkt (&rs->buf, &rs->buf_size, 0);
9147
9148   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9149     {
9150     case PACKET_OK:
9151       /* We have a wait response.  All is well.  */
9152       return 0;
9153     case PACKET_UNKNOWN:
9154       return -1;
9155     case PACKET_ERROR:
9156       if (remote_exec_file[0] == '\0')
9157         error (_("Running the default executable on the remote target failed; "
9158                  "try \"set remote exec-file\"?"));
9159       else
9160         error (_("Running \"%s\" on the remote target failed"),
9161                remote_exec_file);
9162     default:
9163       gdb_assert_not_reached (_("bad switch"));
9164     }
9165 }
9166
9167 /* In the extended protocol we want to be able to do things like
9168    "run" and have them basically work as expected.  So we need
9169    a special create_inferior function.  We support changing the
9170    executable file and the command line arguments, but not the
9171    environment.  */
9172
9173 static void
9174 extended_remote_create_inferior (struct target_ops *ops,
9175                                  char *exec_file, char *args,
9176                                  char **env, int from_tty)
9177 {
9178   int run_worked;
9179   char *stop_reply;
9180   struct remote_state *rs = get_remote_state ();
9181   const char *remote_exec_file = get_remote_exec_file ();
9182
9183   /* If running asynchronously, register the target file descriptor
9184      with the event loop.  */
9185   if (target_can_async_p ())
9186     target_async (1);
9187
9188   /* Disable address space randomization if requested (and supported).  */
9189   if (extended_remote_supports_disable_randomization (ops))
9190     extended_remote_disable_randomization (disable_randomization);
9191
9192   /* Now restart the remote server.  */
9193   run_worked = extended_remote_run (args) != -1;
9194   if (!run_worked)
9195     {
9196       /* vRun was not supported.  Fail if we need it to do what the
9197          user requested.  */
9198       if (remote_exec_file[0])
9199         error (_("Remote target does not support \"set remote exec-file\""));
9200       if (args[0])
9201         error (_("Remote target does not support \"set args\" or run <ARGS>"));
9202
9203       /* Fall back to "R".  */
9204       extended_remote_restart ();
9205     }
9206
9207   if (!have_inferiors ())
9208     {
9209       /* Clean up from the last time we ran, before we mark the target
9210          running again.  This will mark breakpoints uninserted, and
9211          get_offsets may insert breakpoints.  */
9212       init_thread_list ();
9213       init_wait_for_inferior ();
9214     }
9215
9216   /* vRun's success return is a stop reply.  */
9217   stop_reply = run_worked ? rs->buf : NULL;
9218   add_current_inferior_and_thread (stop_reply);
9219
9220   /* Get updated offsets, if the stub uses qOffsets.  */
9221   get_offsets ();
9222 }
9223 \f
9224
9225 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
9226    the list of conditions (in agent expression bytecode format), if any, the
9227    target needs to evaluate.  The output is placed into the packet buffer
9228    started from BUF and ended at BUF_END.  */
9229
9230 static int
9231 remote_add_target_side_condition (struct gdbarch *gdbarch,
9232                                   struct bp_target_info *bp_tgt, char *buf,
9233                                   char *buf_end)
9234 {
9235   struct agent_expr *aexpr = NULL;
9236   int i, ix;
9237   char *pkt;
9238   char *buf_start = buf;
9239
9240   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9241     return 0;
9242
9243   buf += strlen (buf);
9244   xsnprintf (buf, buf_end - buf, "%s", ";");
9245   buf++;
9246
9247   /* Send conditions to the target and free the vector.  */
9248   for (ix = 0;
9249        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9250        ix++)
9251     {
9252       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9253       buf += strlen (buf);
9254       for (i = 0; i < aexpr->len; ++i)
9255         buf = pack_hex_byte (buf, aexpr->buf[i]);
9256       *buf = '\0';
9257     }
9258   return 0;
9259 }
9260
9261 static void
9262 remote_add_target_side_commands (struct gdbarch *gdbarch,
9263                                  struct bp_target_info *bp_tgt, char *buf)
9264 {
9265   struct agent_expr *aexpr = NULL;
9266   int i, ix;
9267
9268   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9269     return;
9270
9271   buf += strlen (buf);
9272
9273   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9274   buf += strlen (buf);
9275
9276   /* Concatenate all the agent expressions that are commands into the
9277      cmds parameter.  */
9278   for (ix = 0;
9279        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9280        ix++)
9281     {
9282       sprintf (buf, "X%x,", aexpr->len);
9283       buf += strlen (buf);
9284       for (i = 0; i < aexpr->len; ++i)
9285         buf = pack_hex_byte (buf, aexpr->buf[i]);
9286       *buf = '\0';
9287     }
9288 }
9289
9290 /* Insert a breakpoint.  On targets that have software breakpoint
9291    support, we ask the remote target to do the work; on targets
9292    which don't, we insert a traditional memory breakpoint.  */
9293
9294 static int
9295 remote_insert_breakpoint (struct target_ops *ops,
9296                           struct gdbarch *gdbarch,
9297                           struct bp_target_info *bp_tgt)
9298 {
9299   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9300      If it succeeds, then set the support to PACKET_ENABLE.  If it
9301      fails, and the user has explicitly requested the Z support then
9302      report an error, otherwise, mark it disabled and go on.  */
9303
9304   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9305     {
9306       CORE_ADDR addr = bp_tgt->reqstd_address;
9307       struct remote_state *rs;
9308       char *p, *endbuf;
9309       int bpsize;
9310       struct condition_list *cond = NULL;
9311
9312       /* Make sure the remote is pointing at the right process, if
9313          necessary.  */
9314       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9315         set_general_process ();
9316
9317       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9318
9319       rs = get_remote_state ();
9320       p = rs->buf;
9321       endbuf = rs->buf + get_remote_packet_size ();
9322
9323       *(p++) = 'Z';
9324       *(p++) = '0';
9325       *(p++) = ',';
9326       addr = (ULONGEST) remote_address_masked (addr);
9327       p += hexnumstr (p, addr);
9328       xsnprintf (p, endbuf - p, ",%d", bpsize);
9329
9330       if (remote_supports_cond_breakpoints (ops))
9331         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9332
9333       if (remote_can_run_breakpoint_commands (ops))
9334         remote_add_target_side_commands (gdbarch, bp_tgt, p);
9335
9336       putpkt (rs->buf);
9337       getpkt (&rs->buf, &rs->buf_size, 0);
9338
9339       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9340         {
9341         case PACKET_ERROR:
9342           return -1;
9343         case PACKET_OK:
9344           bp_tgt->placed_address = addr;
9345           bp_tgt->placed_size = bpsize;
9346           return 0;
9347         case PACKET_UNKNOWN:
9348           break;
9349         }
9350     }
9351
9352   /* If this breakpoint has target-side commands but this stub doesn't
9353      support Z0 packets, throw error.  */
9354   if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9355     throw_error (NOT_SUPPORTED_ERROR, _("\
9356 Target doesn't support breakpoints that have target side commands."));
9357
9358   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9359 }
9360
9361 static int
9362 remote_remove_breakpoint (struct target_ops *ops,
9363                           struct gdbarch *gdbarch,
9364                           struct bp_target_info *bp_tgt)
9365 {
9366   CORE_ADDR addr = bp_tgt->placed_address;
9367   struct remote_state *rs = get_remote_state ();
9368
9369   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9370     {
9371       char *p = rs->buf;
9372       char *endbuf = rs->buf + get_remote_packet_size ();
9373
9374       /* Make sure the remote is pointing at the right process, if
9375          necessary.  */
9376       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9377         set_general_process ();
9378
9379       *(p++) = 'z';
9380       *(p++) = '0';
9381       *(p++) = ',';
9382
9383       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9384       p += hexnumstr (p, addr);
9385       xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9386
9387       putpkt (rs->buf);
9388       getpkt (&rs->buf, &rs->buf_size, 0);
9389
9390       return (rs->buf[0] == 'E');
9391     }
9392
9393   return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9394 }
9395
9396 static enum Z_packet_type
9397 watchpoint_to_Z_packet (int type)
9398 {
9399   switch (type)
9400     {
9401     case hw_write:
9402       return Z_PACKET_WRITE_WP;
9403       break;
9404     case hw_read:
9405       return Z_PACKET_READ_WP;
9406       break;
9407     case hw_access:
9408       return Z_PACKET_ACCESS_WP;
9409       break;
9410     default:
9411       internal_error (__FILE__, __LINE__,
9412                       _("hw_bp_to_z: bad watchpoint type %d"), type);
9413     }
9414 }
9415
9416 static int
9417 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9418                           enum target_hw_bp_type type, struct expression *cond)
9419 {
9420   struct remote_state *rs = get_remote_state ();
9421   char *endbuf = rs->buf + get_remote_packet_size ();
9422   char *p;
9423   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9424
9425   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9426     return 1;
9427
9428   /* Make sure the remote is pointing at the right process, if
9429      necessary.  */
9430   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9431     set_general_process ();
9432
9433   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9434   p = strchr (rs->buf, '\0');
9435   addr = remote_address_masked (addr);
9436   p += hexnumstr (p, (ULONGEST) addr);
9437   xsnprintf (p, endbuf - p, ",%x", len);
9438
9439   putpkt (rs->buf);
9440   getpkt (&rs->buf, &rs->buf_size, 0);
9441
9442   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9443     {
9444     case PACKET_ERROR:
9445       return -1;
9446     case PACKET_UNKNOWN:
9447       return 1;
9448     case PACKET_OK:
9449       return 0;
9450     }
9451   internal_error (__FILE__, __LINE__,
9452                   _("remote_insert_watchpoint: reached end of function"));
9453 }
9454
9455 static int
9456 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9457                                      CORE_ADDR start, int length)
9458 {
9459   CORE_ADDR diff = remote_address_masked (addr - start);
9460
9461   return diff < length;
9462 }
9463
9464
9465 static int
9466 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9467                           enum target_hw_bp_type type, struct expression *cond)
9468 {
9469   struct remote_state *rs = get_remote_state ();
9470   char *endbuf = rs->buf + get_remote_packet_size ();
9471   char *p;
9472   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9473
9474   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9475     return -1;
9476
9477   /* Make sure the remote is pointing at the right process, if
9478      necessary.  */
9479   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9480     set_general_process ();
9481
9482   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9483   p = strchr (rs->buf, '\0');
9484   addr = remote_address_masked (addr);
9485   p += hexnumstr (p, (ULONGEST) addr);
9486   xsnprintf (p, endbuf - p, ",%x", len);
9487   putpkt (rs->buf);
9488   getpkt (&rs->buf, &rs->buf_size, 0);
9489
9490   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9491     {
9492     case PACKET_ERROR:
9493     case PACKET_UNKNOWN:
9494       return -1;
9495     case PACKET_OK:
9496       return 0;
9497     }
9498   internal_error (__FILE__, __LINE__,
9499                   _("remote_remove_watchpoint: reached end of function"));
9500 }
9501
9502
9503 int remote_hw_watchpoint_limit = -1;
9504 int remote_hw_watchpoint_length_limit = -1;
9505 int remote_hw_breakpoint_limit = -1;
9506
9507 static int
9508 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9509                                     CORE_ADDR addr, int len)
9510 {
9511   if (remote_hw_watchpoint_length_limit == 0)
9512     return 0;
9513   else if (remote_hw_watchpoint_length_limit < 0)
9514     return 1;
9515   else if (len <= remote_hw_watchpoint_length_limit)
9516     return 1;
9517   else
9518     return 0;
9519 }
9520
9521 static int
9522 remote_check_watch_resources (struct target_ops *self,
9523                               enum bptype type, int cnt, int ot)
9524 {
9525   if (type == bp_hardware_breakpoint)
9526     {
9527       if (remote_hw_breakpoint_limit == 0)
9528         return 0;
9529       else if (remote_hw_breakpoint_limit < 0)
9530         return 1;
9531       else if (cnt <= remote_hw_breakpoint_limit)
9532         return 1;
9533     }
9534   else
9535     {
9536       if (remote_hw_watchpoint_limit == 0)
9537         return 0;
9538       else if (remote_hw_watchpoint_limit < 0)
9539         return 1;
9540       else if (ot)
9541         return -1;
9542       else if (cnt <= remote_hw_watchpoint_limit)
9543         return 1;
9544     }
9545   return -1;
9546 }
9547
9548 /* The to_stopped_by_sw_breakpoint method of target remote.  */
9549
9550 static int
9551 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9552 {
9553   struct thread_info *thread = inferior_thread ();
9554
9555   return (thread->priv != NULL
9556           && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9557 }
9558
9559 /* The to_supports_stopped_by_sw_breakpoint method of target
9560    remote.  */
9561
9562 static int
9563 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9564 {
9565   struct remote_state *rs = get_remote_state ();
9566
9567   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9568 }
9569
9570 /* The to_stopped_by_hw_breakpoint method of target remote.  */
9571
9572 static int
9573 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9574 {
9575   struct thread_info *thread = inferior_thread ();
9576
9577   return (thread->priv != NULL
9578           && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9579 }
9580
9581 /* The to_supports_stopped_by_hw_breakpoint method of target
9582    remote.  */
9583
9584 static int
9585 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9586 {
9587   struct remote_state *rs = get_remote_state ();
9588
9589   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9590 }
9591
9592 static int
9593 remote_stopped_by_watchpoint (struct target_ops *ops)
9594 {
9595   struct thread_info *thread = inferior_thread ();
9596
9597   return (thread->priv != NULL
9598           && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9599 }
9600
9601 static int
9602 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9603 {
9604   struct thread_info *thread = inferior_thread ();
9605
9606   if (thread->priv != NULL
9607       && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9608     {
9609       *addr_p = thread->priv->watch_data_address;
9610       return 1;
9611     }
9612
9613   return 0;
9614 }
9615
9616
9617 static int
9618 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9619                              struct bp_target_info *bp_tgt)
9620 {
9621   CORE_ADDR addr = bp_tgt->reqstd_address;
9622   struct remote_state *rs;
9623   char *p, *endbuf;
9624   char *message;
9625   int bpsize;
9626
9627   /* The length field should be set to the size of a breakpoint
9628      instruction, even though we aren't inserting one ourselves.  */
9629
9630   gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9631
9632   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9633     return -1;
9634
9635   /* Make sure the remote is pointing at the right process, if
9636      necessary.  */
9637   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9638     set_general_process ();
9639
9640   rs = get_remote_state ();
9641   p = rs->buf;
9642   endbuf = rs->buf + get_remote_packet_size ();
9643
9644   *(p++) = 'Z';
9645   *(p++) = '1';
9646   *(p++) = ',';
9647
9648   addr = remote_address_masked (addr);
9649   p += hexnumstr (p, (ULONGEST) addr);
9650   xsnprintf (p, endbuf - p, ",%x", bpsize);
9651
9652   if (remote_supports_cond_breakpoints (self))
9653     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9654
9655   if (remote_can_run_breakpoint_commands (self))
9656     remote_add_target_side_commands (gdbarch, bp_tgt, p);
9657
9658   putpkt (rs->buf);
9659   getpkt (&rs->buf, &rs->buf_size, 0);
9660
9661   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9662     {
9663     case PACKET_ERROR:
9664       if (rs->buf[1] == '.')
9665         {
9666           message = strchr (rs->buf + 2, '.');
9667           if (message)
9668             error (_("Remote failure reply: %s"), message + 1);
9669         }
9670       return -1;
9671     case PACKET_UNKNOWN:
9672       return -1;
9673     case PACKET_OK:
9674       bp_tgt->placed_address = addr;
9675       bp_tgt->placed_size = bpsize;
9676       return 0;
9677     }
9678   internal_error (__FILE__, __LINE__,
9679                   _("remote_insert_hw_breakpoint: reached end of function"));
9680 }
9681
9682
9683 static int
9684 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9685                              struct bp_target_info *bp_tgt)
9686 {
9687   CORE_ADDR addr;
9688   struct remote_state *rs = get_remote_state ();
9689   char *p = rs->buf;
9690   char *endbuf = rs->buf + get_remote_packet_size ();
9691
9692   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9693     return -1;
9694
9695   /* Make sure the remote is pointing at the right process, if
9696      necessary.  */
9697   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9698     set_general_process ();
9699
9700   *(p++) = 'z';
9701   *(p++) = '1';
9702   *(p++) = ',';
9703
9704   addr = remote_address_masked (bp_tgt->placed_address);
9705   p += hexnumstr (p, (ULONGEST) addr);
9706   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);
9707
9708   putpkt (rs->buf);
9709   getpkt (&rs->buf, &rs->buf_size, 0);
9710
9711   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9712     {
9713     case PACKET_ERROR:
9714     case PACKET_UNKNOWN:
9715       return -1;
9716     case PACKET_OK:
9717       return 0;
9718     }
9719   internal_error (__FILE__, __LINE__,
9720                   _("remote_remove_hw_breakpoint: reached end of function"));
9721 }
9722
9723 /* Verify memory using the "qCRC:" request.  */
9724
9725 static int
9726 remote_verify_memory (struct target_ops *ops,
9727                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9728 {
9729   struct remote_state *rs = get_remote_state ();
9730   unsigned long host_crc, target_crc;
9731   char *tmp;
9732
9733   /* It doesn't make sense to use qCRC if the remote target is
9734      connected but not running.  */
9735   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9736     {
9737       enum packet_result result;
9738
9739       /* Make sure the remote is pointing at the right process.  */
9740       set_general_process ();
9741
9742       /* FIXME: assumes lma can fit into long.  */
9743       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9744                  (long) lma, (long) size);
9745       putpkt (rs->buf);
9746
9747       /* Be clever; compute the host_crc before waiting for target
9748          reply.  */
9749       host_crc = xcrc32 (data, size, 0xffffffff);
9750
9751       getpkt (&rs->buf, &rs->buf_size, 0);
9752
9753       result = packet_ok (rs->buf,
9754                           &remote_protocol_packets[PACKET_qCRC]);
9755       if (result == PACKET_ERROR)
9756         return -1;
9757       else if (result == PACKET_OK)
9758         {
9759           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9760             target_crc = target_crc * 16 + fromhex (*tmp);
9761
9762           return (host_crc == target_crc);
9763         }
9764     }
9765
9766   return simple_verify_memory (ops, data, lma, size);
9767 }
9768
9769 /* compare-sections command
9770
9771    With no arguments, compares each loadable section in the exec bfd
9772    with the same memory range on the target, and reports mismatches.
9773    Useful for verifying the image on the target against the exec file.  */
9774
9775 static void
9776 compare_sections_command (char *args, int from_tty)
9777 {
9778   asection *s;
9779   struct cleanup *old_chain;
9780   gdb_byte *sectdata;
9781   const char *sectname;
9782   bfd_size_type size;
9783   bfd_vma lma;
9784   int matched = 0;
9785   int mismatched = 0;
9786   int res;
9787   int read_only = 0;
9788
9789   if (!exec_bfd)
9790     error (_("command cannot be used without an exec file"));
9791
9792   /* Make sure the remote is pointing at the right process.  */
9793   set_general_process ();
9794
9795   if (args != NULL && strcmp (args, "-r") == 0)
9796     {
9797       read_only = 1;
9798       args = NULL;
9799     }
9800
9801   for (s = exec_bfd->sections; s; s = s->next)
9802     {
9803       if (!(s->flags & SEC_LOAD))
9804         continue;               /* Skip non-loadable section.  */
9805
9806       if (read_only && (s->flags & SEC_READONLY) == 0)
9807         continue;               /* Skip writeable sections */
9808
9809       size = bfd_get_section_size (s);
9810       if (size == 0)
9811         continue;               /* Skip zero-length section.  */
9812
9813       sectname = bfd_get_section_name (exec_bfd, s);
9814       if (args && strcmp (args, sectname) != 0)
9815         continue;               /* Not the section selected by user.  */
9816
9817       matched = 1;              /* Do this section.  */
9818       lma = s->lma;
9819
9820       sectdata = (gdb_byte *) xmalloc (size);
9821       old_chain = make_cleanup (xfree, sectdata);
9822       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9823
9824       res = target_verify_memory (sectdata, lma, size);
9825
9826       if (res == -1)
9827         error (_("target memory fault, section %s, range %s -- %s"), sectname,
9828                paddress (target_gdbarch (), lma),
9829                paddress (target_gdbarch (), lma + size));
9830
9831       printf_filtered ("Section %s, range %s -- %s: ", sectname,
9832                        paddress (target_gdbarch (), lma),
9833                        paddress (target_gdbarch (), lma + size));
9834       if (res)
9835         printf_filtered ("matched.\n");
9836       else
9837         {
9838           printf_filtered ("MIS-MATCHED!\n");
9839           mismatched++;
9840         }
9841
9842       do_cleanups (old_chain);
9843     }
9844   if (mismatched > 0)
9845     warning (_("One or more sections of the target image does not match\n\
9846 the loaded file\n"));
9847   if (args && !matched)
9848     printf_filtered (_("No loaded section named '%s'.\n"), args);
9849 }
9850
9851 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9852    into remote target.  The number of bytes written to the remote
9853    target is returned, or -1 for error.  */
9854
9855 static enum target_xfer_status
9856 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9857                     const char *annex, const gdb_byte *writebuf, 
9858                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9859                     struct packet_config *packet)
9860 {
9861   int i, buf_len;
9862   ULONGEST n;
9863   struct remote_state *rs = get_remote_state ();
9864   int max_size = get_memory_write_packet_size (); 
9865
9866   if (packet->support == PACKET_DISABLE)
9867     return TARGET_XFER_E_IO;
9868
9869   /* Insert header.  */
9870   i = snprintf (rs->buf, max_size, 
9871                 "qXfer:%s:write:%s:%s:",
9872                 object_name, annex ? annex : "",
9873                 phex_nz (offset, sizeof offset));
9874   max_size -= (i + 1);
9875
9876   /* Escape as much data as fits into rs->buf.  */
9877   buf_len = remote_escape_output 
9878     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9879
9880   if (putpkt_binary (rs->buf, i + buf_len) < 0
9881       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9882       || packet_ok (rs->buf, packet) != PACKET_OK)
9883     return TARGET_XFER_E_IO;
9884
9885   unpack_varlen_hex (rs->buf, &n);
9886
9887   *xfered_len = n;
9888   return TARGET_XFER_OK;
9889 }
9890
9891 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9892    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9893    number of bytes read is returned, or 0 for EOF, or -1 for error.
9894    The number of bytes read may be less than LEN without indicating an
9895    EOF.  PACKET is checked and updated to indicate whether the remote
9896    target supports this object.  */
9897
9898 static enum target_xfer_status
9899 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9900                    const char *annex,
9901                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9902                    ULONGEST *xfered_len,
9903                    struct packet_config *packet)
9904 {
9905   struct remote_state *rs = get_remote_state ();
9906   LONGEST i, n, packet_len;
9907
9908   if (packet->support == PACKET_DISABLE)
9909     return TARGET_XFER_E_IO;
9910
9911   /* Check whether we've cached an end-of-object packet that matches
9912      this request.  */
9913   if (rs->finished_object)
9914     {
9915       if (strcmp (object_name, rs->finished_object) == 0
9916           && strcmp (annex ? annex : "", rs->finished_annex) == 0
9917           && offset == rs->finished_offset)
9918         return TARGET_XFER_EOF;
9919
9920
9921       /* Otherwise, we're now reading something different.  Discard
9922          the cache.  */
9923       xfree (rs->finished_object);
9924       xfree (rs->finished_annex);
9925       rs->finished_object = NULL;
9926       rs->finished_annex = NULL;
9927     }
9928
9929   /* Request only enough to fit in a single packet.  The actual data
9930      may not, since we don't know how much of it will need to be escaped;
9931      the target is free to respond with slightly less data.  We subtract
9932      five to account for the response type and the protocol frame.  */
9933   n = min (get_remote_packet_size () - 5, len);
9934   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9935             object_name, annex ? annex : "",
9936             phex_nz (offset, sizeof offset),
9937             phex_nz (n, sizeof n));
9938   i = putpkt (rs->buf);
9939   if (i < 0)
9940     return TARGET_XFER_E_IO;
9941
9942   rs->buf[0] = '\0';
9943   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9944   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9945     return TARGET_XFER_E_IO;
9946
9947   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9948     error (_("Unknown remote qXfer reply: %s"), rs->buf);
9949
9950   /* 'm' means there is (or at least might be) more data after this
9951      batch.  That does not make sense unless there's at least one byte
9952      of data in this reply.  */
9953   if (rs->buf[0] == 'm' && packet_len == 1)
9954     error (_("Remote qXfer reply contained no data."));
9955
9956   /* Got some data.  */
9957   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9958                              packet_len - 1, readbuf, n);
9959
9960   /* 'l' is an EOF marker, possibly including a final block of data,
9961      or possibly empty.  If we have the final block of a non-empty
9962      object, record this fact to bypass a subsequent partial read.  */
9963   if (rs->buf[0] == 'l' && offset + i > 0)
9964     {
9965       rs->finished_object = xstrdup (object_name);
9966       rs->finished_annex = xstrdup (annex ? annex : "");
9967       rs->finished_offset = offset + i;
9968     }
9969
9970   if (i == 0)
9971     return TARGET_XFER_EOF;
9972   else
9973     {
9974       *xfered_len = i;
9975       return TARGET_XFER_OK;
9976     }
9977 }
9978
9979 static enum target_xfer_status
9980 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9981                      const char *annex, gdb_byte *readbuf,
9982                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9983                      ULONGEST *xfered_len)
9984 {
9985   struct remote_state *rs;
9986   int i;
9987   char *p2;
9988   char query_type;
9989   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9990
9991   set_remote_traceframe ();
9992   set_general_thread (inferior_ptid);
9993
9994   rs = get_remote_state ();
9995
9996   /* Handle memory using the standard memory routines.  */
9997   if (object == TARGET_OBJECT_MEMORY)
9998     {
9999       /* If the remote target is connected but not running, we should
10000          pass this request down to a lower stratum (e.g. the executable
10001          file).  */
10002       if (!target_has_execution)
10003         return TARGET_XFER_EOF;
10004
10005       if (writebuf != NULL)
10006         return remote_write_bytes (offset, writebuf, len, unit_size,
10007                                    xfered_len);
10008       else
10009         return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10010                                   xfered_len);
10011     }
10012
10013   /* Handle SPU memory using qxfer packets.  */
10014   if (object == TARGET_OBJECT_SPU)
10015     {
10016       if (readbuf)
10017         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
10018                                   xfered_len, &remote_protocol_packets
10019                                   [PACKET_qXfer_spu_read]);
10020       else
10021         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
10022                                    xfered_len, &remote_protocol_packets
10023                                    [PACKET_qXfer_spu_write]);
10024     }
10025
10026   /* Handle extra signal info using qxfer packets.  */
10027   if (object == TARGET_OBJECT_SIGNAL_INFO)
10028     {
10029       if (readbuf)
10030         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10031                                   xfered_len, &remote_protocol_packets
10032                                   [PACKET_qXfer_siginfo_read]);
10033       else
10034         return remote_write_qxfer (ops, "siginfo", annex,
10035                                    writebuf, offset, len, xfered_len,
10036                                    &remote_protocol_packets
10037                                    [PACKET_qXfer_siginfo_write]);
10038     }
10039
10040   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10041     {
10042       if (readbuf)
10043         return remote_read_qxfer (ops, "statictrace", annex,
10044                                   readbuf, offset, len, xfered_len,
10045                                   &remote_protocol_packets
10046                                   [PACKET_qXfer_statictrace_read]);
10047       else
10048         return TARGET_XFER_E_IO;
10049     }
10050
10051   /* Only handle flash writes.  */
10052   if (writebuf != NULL)
10053     {
10054       LONGEST xfered;
10055
10056       switch (object)
10057         {
10058         case TARGET_OBJECT_FLASH:
10059           return remote_flash_write (ops, offset, len, xfered_len,
10060                                      writebuf);
10061
10062         default:
10063           return TARGET_XFER_E_IO;
10064         }
10065     }
10066
10067   /* Map pre-existing objects onto letters.  DO NOT do this for new
10068      objects!!!  Instead specify new query packets.  */
10069   switch (object)
10070     {
10071     case TARGET_OBJECT_AVR:
10072       query_type = 'R';
10073       break;
10074
10075     case TARGET_OBJECT_AUXV:
10076       gdb_assert (annex == NULL);
10077       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10078                                 xfered_len,
10079                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10080
10081     case TARGET_OBJECT_AVAILABLE_FEATURES:
10082       return remote_read_qxfer
10083         (ops, "features", annex, readbuf, offset, len, xfered_len,
10084          &remote_protocol_packets[PACKET_qXfer_features]);
10085
10086     case TARGET_OBJECT_LIBRARIES:
10087       return remote_read_qxfer
10088         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10089          &remote_protocol_packets[PACKET_qXfer_libraries]);
10090
10091     case TARGET_OBJECT_LIBRARIES_SVR4:
10092       return remote_read_qxfer
10093         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10094          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10095
10096     case TARGET_OBJECT_MEMORY_MAP:
10097       gdb_assert (annex == NULL);
10098       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10099                                  xfered_len,
10100                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10101
10102     case TARGET_OBJECT_OSDATA:
10103       /* Should only get here if we're connected.  */
10104       gdb_assert (rs->remote_desc);
10105       return remote_read_qxfer
10106         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10107         &remote_protocol_packets[PACKET_qXfer_osdata]);
10108
10109     case TARGET_OBJECT_THREADS:
10110       gdb_assert (annex == NULL);
10111       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10112                                 xfered_len,
10113                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10114
10115     case TARGET_OBJECT_TRACEFRAME_INFO:
10116       gdb_assert (annex == NULL);
10117       return remote_read_qxfer
10118         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10119          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10120
10121     case TARGET_OBJECT_FDPIC:
10122       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10123                                 xfered_len,
10124                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10125
10126     case TARGET_OBJECT_OPENVMS_UIB:
10127       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10128                                 xfered_len,
10129                                 &remote_protocol_packets[PACKET_qXfer_uib]);
10130
10131     case TARGET_OBJECT_BTRACE:
10132       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10133                                 xfered_len,
10134         &remote_protocol_packets[PACKET_qXfer_btrace]);
10135
10136     case TARGET_OBJECT_BTRACE_CONF:
10137       return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10138                                 len, xfered_len,
10139         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10140
10141     case TARGET_OBJECT_EXEC_FILE:
10142       return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10143                                 len, xfered_len,
10144         &remote_protocol_packets[PACKET_qXfer_exec_file]);
10145
10146     default:
10147       return TARGET_XFER_E_IO;
10148     }
10149
10150   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
10151      large enough let the caller deal with it.  */
10152   if (len < get_remote_packet_size ())
10153     return TARGET_XFER_E_IO;
10154   len = get_remote_packet_size ();
10155
10156   /* Except for querying the minimum buffer size, target must be open.  */
10157   if (!rs->remote_desc)
10158     error (_("remote query is only available after target open"));
10159
10160   gdb_assert (annex != NULL);
10161   gdb_assert (readbuf != NULL);
10162
10163   p2 = rs->buf;
10164   *p2++ = 'q';
10165   *p2++ = query_type;
10166
10167   /* We used one buffer char for the remote protocol q command and
10168      another for the query type.  As the remote protocol encapsulation
10169      uses 4 chars plus one extra in case we are debugging
10170      (remote_debug), we have PBUFZIZ - 7 left to pack the query
10171      string.  */
10172   i = 0;
10173   while (annex[i] && (i < (get_remote_packet_size () - 8)))
10174     {
10175       /* Bad caller may have sent forbidden characters.  */
10176       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10177       *p2++ = annex[i];
10178       i++;
10179     }
10180   *p2 = '\0';
10181   gdb_assert (annex[i] == '\0');
10182
10183   i = putpkt (rs->buf);
10184   if (i < 0)
10185     return TARGET_XFER_E_IO;
10186
10187   getpkt (&rs->buf, &rs->buf_size, 0);
10188   strcpy ((char *) readbuf, rs->buf);
10189
10190   *xfered_len = strlen ((char *) readbuf);
10191   return TARGET_XFER_OK;
10192 }
10193
10194 static int
10195 remote_search_memory (struct target_ops* ops,
10196                       CORE_ADDR start_addr, ULONGEST search_space_len,
10197                       const gdb_byte *pattern, ULONGEST pattern_len,
10198                       CORE_ADDR *found_addrp)
10199 {
10200   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10201   struct remote_state *rs = get_remote_state ();
10202   int max_size = get_memory_write_packet_size ();
10203   struct packet_config *packet =
10204     &remote_protocol_packets[PACKET_qSearch_memory];
10205   /* Number of packet bytes used to encode the pattern;
10206      this could be more than PATTERN_LEN due to escape characters.  */
10207   int escaped_pattern_len;
10208   /* Amount of pattern that was encodable in the packet.  */
10209   int used_pattern_len;
10210   int i;
10211   int found;
10212   ULONGEST found_addr;
10213
10214   /* Don't go to the target if we don't have to.
10215      This is done before checking packet->support to avoid the possibility that
10216      a success for this edge case means the facility works in general.  */
10217   if (pattern_len > search_space_len)
10218     return 0;
10219   if (pattern_len == 0)
10220     {
10221       *found_addrp = start_addr;
10222       return 1;
10223     }
10224
10225   /* If we already know the packet isn't supported, fall back to the simple
10226      way of searching memory.  */
10227
10228   if (packet_config_support (packet) == PACKET_DISABLE)
10229     {
10230       /* Target doesn't provided special support, fall back and use the
10231          standard support (copy memory and do the search here).  */
10232       return simple_search_memory (ops, start_addr, search_space_len,
10233                                    pattern, pattern_len, found_addrp);
10234     }
10235
10236   /* Make sure the remote is pointing at the right process.  */
10237   set_general_process ();
10238
10239   /* Insert header.  */
10240   i = snprintf (rs->buf, max_size, 
10241                 "qSearch:memory:%s;%s;",
10242                 phex_nz (start_addr, addr_size),
10243                 phex_nz (search_space_len, sizeof (search_space_len)));
10244   max_size -= (i + 1);
10245
10246   /* Escape as much data as fits into rs->buf.  */
10247   escaped_pattern_len =
10248     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10249                           &used_pattern_len, max_size);
10250
10251   /* Bail if the pattern is too large.  */
10252   if (used_pattern_len != pattern_len)
10253     error (_("Pattern is too large to transmit to remote target."));
10254
10255   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10256       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10257       || packet_ok (rs->buf, packet) != PACKET_OK)
10258     {
10259       /* The request may not have worked because the command is not
10260          supported.  If so, fall back to the simple way.  */
10261       if (packet->support == PACKET_DISABLE)
10262         {
10263           return simple_search_memory (ops, start_addr, search_space_len,
10264                                        pattern, pattern_len, found_addrp);
10265         }
10266       return -1;
10267     }
10268
10269   if (rs->buf[0] == '0')
10270     found = 0;
10271   else if (rs->buf[0] == '1')
10272     {
10273       found = 1;
10274       if (rs->buf[1] != ',')
10275         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10276       unpack_varlen_hex (rs->buf + 2, &found_addr);
10277       *found_addrp = found_addr;
10278     }
10279   else
10280     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10281
10282   return found;
10283 }
10284
10285 static void
10286 remote_rcmd (struct target_ops *self, const char *command,
10287              struct ui_file *outbuf)
10288 {
10289   struct remote_state *rs = get_remote_state ();
10290   char *p = rs->buf;
10291
10292   if (!rs->remote_desc)
10293     error (_("remote rcmd is only available after target open"));
10294
10295   /* Send a NULL command across as an empty command.  */
10296   if (command == NULL)
10297     command = "";
10298
10299   /* The query prefix.  */
10300   strcpy (rs->buf, "qRcmd,");
10301   p = strchr (rs->buf, '\0');
10302
10303   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10304       > get_remote_packet_size ())
10305     error (_("\"monitor\" command ``%s'' is too long."), command);
10306
10307   /* Encode the actual command.  */
10308   bin2hex ((const gdb_byte *) command, p, strlen (command));
10309
10310   if (putpkt (rs->buf) < 0)
10311     error (_("Communication problem with target."));
10312
10313   /* get/display the response */
10314   while (1)
10315     {
10316       char *buf;
10317
10318       /* XXX - see also remote_get_noisy_reply().  */
10319       QUIT;                     /* Allow user to bail out with ^C.  */
10320       rs->buf[0] = '\0';
10321       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10322         { 
10323           /* Timeout.  Continue to (try to) read responses.
10324              This is better than stopping with an error, assuming the stub
10325              is still executing the (long) monitor command.
10326              If needed, the user can interrupt gdb using C-c, obtaining
10327              an effect similar to stop on timeout.  */
10328           continue;
10329         }
10330       buf = rs->buf;
10331       if (buf[0] == '\0')
10332         error (_("Target does not support this command."));
10333       if (buf[0] == 'O' && buf[1] != 'K')
10334         {
10335           remote_console_output (buf + 1); /* 'O' message from stub.  */
10336           continue;
10337         }
10338       if (strcmp (buf, "OK") == 0)
10339         break;
10340       if (strlen (buf) == 3 && buf[0] == 'E'
10341           && isdigit (buf[1]) && isdigit (buf[2]))
10342         {
10343           error (_("Protocol error with Rcmd"));
10344         }
10345       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10346         {
10347           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10348
10349           fputc_unfiltered (c, outbuf);
10350         }
10351       break;
10352     }
10353 }
10354
10355 static VEC(mem_region_s) *
10356 remote_memory_map (struct target_ops *ops)
10357 {
10358   VEC(mem_region_s) *result = NULL;
10359   char *text = target_read_stralloc (&current_target,
10360                                      TARGET_OBJECT_MEMORY_MAP, NULL);
10361
10362   if (text)
10363     {
10364       struct cleanup *back_to = make_cleanup (xfree, text);
10365
10366       result = parse_memory_map (text);
10367       do_cleanups (back_to);
10368     }
10369
10370   return result;
10371 }
10372
10373 static void
10374 packet_command (char *args, int from_tty)
10375 {
10376   struct remote_state *rs = get_remote_state ();
10377
10378   if (!rs->remote_desc)
10379     error (_("command can only be used with remote target"));
10380
10381   if (!args)
10382     error (_("remote-packet command requires packet text as argument"));
10383
10384   puts_filtered ("sending: ");
10385   print_packet (args);
10386   puts_filtered ("\n");
10387   putpkt (args);
10388
10389   getpkt (&rs->buf, &rs->buf_size, 0);
10390   puts_filtered ("received: ");
10391   print_packet (rs->buf);
10392   puts_filtered ("\n");
10393 }
10394
10395 #if 0
10396 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10397
10398 static void display_thread_info (struct gdb_ext_thread_info *info);
10399
10400 static void threadset_test_cmd (char *cmd, int tty);
10401
10402 static void threadalive_test (char *cmd, int tty);
10403
10404 static void threadlist_test_cmd (char *cmd, int tty);
10405
10406 int get_and_display_threadinfo (threadref *ref);
10407
10408 static void threadinfo_test_cmd (char *cmd, int tty);
10409
10410 static int thread_display_step (threadref *ref, void *context);
10411
10412 static void threadlist_update_test_cmd (char *cmd, int tty);
10413
10414 static void init_remote_threadtests (void);
10415
10416 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
10417
10418 static void
10419 threadset_test_cmd (char *cmd, int tty)
10420 {
10421   int sample_thread = SAMPLE_THREAD;
10422
10423   printf_filtered (_("Remote threadset test\n"));
10424   set_general_thread (sample_thread);
10425 }
10426
10427
10428 static void
10429 threadalive_test (char *cmd, int tty)
10430 {
10431   int sample_thread = SAMPLE_THREAD;
10432   int pid = ptid_get_pid (inferior_ptid);
10433   ptid_t ptid = ptid_build (pid, sample_thread, 0);
10434
10435   if (remote_thread_alive (ptid))
10436     printf_filtered ("PASS: Thread alive test\n");
10437   else
10438     printf_filtered ("FAIL: Thread alive test\n");
10439 }
10440
10441 void output_threadid (char *title, threadref *ref);
10442
10443 void
10444 output_threadid (char *title, threadref *ref)
10445 {
10446   char hexid[20];
10447
10448   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
10449   hexid[16] = 0;
10450   printf_filtered ("%s  %s\n", title, (&hexid[0]));
10451 }
10452
10453 static void
10454 threadlist_test_cmd (char *cmd, int tty)
10455 {
10456   int startflag = 1;
10457   threadref nextthread;
10458   int done, result_count;
10459   threadref threadlist[3];
10460
10461   printf_filtered ("Remote Threadlist test\n");
10462   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10463                               &result_count, &threadlist[0]))
10464     printf_filtered ("FAIL: threadlist test\n");
10465   else
10466     {
10467       threadref *scan = threadlist;
10468       threadref *limit = scan + result_count;
10469
10470       while (scan < limit)
10471         output_threadid (" thread ", scan++);
10472     }
10473 }
10474
10475 void
10476 display_thread_info (struct gdb_ext_thread_info *info)
10477 {
10478   output_threadid ("Threadid: ", &info->threadid);
10479   printf_filtered ("Name: %s\n ", info->shortname);
10480   printf_filtered ("State: %s\n", info->display);
10481   printf_filtered ("other: %s\n\n", info->more_display);
10482 }
10483
10484 int
10485 get_and_display_threadinfo (threadref *ref)
10486 {
10487   int result;
10488   int set;
10489   struct gdb_ext_thread_info threadinfo;
10490
10491   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10492     | TAG_MOREDISPLAY | TAG_DISPLAY;
10493   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10494     display_thread_info (&threadinfo);
10495   return result;
10496 }
10497
10498 static void
10499 threadinfo_test_cmd (char *cmd, int tty)
10500 {
10501   int athread = SAMPLE_THREAD;
10502   threadref thread;
10503   int set;
10504
10505   int_to_threadref (&thread, athread);
10506   printf_filtered ("Remote Threadinfo test\n");
10507   if (!get_and_display_threadinfo (&thread))
10508     printf_filtered ("FAIL cannot get thread info\n");
10509 }
10510
10511 static int
10512 thread_display_step (threadref *ref, void *context)
10513 {
10514   /* output_threadid(" threadstep ",ref); *//* simple test */
10515   return get_and_display_threadinfo (ref);
10516 }
10517
10518 static void
10519 threadlist_update_test_cmd (char *cmd, int tty)
10520 {
10521   printf_filtered ("Remote Threadlist update test\n");
10522   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10523 }
10524
10525 static void
10526 init_remote_threadtests (void)
10527 {
10528   add_com ("tlist", class_obscure, threadlist_test_cmd,
10529            _("Fetch and print the remote list of "
10530              "thread identifiers, one pkt only"));
10531   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10532            _("Fetch and display info about one thread"));
10533   add_com ("tset", class_obscure, threadset_test_cmd,
10534            _("Test setting to a different thread"));
10535   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10536            _("Iterate through updating all remote thread info"));
10537   add_com ("talive", class_obscure, threadalive_test,
10538            _(" Remote thread alive test "));
10539 }
10540
10541 #endif /* 0 */
10542
10543 /* Convert a thread ID to a string.  Returns the string in a static
10544    buffer.  */
10545
10546 static char *
10547 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10548 {
10549   static char buf[64];
10550   struct remote_state *rs = get_remote_state ();
10551
10552   if (ptid_equal (ptid, null_ptid))
10553     return normal_pid_to_str (ptid);
10554   else if (ptid_is_pid (ptid))
10555     {
10556       /* Printing an inferior target id.  */
10557
10558       /* When multi-process extensions are off, there's no way in the
10559          remote protocol to know the remote process id, if there's any
10560          at all.  There's one exception --- when we're connected with
10561          target extended-remote, and we manually attached to a process
10562          with "attach PID".  We don't record anywhere a flag that
10563          allows us to distinguish that case from the case of
10564          connecting with extended-remote and the stub already being
10565          attached to a process, and reporting yes to qAttached, hence
10566          no smart special casing here.  */
10567       if (!remote_multi_process_p (rs))
10568         {
10569           xsnprintf (buf, sizeof buf, "Remote target");
10570           return buf;
10571         }
10572
10573       return normal_pid_to_str (ptid);
10574     }
10575   else
10576     {
10577       if (ptid_equal (magic_null_ptid, ptid))
10578         xsnprintf (buf, sizeof buf, "Thread <main>");
10579       else if (remote_multi_process_p (rs))
10580         if (ptid_get_lwp (ptid) == 0)
10581           return normal_pid_to_str (ptid);
10582         else
10583           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10584                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
10585       else
10586         xsnprintf (buf, sizeof buf, "Thread %ld",
10587                    ptid_get_lwp (ptid));
10588       return buf;
10589     }
10590 }
10591
10592 /* Get the address of the thread local variable in OBJFILE which is
10593    stored at OFFSET within the thread local storage for thread PTID.  */
10594
10595 static CORE_ADDR
10596 remote_get_thread_local_address (struct target_ops *ops,
10597                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10598 {
10599   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10600     {
10601       struct remote_state *rs = get_remote_state ();
10602       char *p = rs->buf;
10603       char *endp = rs->buf + get_remote_packet_size ();
10604       enum packet_result result;
10605
10606       strcpy (p, "qGetTLSAddr:");
10607       p += strlen (p);
10608       p = write_ptid (p, endp, ptid);
10609       *p++ = ',';
10610       p += hexnumstr (p, offset);
10611       *p++ = ',';
10612       p += hexnumstr (p, lm);
10613       *p++ = '\0';
10614
10615       putpkt (rs->buf);
10616       getpkt (&rs->buf, &rs->buf_size, 0);
10617       result = packet_ok (rs->buf,
10618                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
10619       if (result == PACKET_OK)
10620         {
10621           ULONGEST result;
10622
10623           unpack_varlen_hex (rs->buf, &result);
10624           return result;
10625         }
10626       else if (result == PACKET_UNKNOWN)
10627         throw_error (TLS_GENERIC_ERROR,
10628                      _("Remote target doesn't support qGetTLSAddr packet"));
10629       else
10630         throw_error (TLS_GENERIC_ERROR,
10631                      _("Remote target failed to process qGetTLSAddr request"));
10632     }
10633   else
10634     throw_error (TLS_GENERIC_ERROR,
10635                  _("TLS not supported or disabled on this target"));
10636   /* Not reached.  */
10637   return 0;
10638 }
10639
10640 /* Provide thread local base, i.e. Thread Information Block address.
10641    Returns 1 if ptid is found and thread_local_base is non zero.  */
10642
10643 static int
10644 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10645 {
10646   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10647     {
10648       struct remote_state *rs = get_remote_state ();
10649       char *p = rs->buf;
10650       char *endp = rs->buf + get_remote_packet_size ();
10651       enum packet_result result;
10652
10653       strcpy (p, "qGetTIBAddr:");
10654       p += strlen (p);
10655       p = write_ptid (p, endp, ptid);
10656       *p++ = '\0';
10657
10658       putpkt (rs->buf);
10659       getpkt (&rs->buf, &rs->buf_size, 0);
10660       result = packet_ok (rs->buf,
10661                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
10662       if (result == PACKET_OK)
10663         {
10664           ULONGEST result;
10665
10666           unpack_varlen_hex (rs->buf, &result);
10667           if (addr)
10668             *addr = (CORE_ADDR) result;
10669           return 1;
10670         }
10671       else if (result == PACKET_UNKNOWN)
10672         error (_("Remote target doesn't support qGetTIBAddr packet"));
10673       else
10674         error (_("Remote target failed to process qGetTIBAddr request"));
10675     }
10676   else
10677     error (_("qGetTIBAddr not supported or disabled on this target"));
10678   /* Not reached.  */
10679   return 0;
10680 }
10681
10682 /* Support for inferring a target description based on the current
10683    architecture and the size of a 'g' packet.  While the 'g' packet
10684    can have any size (since optional registers can be left off the
10685    end), some sizes are easily recognizable given knowledge of the
10686    approximate architecture.  */
10687
10688 struct remote_g_packet_guess
10689 {
10690   int bytes;
10691   const struct target_desc *tdesc;
10692 };
10693 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10694 DEF_VEC_O(remote_g_packet_guess_s);
10695
10696 struct remote_g_packet_data
10697 {
10698   VEC(remote_g_packet_guess_s) *guesses;
10699 };
10700
10701 static struct gdbarch_data *remote_g_packet_data_handle;
10702
10703 static void *
10704 remote_g_packet_data_init (struct obstack *obstack)
10705 {
10706   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10707 }
10708
10709 void
10710 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10711                                 const struct target_desc *tdesc)
10712 {
10713   struct remote_g_packet_data *data
10714     = ((struct remote_g_packet_data *)
10715        gdbarch_data (gdbarch, remote_g_packet_data_handle));
10716   struct remote_g_packet_guess new_guess, *guess;
10717   int ix;
10718
10719   gdb_assert (tdesc != NULL);
10720
10721   for (ix = 0;
10722        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10723        ix++)
10724     if (guess->bytes == bytes)
10725       internal_error (__FILE__, __LINE__,
10726                       _("Duplicate g packet description added for size %d"),
10727                       bytes);
10728
10729   new_guess.bytes = bytes;
10730   new_guess.tdesc = tdesc;
10731   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10732 }
10733
10734 /* Return 1 if remote_read_description would do anything on this target
10735    and architecture, 0 otherwise.  */
10736
10737 static int
10738 remote_read_description_p (struct target_ops *target)
10739 {
10740   struct remote_g_packet_data *data
10741     = ((struct remote_g_packet_data *)
10742        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10743
10744   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10745     return 1;
10746
10747   return 0;
10748 }
10749
10750 static const struct target_desc *
10751 remote_read_description (struct target_ops *target)
10752 {
10753   struct remote_g_packet_data *data
10754     = ((struct remote_g_packet_data *)
10755        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10756
10757   /* Do not try this during initial connection, when we do not know
10758      whether there is a running but stopped thread.  */
10759   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10760     return target->beneath->to_read_description (target->beneath);
10761
10762   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10763     {
10764       struct remote_g_packet_guess *guess;
10765       int ix;
10766       int bytes = send_g_packet ();
10767
10768       for (ix = 0;
10769            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10770            ix++)
10771         if (guess->bytes == bytes)
10772           return guess->tdesc;
10773
10774       /* We discard the g packet.  A minor optimization would be to
10775          hold on to it, and fill the register cache once we have selected
10776          an architecture, but it's too tricky to do safely.  */
10777     }
10778
10779   return target->beneath->to_read_description (target->beneath);
10780 }
10781
10782 /* Remote file transfer support.  This is host-initiated I/O, not
10783    target-initiated; for target-initiated, see remote-fileio.c.  */
10784
10785 /* If *LEFT is at least the length of STRING, copy STRING to
10786    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10787    decrease *LEFT.  Otherwise raise an error.  */
10788
10789 static void
10790 remote_buffer_add_string (char **buffer, int *left, char *string)
10791 {
10792   int len = strlen (string);
10793
10794   if (len > *left)
10795     error (_("Packet too long for target."));
10796
10797   memcpy (*buffer, string, len);
10798   *buffer += len;
10799   *left -= len;
10800
10801   /* NUL-terminate the buffer as a convenience, if there is
10802      room.  */
10803   if (*left)
10804     **buffer = '\0';
10805 }
10806
10807 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10808    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10809    decrease *LEFT.  Otherwise raise an error.  */
10810
10811 static void
10812 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10813                          int len)
10814 {
10815   if (2 * len > *left)
10816     error (_("Packet too long for target."));
10817
10818   bin2hex (bytes, *buffer, len);
10819   *buffer += 2 * len;
10820   *left -= 2 * len;
10821
10822   /* NUL-terminate the buffer as a convenience, if there is
10823      room.  */
10824   if (*left)
10825     **buffer = '\0';
10826 }
10827
10828 /* If *LEFT is large enough, convert VALUE to hex and add it to
10829    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10830    decrease *LEFT.  Otherwise raise an error.  */
10831
10832 static void
10833 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10834 {
10835   int len = hexnumlen (value);
10836
10837   if (len > *left)
10838     error (_("Packet too long for target."));
10839
10840   hexnumstr (*buffer, value);
10841   *buffer += len;
10842   *left -= len;
10843
10844   /* NUL-terminate the buffer as a convenience, if there is
10845      room.  */
10846   if (*left)
10847     **buffer = '\0';
10848 }
10849
10850 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
10851    value, *REMOTE_ERRNO to the remote error number or zero if none
10852    was included, and *ATTACHMENT to point to the start of the annex
10853    if any.  The length of the packet isn't needed here; there may
10854    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10855
10856    Return 0 if the packet could be parsed, -1 if it could not.  If
10857    -1 is returned, the other variables may not be initialized.  */
10858
10859 static int
10860 remote_hostio_parse_result (char *buffer, int *retcode,
10861                             int *remote_errno, char **attachment)
10862 {
10863   char *p, *p2;
10864
10865   *remote_errno = 0;
10866   *attachment = NULL;
10867
10868   if (buffer[0] != 'F')
10869     return -1;
10870
10871   errno = 0;
10872   *retcode = strtol (&buffer[1], &p, 16);
10873   if (errno != 0 || p == &buffer[1])
10874     return -1;
10875
10876   /* Check for ",errno".  */
10877   if (*p == ',')
10878     {
10879       errno = 0;
10880       *remote_errno = strtol (p + 1, &p2, 16);
10881       if (errno != 0 || p + 1 == p2)
10882         return -1;
10883       p = p2;
10884     }
10885
10886   /* Check for ";attachment".  If there is no attachment, the
10887      packet should end here.  */
10888   if (*p == ';')
10889     {
10890       *attachment = p + 1;
10891       return 0;
10892     }
10893   else if (*p == '\0')
10894     return 0;
10895   else
10896     return -1;
10897 }
10898
10899 /* Send a prepared I/O packet to the target and read its response.
10900    The prepared packet is in the global RS->BUF before this function
10901    is called, and the answer is there when we return.
10902
10903    COMMAND_BYTES is the length of the request to send, which may include
10904    binary data.  WHICH_PACKET is the packet configuration to check
10905    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
10906    is set to the error number and -1 is returned.  Otherwise the value
10907    returned by the function is returned.
10908
10909    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10910    attachment is expected; an error will be reported if there's a
10911    mismatch.  If one is found, *ATTACHMENT will be set to point into
10912    the packet buffer and *ATTACHMENT_LEN will be set to the
10913    attachment's length.  */
10914
10915 static int
10916 remote_hostio_send_command (int command_bytes, int which_packet,
10917                             int *remote_errno, char **attachment,
10918                             int *attachment_len)
10919 {
10920   struct remote_state *rs = get_remote_state ();
10921   int ret, bytes_read;
10922   char *attachment_tmp;
10923
10924   if (!rs->remote_desc
10925       || packet_support (which_packet) == PACKET_DISABLE)
10926     {
10927       *remote_errno = FILEIO_ENOSYS;
10928       return -1;
10929     }
10930
10931   putpkt_binary (rs->buf, command_bytes);
10932   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10933
10934   /* If it timed out, something is wrong.  Don't try to parse the
10935      buffer.  */
10936   if (bytes_read < 0)
10937     {
10938       *remote_errno = FILEIO_EINVAL;
10939       return -1;
10940     }
10941
10942   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10943     {
10944     case PACKET_ERROR:
10945       *remote_errno = FILEIO_EINVAL;
10946       return -1;
10947     case PACKET_UNKNOWN:
10948       *remote_errno = FILEIO_ENOSYS;
10949       return -1;
10950     case PACKET_OK:
10951       break;
10952     }
10953
10954   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10955                                   &attachment_tmp))
10956     {
10957       *remote_errno = FILEIO_EINVAL;
10958       return -1;
10959     }
10960
10961   /* Make sure we saw an attachment if and only if we expected one.  */
10962   if ((attachment_tmp == NULL && attachment != NULL)
10963       || (attachment_tmp != NULL && attachment == NULL))
10964     {
10965       *remote_errno = FILEIO_EINVAL;
10966       return -1;
10967     }
10968
10969   /* If an attachment was found, it must point into the packet buffer;
10970      work out how many bytes there were.  */
10971   if (attachment_tmp != NULL)
10972     {
10973       *attachment = attachment_tmp;
10974       *attachment_len = bytes_read - (*attachment - rs->buf);
10975     }
10976
10977   return ret;
10978 }
10979
10980 /* Invalidate the readahead cache.  */
10981
10982 static void
10983 readahead_cache_invalidate (void)
10984 {
10985   struct remote_state *rs = get_remote_state ();
10986
10987   rs->readahead_cache.fd = -1;
10988 }
10989
10990 /* Invalidate the readahead cache if it is holding data for FD.  */
10991
10992 static void
10993 readahead_cache_invalidate_fd (int fd)
10994 {
10995   struct remote_state *rs = get_remote_state ();
10996
10997   if (rs->readahead_cache.fd == fd)
10998     rs->readahead_cache.fd = -1;
10999 }
11000
11001 /* Set the filesystem remote_hostio functions that take FILENAME
11002    arguments will use.  Return 0 on success, or -1 if an error
11003    occurs (and set *REMOTE_ERRNO).  */
11004
11005 static int
11006 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11007 {
11008   struct remote_state *rs = get_remote_state ();
11009   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11010   char *p = rs->buf;
11011   int left = get_remote_packet_size () - 1;
11012   char arg[9];
11013   int ret;
11014
11015   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11016     return 0;
11017
11018   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11019     return 0;
11020
11021   remote_buffer_add_string (&p, &left, "vFile:setfs:");
11022
11023   xsnprintf (arg, sizeof (arg), "%x", required_pid);
11024   remote_buffer_add_string (&p, &left, arg);
11025
11026   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11027                                     remote_errno, NULL, NULL);
11028
11029   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11030     return 0;
11031
11032   if (ret == 0)
11033     rs->fs_pid = required_pid;
11034
11035   return ret;
11036 }
11037
11038 /* Implementation of to_fileio_open.  */
11039
11040 static int
11041 remote_hostio_open (struct target_ops *self,
11042                     struct inferior *inf, const char *filename,
11043                     int flags, int mode, int warn_if_slow,
11044                     int *remote_errno)
11045 {
11046   struct remote_state *rs = get_remote_state ();
11047   char *p = rs->buf;
11048   int left = get_remote_packet_size () - 1;
11049
11050   if (warn_if_slow)
11051     {
11052       static int warning_issued = 0;
11053
11054       printf_unfiltered (_("Reading %s from remote target...\n"),
11055                          filename);
11056
11057       if (!warning_issued)
11058         {
11059           warning (_("File transfers from remote targets can be slow."
11060                      " Use \"set sysroot\" to access files locally"
11061                      " instead."));
11062           warning_issued = 1;
11063         }
11064     }
11065
11066   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11067     return -1;
11068
11069   remote_buffer_add_string (&p, &left, "vFile:open:");
11070
11071   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11072                            strlen (filename));
11073   remote_buffer_add_string (&p, &left, ",");
11074
11075   remote_buffer_add_int (&p, &left, flags);
11076   remote_buffer_add_string (&p, &left, ",");
11077
11078   remote_buffer_add_int (&p, &left, mode);
11079
11080   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11081                                      remote_errno, NULL, NULL);
11082 }
11083
11084 /* Implementation of to_fileio_pwrite.  */
11085
11086 static int
11087 remote_hostio_pwrite (struct target_ops *self,
11088                       int fd, const gdb_byte *write_buf, int len,
11089                       ULONGEST offset, int *remote_errno)
11090 {
11091   struct remote_state *rs = get_remote_state ();
11092   char *p = rs->buf;
11093   int left = get_remote_packet_size ();
11094   int out_len;
11095
11096   readahead_cache_invalidate_fd (fd);
11097
11098   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11099
11100   remote_buffer_add_int (&p, &left, fd);
11101   remote_buffer_add_string (&p, &left, ",");
11102
11103   remote_buffer_add_int (&p, &left, offset);
11104   remote_buffer_add_string (&p, &left, ",");
11105
11106   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11107                              get_remote_packet_size () - (p - rs->buf));
11108
11109   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11110                                      remote_errno, NULL, NULL);
11111 }
11112
11113 /* Helper for the implementation of to_fileio_pread.  Read the file
11114    from the remote side with vFile:pread.  */
11115
11116 static int
11117 remote_hostio_pread_vFile (struct target_ops *self,
11118                            int fd, gdb_byte *read_buf, int len,
11119                            ULONGEST offset, int *remote_errno)
11120 {
11121   struct remote_state *rs = get_remote_state ();
11122   char *p = rs->buf;
11123   char *attachment;
11124   int left = get_remote_packet_size ();
11125   int ret, attachment_len;
11126   int read_len;
11127
11128   remote_buffer_add_string (&p, &left, "vFile:pread:");
11129
11130   remote_buffer_add_int (&p, &left, fd);
11131   remote_buffer_add_string (&p, &left, ",");
11132
11133   remote_buffer_add_int (&p, &left, len);
11134   remote_buffer_add_string (&p, &left, ",");
11135
11136   remote_buffer_add_int (&p, &left, offset);
11137
11138   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11139                                     remote_errno, &attachment,
11140                                     &attachment_len);
11141
11142   if (ret < 0)
11143     return ret;
11144
11145   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11146                                     read_buf, len);
11147   if (read_len != ret)
11148     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11149
11150   return ret;
11151 }
11152
11153 /* Serve pread from the readahead cache.  Returns number of bytes
11154    read, or 0 if the request can't be served from the cache.  */
11155
11156 static int
11157 remote_hostio_pread_from_cache (struct remote_state *rs,
11158                                 int fd, gdb_byte *read_buf, size_t len,
11159                                 ULONGEST offset)
11160 {
11161   struct readahead_cache *cache = &rs->readahead_cache;
11162
11163   if (cache->fd == fd
11164       && cache->offset <= offset
11165       && offset < cache->offset + cache->bufsize)
11166     {
11167       ULONGEST max = cache->offset + cache->bufsize;
11168
11169       if (offset + len > max)
11170         len = max - offset;
11171
11172       memcpy (read_buf, cache->buf + offset - cache->offset, len);
11173       return len;
11174     }
11175
11176   return 0;
11177 }
11178
11179 /* Implementation of to_fileio_pread.  */
11180
11181 static int
11182 remote_hostio_pread (struct target_ops *self,
11183                      int fd, gdb_byte *read_buf, int len,
11184                      ULONGEST offset, int *remote_errno)
11185 {
11186   int ret;
11187   struct remote_state *rs = get_remote_state ();
11188   struct readahead_cache *cache = &rs->readahead_cache;
11189
11190   ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11191   if (ret > 0)
11192     {
11193       cache->hit_count++;
11194
11195       if (remote_debug)
11196         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11197                             pulongest (cache->hit_count));
11198       return ret;
11199     }
11200
11201   cache->miss_count++;
11202   if (remote_debug)
11203     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11204                         pulongest (cache->miss_count));
11205
11206   cache->fd = fd;
11207   cache->offset = offset;
11208   cache->bufsize = get_remote_packet_size ();
11209   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11210
11211   ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11212                                    cache->offset, remote_errno);
11213   if (ret <= 0)
11214     {
11215       readahead_cache_invalidate_fd (fd);
11216       return ret;
11217     }
11218
11219   cache->bufsize = ret;
11220   return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11221 }
11222
11223 /* Implementation of to_fileio_close.  */
11224
11225 static int
11226 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11227 {
11228   struct remote_state *rs = get_remote_state ();
11229   char *p = rs->buf;
11230   int left = get_remote_packet_size () - 1;
11231
11232   readahead_cache_invalidate_fd (fd);
11233
11234   remote_buffer_add_string (&p, &left, "vFile:close:");
11235
11236   remote_buffer_add_int (&p, &left, fd);
11237
11238   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11239                                      remote_errno, NULL, NULL);
11240 }
11241
11242 /* Implementation of to_fileio_unlink.  */
11243
11244 static int
11245 remote_hostio_unlink (struct target_ops *self,
11246                       struct inferior *inf, const char *filename,
11247                       int *remote_errno)
11248 {
11249   struct remote_state *rs = get_remote_state ();
11250   char *p = rs->buf;
11251   int left = get_remote_packet_size () - 1;
11252
11253   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11254     return -1;
11255
11256   remote_buffer_add_string (&p, &left, "vFile:unlink:");
11257
11258   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11259                            strlen (filename));
11260
11261   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11262                                      remote_errno, NULL, NULL);
11263 }
11264
11265 /* Implementation of to_fileio_readlink.  */
11266
11267 static char *
11268 remote_hostio_readlink (struct target_ops *self,
11269                         struct inferior *inf, const char *filename,
11270                         int *remote_errno)
11271 {
11272   struct remote_state *rs = get_remote_state ();
11273   char *p = rs->buf;
11274   char *attachment;
11275   int left = get_remote_packet_size ();
11276   int len, attachment_len;
11277   int read_len;
11278   char *ret;
11279
11280   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11281     return NULL;
11282
11283   remote_buffer_add_string (&p, &left, "vFile:readlink:");
11284
11285   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11286                            strlen (filename));
11287
11288   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11289                                     remote_errno, &attachment,
11290                                     &attachment_len);
11291
11292   if (len < 0)
11293     return NULL;
11294
11295   ret = (char *) xmalloc (len + 1);
11296
11297   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11298                                     (gdb_byte *) ret, len);
11299   if (read_len != len)
11300     error (_("Readlink returned %d, but %d bytes."), len, read_len);
11301
11302   ret[len] = '\0';
11303   return ret;
11304 }
11305
11306 /* Implementation of to_fileio_fstat.  */
11307
11308 static int
11309 remote_hostio_fstat (struct target_ops *self,
11310                      int fd, struct stat *st,
11311                      int *remote_errno)
11312 {
11313   struct remote_state *rs = get_remote_state ();
11314   char *p = rs->buf;
11315   int left = get_remote_packet_size ();
11316   int attachment_len, ret;
11317   char *attachment;
11318   struct fio_stat fst;
11319   int read_len;
11320
11321   remote_buffer_add_string (&p, &left, "vFile:fstat:");
11322
11323   remote_buffer_add_int (&p, &left, fd);
11324
11325   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11326                                     remote_errno, &attachment,
11327                                     &attachment_len);
11328   if (ret < 0)
11329     {
11330       if (*remote_errno != FILEIO_ENOSYS)
11331         return ret;
11332
11333       /* Strictly we should return -1, ENOSYS here, but when
11334          "set sysroot remote:" was implemented in August 2008
11335          BFD's need for a stat function was sidestepped with
11336          this hack.  This was not remedied until March 2015
11337          so we retain the previous behavior to avoid breaking
11338          compatibility.
11339
11340          Note that the memset is a March 2015 addition; older
11341          GDBs set st_size *and nothing else* so the structure
11342          would have garbage in all other fields.  This might
11343          break something but retaining the previous behavior
11344          here would be just too wrong.  */
11345
11346       memset (st, 0, sizeof (struct stat));
11347       st->st_size = INT_MAX;
11348       return 0;
11349     }
11350
11351   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11352                                     (gdb_byte *) &fst, sizeof (fst));
11353
11354   if (read_len != ret)
11355     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11356
11357   if (read_len != sizeof (fst))
11358     error (_("vFile:fstat returned %d bytes, but expecting %d."),
11359            read_len, (int) sizeof (fst));
11360
11361   remote_fileio_to_host_stat (&fst, st);
11362
11363   return 0;
11364 }
11365
11366 /* Implementation of to_filesystem_is_local.  */
11367
11368 static int
11369 remote_filesystem_is_local (struct target_ops *self)
11370 {
11371   /* Valgrind GDB presents itself as a remote target but works
11372      on the local filesystem: it does not implement remote get
11373      and users are not expected to set a sysroot.  To handle
11374      this case we treat the remote filesystem as local if the
11375      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11376      does not support vFile:open.  */
11377   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11378     {
11379       enum packet_support ps = packet_support (PACKET_vFile_open);
11380
11381       if (ps == PACKET_SUPPORT_UNKNOWN)
11382         {
11383           int fd, remote_errno;
11384
11385           /* Try opening a file to probe support.  The supplied
11386              filename is irrelevant, we only care about whether
11387              the stub recognizes the packet or not.  */
11388           fd = remote_hostio_open (self, NULL, "just probing",
11389                                    FILEIO_O_RDONLY, 0700, 0,
11390                                    &remote_errno);
11391
11392           if (fd >= 0)
11393             remote_hostio_close (self, fd, &remote_errno);
11394
11395           ps = packet_support (PACKET_vFile_open);
11396         }
11397
11398       if (ps == PACKET_DISABLE)
11399         {
11400           static int warning_issued = 0;
11401
11402           if (!warning_issued)
11403             {
11404               warning (_("remote target does not support file"
11405                          " transfer, attempting to access files"
11406                          " from local filesystem."));
11407               warning_issued = 1;
11408             }
11409
11410           return 1;
11411         }
11412     }
11413
11414   return 0;
11415 }
11416
11417 static int
11418 remote_fileio_errno_to_host (int errnum)
11419 {
11420   switch (errnum)
11421     {
11422       case FILEIO_EPERM:
11423         return EPERM;
11424       case FILEIO_ENOENT:
11425         return ENOENT;
11426       case FILEIO_EINTR:
11427         return EINTR;
11428       case FILEIO_EIO:
11429         return EIO;
11430       case FILEIO_EBADF:
11431         return EBADF;
11432       case FILEIO_EACCES:
11433         return EACCES;
11434       case FILEIO_EFAULT:
11435         return EFAULT;
11436       case FILEIO_EBUSY:
11437         return EBUSY;
11438       case FILEIO_EEXIST:
11439         return EEXIST;
11440       case FILEIO_ENODEV:
11441         return ENODEV;
11442       case FILEIO_ENOTDIR:
11443         return ENOTDIR;
11444       case FILEIO_EISDIR:
11445         return EISDIR;
11446       case FILEIO_EINVAL:
11447         return EINVAL;
11448       case FILEIO_ENFILE:
11449         return ENFILE;
11450       case FILEIO_EMFILE:
11451         return EMFILE;
11452       case FILEIO_EFBIG:
11453         return EFBIG;
11454       case FILEIO_ENOSPC:
11455         return ENOSPC;
11456       case FILEIO_ESPIPE:
11457         return ESPIPE;
11458       case FILEIO_EROFS:
11459         return EROFS;
11460       case FILEIO_ENOSYS:
11461         return ENOSYS;
11462       case FILEIO_ENAMETOOLONG:
11463         return ENAMETOOLONG;
11464     }
11465   return -1;
11466 }
11467
11468 static char *
11469 remote_hostio_error (int errnum)
11470 {
11471   int host_error = remote_fileio_errno_to_host (errnum);
11472
11473   if (host_error == -1)
11474     error (_("Unknown remote I/O error %d"), errnum);
11475   else
11476     error (_("Remote I/O error: %s"), safe_strerror (host_error));
11477 }
11478
11479 static void
11480 remote_hostio_close_cleanup (void *opaque)
11481 {
11482   int fd = *(int *) opaque;
11483   int remote_errno;
11484
11485   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11486 }
11487
11488 void
11489 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11490 {
11491   struct cleanup *back_to, *close_cleanup;
11492   int retcode, fd, remote_errno, bytes, io_size;
11493   FILE *file;
11494   gdb_byte *buffer;
11495   int bytes_in_buffer;
11496   int saw_eof;
11497   ULONGEST offset;
11498   struct remote_state *rs = get_remote_state ();
11499
11500   if (!rs->remote_desc)
11501     error (_("command can only be used with remote target"));
11502
11503   file = gdb_fopen_cloexec (local_file, "rb");
11504   if (file == NULL)
11505     perror_with_name (local_file);
11506   back_to = make_cleanup_fclose (file);
11507
11508   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11509                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11510                                          | FILEIO_O_TRUNC),
11511                            0700, 0, &remote_errno);
11512   if (fd == -1)
11513     remote_hostio_error (remote_errno);
11514
11515   /* Send up to this many bytes at once.  They won't all fit in the
11516      remote packet limit, so we'll transfer slightly fewer.  */
11517   io_size = get_remote_packet_size ();
11518   buffer = (gdb_byte *) xmalloc (io_size);
11519   make_cleanup (xfree, buffer);
11520
11521   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11522
11523   bytes_in_buffer = 0;
11524   saw_eof = 0;
11525   offset = 0;
11526   while (bytes_in_buffer || !saw_eof)
11527     {
11528       if (!saw_eof)
11529         {
11530           bytes = fread (buffer + bytes_in_buffer, 1,
11531                          io_size - bytes_in_buffer,
11532                          file);
11533           if (bytes == 0)
11534             {
11535               if (ferror (file))
11536                 error (_("Error reading %s."), local_file);
11537               else
11538                 {
11539                   /* EOF.  Unless there is something still in the
11540                      buffer from the last iteration, we are done.  */
11541                   saw_eof = 1;
11542                   if (bytes_in_buffer == 0)
11543                     break;
11544                 }
11545             }
11546         }
11547       else
11548         bytes = 0;
11549
11550       bytes += bytes_in_buffer;
11551       bytes_in_buffer = 0;
11552
11553       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11554                                       fd, buffer, bytes,
11555                                       offset, &remote_errno);
11556
11557       if (retcode < 0)
11558         remote_hostio_error (remote_errno);
11559       else if (retcode == 0)
11560         error (_("Remote write of %d bytes returned 0!"), bytes);
11561       else if (retcode < bytes)
11562         {
11563           /* Short write.  Save the rest of the read data for the next
11564              write.  */
11565           bytes_in_buffer = bytes - retcode;
11566           memmove (buffer, buffer + retcode, bytes_in_buffer);
11567         }
11568
11569       offset += retcode;
11570     }
11571
11572   discard_cleanups (close_cleanup);
11573   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11574     remote_hostio_error (remote_errno);
11575
11576   if (from_tty)
11577     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11578   do_cleanups (back_to);
11579 }
11580
11581 void
11582 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11583 {
11584   struct cleanup *back_to, *close_cleanup;
11585   int fd, remote_errno, bytes, io_size;
11586   FILE *file;
11587   gdb_byte *buffer;
11588   ULONGEST offset;
11589   struct remote_state *rs = get_remote_state ();
11590
11591   if (!rs->remote_desc)
11592     error (_("command can only be used with remote target"));
11593
11594   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11595                            remote_file, FILEIO_O_RDONLY, 0, 0,
11596                            &remote_errno);
11597   if (fd == -1)
11598     remote_hostio_error (remote_errno);
11599
11600   file = gdb_fopen_cloexec (local_file, "wb");
11601   if (file == NULL)
11602     perror_with_name (local_file);
11603   back_to = make_cleanup_fclose (file);
11604
11605   /* Send up to this many bytes at once.  They won't all fit in the
11606      remote packet limit, so we'll transfer slightly fewer.  */
11607   io_size = get_remote_packet_size ();
11608   buffer = (gdb_byte *) xmalloc (io_size);
11609   make_cleanup (xfree, buffer);
11610
11611   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11612
11613   offset = 0;
11614   while (1)
11615     {
11616       bytes = remote_hostio_pread (find_target_at (process_stratum),
11617                                    fd, buffer, io_size, offset, &remote_errno);
11618       if (bytes == 0)
11619         /* Success, but no bytes, means end-of-file.  */
11620         break;
11621       if (bytes == -1)
11622         remote_hostio_error (remote_errno);
11623
11624       offset += bytes;
11625
11626       bytes = fwrite (buffer, 1, bytes, file);
11627       if (bytes == 0)
11628         perror_with_name (local_file);
11629     }
11630
11631   discard_cleanups (close_cleanup);
11632   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11633     remote_hostio_error (remote_errno);
11634
11635   if (from_tty)
11636     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11637   do_cleanups (back_to);
11638 }
11639
11640 void
11641 remote_file_delete (const char *remote_file, int from_tty)
11642 {
11643   int retcode, remote_errno;
11644   struct remote_state *rs = get_remote_state ();
11645
11646   if (!rs->remote_desc)
11647     error (_("command can only be used with remote target"));
11648
11649   retcode = remote_hostio_unlink (find_target_at (process_stratum),
11650                                   NULL, remote_file, &remote_errno);
11651   if (retcode == -1)
11652     remote_hostio_error (remote_errno);
11653
11654   if (from_tty)
11655     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11656 }
11657
11658 static void
11659 remote_put_command (char *args, int from_tty)
11660 {
11661   struct cleanup *back_to;
11662   char **argv;
11663
11664   if (args == NULL)
11665     error_no_arg (_("file to put"));
11666
11667   argv = gdb_buildargv (args);
11668   back_to = make_cleanup_freeargv (argv);
11669   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11670     error (_("Invalid parameters to remote put"));
11671
11672   remote_file_put (argv[0], argv[1], from_tty);
11673
11674   do_cleanups (back_to);
11675 }
11676
11677 static void
11678 remote_get_command (char *args, int from_tty)
11679 {
11680   struct cleanup *back_to;
11681   char **argv;
11682
11683   if (args == NULL)
11684     error_no_arg (_("file to get"));
11685
11686   argv = gdb_buildargv (args);
11687   back_to = make_cleanup_freeargv (argv);
11688   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11689     error (_("Invalid parameters to remote get"));
11690
11691   remote_file_get (argv[0], argv[1], from_tty);
11692
11693   do_cleanups (back_to);
11694 }
11695
11696 static void
11697 remote_delete_command (char *args, int from_tty)
11698 {
11699   struct cleanup *back_to;
11700   char **argv;
11701
11702   if (args == NULL)
11703     error_no_arg (_("file to delete"));
11704
11705   argv = gdb_buildargv (args);
11706   back_to = make_cleanup_freeargv (argv);
11707   if (argv[0] == NULL || argv[1] != NULL)
11708     error (_("Invalid parameters to remote delete"));
11709
11710   remote_file_delete (argv[0], from_tty);
11711
11712   do_cleanups (back_to);
11713 }
11714
11715 static void
11716 remote_command (char *args, int from_tty)
11717 {
11718   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11719 }
11720
11721 static int
11722 remote_can_execute_reverse (struct target_ops *self)
11723 {
11724   if (packet_support (PACKET_bs) == PACKET_ENABLE
11725       || packet_support (PACKET_bc) == PACKET_ENABLE)
11726     return 1;
11727   else
11728     return 0;
11729 }
11730
11731 static int
11732 remote_supports_non_stop (struct target_ops *self)
11733 {
11734   return 1;
11735 }
11736
11737 static int
11738 remote_supports_disable_randomization (struct target_ops *self)
11739 {
11740   /* Only supported in extended mode.  */
11741   return 0;
11742 }
11743
11744 static int
11745 remote_supports_multi_process (struct target_ops *self)
11746 {
11747   struct remote_state *rs = get_remote_state ();
11748
11749   return remote_multi_process_p (rs);
11750 }
11751
11752 static int
11753 remote_supports_cond_tracepoints (void)
11754 {
11755   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11756 }
11757
11758 static int
11759 remote_supports_cond_breakpoints (struct target_ops *self)
11760 {
11761   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11762 }
11763
11764 static int
11765 remote_supports_fast_tracepoints (void)
11766 {
11767   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11768 }
11769
11770 static int
11771 remote_supports_static_tracepoints (void)
11772 {
11773   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11774 }
11775
11776 static int
11777 remote_supports_install_in_trace (void)
11778 {
11779   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11780 }
11781
11782 static int
11783 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11784 {
11785   return (packet_support (PACKET_EnableDisableTracepoints_feature)
11786           == PACKET_ENABLE);
11787 }
11788
11789 static int
11790 remote_supports_string_tracing (struct target_ops *self)
11791 {
11792   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11793 }
11794
11795 static int
11796 remote_can_run_breakpoint_commands (struct target_ops *self)
11797 {
11798   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11799 }
11800
11801 static void
11802 remote_trace_init (struct target_ops *self)
11803 {
11804   putpkt ("QTinit");
11805   remote_get_noisy_reply (&target_buf, &target_buf_size);
11806   if (strcmp (target_buf, "OK") != 0)
11807     error (_("Target does not support this command."));
11808 }
11809
11810 static void free_actions_list (char **actions_list);
11811 static void free_actions_list_cleanup_wrapper (void *);
11812 static void
11813 free_actions_list_cleanup_wrapper (void *al)
11814 {
11815   free_actions_list ((char **) al);
11816 }
11817
11818 static void
11819 free_actions_list (char **actions_list)
11820 {
11821   int ndx;
11822
11823   if (actions_list == 0)
11824     return;
11825
11826   for (ndx = 0; actions_list[ndx]; ndx++)
11827     xfree (actions_list[ndx]);
11828
11829   xfree (actions_list);
11830 }
11831
11832 /* Recursive routine to walk through command list including loops, and
11833    download packets for each command.  */
11834
11835 static void
11836 remote_download_command_source (int num, ULONGEST addr,
11837                                 struct command_line *cmds)
11838 {
11839   struct remote_state *rs = get_remote_state ();
11840   struct command_line *cmd;
11841
11842   for (cmd = cmds; cmd; cmd = cmd->next)
11843     {
11844       QUIT;     /* Allow user to bail out with ^C.  */
11845       strcpy (rs->buf, "QTDPsrc:");
11846       encode_source_string (num, addr, "cmd", cmd->line,
11847                             rs->buf + strlen (rs->buf),
11848                             rs->buf_size - strlen (rs->buf));
11849       putpkt (rs->buf);
11850       remote_get_noisy_reply (&target_buf, &target_buf_size);
11851       if (strcmp (target_buf, "OK"))
11852         warning (_("Target does not support source download."));
11853
11854       if (cmd->control_type == while_control
11855           || cmd->control_type == while_stepping_control)
11856         {
11857           remote_download_command_source (num, addr, *cmd->body_list);
11858
11859           QUIT; /* Allow user to bail out with ^C.  */
11860           strcpy (rs->buf, "QTDPsrc:");
11861           encode_source_string (num, addr, "cmd", "end",
11862                                 rs->buf + strlen (rs->buf),
11863                                 rs->buf_size - strlen (rs->buf));
11864           putpkt (rs->buf);
11865           remote_get_noisy_reply (&target_buf, &target_buf_size);
11866           if (strcmp (target_buf, "OK"))
11867             warning (_("Target does not support source download."));
11868         }
11869     }
11870 }
11871
11872 static void
11873 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11874 {
11875 #define BUF_SIZE 2048
11876
11877   CORE_ADDR tpaddr;
11878   char addrbuf[40];
11879   char buf[BUF_SIZE];
11880   char **tdp_actions;
11881   char **stepping_actions;
11882   int ndx;
11883   struct cleanup *old_chain = NULL;
11884   struct agent_expr *aexpr;
11885   struct cleanup *aexpr_chain = NULL;
11886   char *pkt;
11887   struct breakpoint *b = loc->owner;
11888   struct tracepoint *t = (struct tracepoint *) b;
11889
11890   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11891   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11892                             tdp_actions);
11893   (void) make_cleanup (free_actions_list_cleanup_wrapper,
11894                        stepping_actions);
11895
11896   tpaddr = loc->address;
11897   sprintf_vma (addrbuf, tpaddr);
11898   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11899              addrbuf, /* address */
11900              (b->enable_state == bp_enabled ? 'E' : 'D'),
11901              t->step_count, t->pass_count);
11902   /* Fast tracepoints are mostly handled by the target, but we can
11903      tell the target how big of an instruction block should be moved
11904      around.  */
11905   if (b->type == bp_fast_tracepoint)
11906     {
11907       /* Only test for support at download time; we may not know
11908          target capabilities at definition time.  */
11909       if (remote_supports_fast_tracepoints ())
11910         {
11911           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11912                                                 NULL))
11913             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11914                        gdb_insn_length (loc->gdbarch, tpaddr));
11915           else
11916             /* If it passed validation at definition but fails now,
11917                something is very wrong.  */
11918             internal_error (__FILE__, __LINE__,
11919                             _("Fast tracepoint not "
11920                               "valid during download"));
11921         }
11922       else
11923         /* Fast tracepoints are functionally identical to regular
11924            tracepoints, so don't take lack of support as a reason to
11925            give up on the trace run.  */
11926         warning (_("Target does not support fast tracepoints, "
11927                    "downloading %d as regular tracepoint"), b->number);
11928     }
11929   else if (b->type == bp_static_tracepoint)
11930     {
11931       /* Only test for support at download time; we may not know
11932          target capabilities at definition time.  */
11933       if (remote_supports_static_tracepoints ())
11934         {
11935           struct static_tracepoint_marker marker;
11936
11937           if (target_static_tracepoint_marker_at (tpaddr, &marker))
11938             strcat (buf, ":S");
11939           else
11940             error (_("Static tracepoint not valid during download"));
11941         }
11942       else
11943         /* Fast tracepoints are functionally identical to regular
11944            tracepoints, so don't take lack of support as a reason
11945            to give up on the trace run.  */
11946         error (_("Target does not support static tracepoints"));
11947     }
11948   /* If the tracepoint has a conditional, make it into an agent
11949      expression and append to the definition.  */
11950   if (loc->cond)
11951     {
11952       /* Only test support at download time, we may not know target
11953          capabilities at definition time.  */
11954       if (remote_supports_cond_tracepoints ())
11955         {
11956           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11957           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11958           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11959                      aexpr->len);
11960           pkt = buf + strlen (buf);
11961           for (ndx = 0; ndx < aexpr->len; ++ndx)
11962             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11963           *pkt = '\0';
11964           do_cleanups (aexpr_chain);
11965         }
11966       else
11967         warning (_("Target does not support conditional tracepoints, "
11968                    "ignoring tp %d cond"), b->number);
11969     }
11970
11971   if (b->commands || *default_collect)
11972     strcat (buf, "-");
11973   putpkt (buf);
11974   remote_get_noisy_reply (&target_buf, &target_buf_size);
11975   if (strcmp (target_buf, "OK"))
11976     error (_("Target does not support tracepoints."));
11977
11978   /* do_single_steps (t); */
11979   if (tdp_actions)
11980     {
11981       for (ndx = 0; tdp_actions[ndx]; ndx++)
11982         {
11983           QUIT; /* Allow user to bail out with ^C.  */
11984           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11985                      b->number, addrbuf, /* address */
11986                      tdp_actions[ndx],
11987                      ((tdp_actions[ndx + 1] || stepping_actions)
11988                       ? '-' : 0));
11989           putpkt (buf);
11990           remote_get_noisy_reply (&target_buf,
11991                                   &target_buf_size);
11992           if (strcmp (target_buf, "OK"))
11993             error (_("Error on target while setting tracepoints."));
11994         }
11995     }
11996   if (stepping_actions)
11997     {
11998       for (ndx = 0; stepping_actions[ndx]; ndx++)
11999         {
12000           QUIT; /* Allow user to bail out with ^C.  */
12001           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12002                      b->number, addrbuf, /* address */
12003                      ((ndx == 0) ? "S" : ""),
12004                      stepping_actions[ndx],
12005                      (stepping_actions[ndx + 1] ? "-" : ""));
12006           putpkt (buf);
12007           remote_get_noisy_reply (&target_buf,
12008                                   &target_buf_size);
12009           if (strcmp (target_buf, "OK"))
12010             error (_("Error on target while setting tracepoints."));
12011         }
12012     }
12013
12014   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12015     {
12016       if (b->location != NULL)
12017         {
12018           strcpy (buf, "QTDPsrc:");
12019           encode_source_string (b->number, loc->address, "at",
12020                                 event_location_to_string (b->location),
12021                                 buf + strlen (buf), 2048 - strlen (buf));
12022           putpkt (buf);
12023           remote_get_noisy_reply (&target_buf, &target_buf_size);
12024           if (strcmp (target_buf, "OK"))
12025             warning (_("Target does not support source download."));
12026         }
12027       if (b->cond_string)
12028         {
12029           strcpy (buf, "QTDPsrc:");
12030           encode_source_string (b->number, loc->address,
12031                                 "cond", b->cond_string, buf + strlen (buf),
12032                                 2048 - strlen (buf));
12033           putpkt (buf);
12034           remote_get_noisy_reply (&target_buf, &target_buf_size);
12035           if (strcmp (target_buf, "OK"))
12036             warning (_("Target does not support source download."));
12037         }
12038       remote_download_command_source (b->number, loc->address,
12039                                       breakpoint_commands (b));
12040     }
12041
12042   do_cleanups (old_chain);
12043 }
12044
12045 static int
12046 remote_can_download_tracepoint (struct target_ops *self)
12047 {
12048   struct remote_state *rs = get_remote_state ();
12049   struct trace_status *ts;
12050   int status;
12051
12052   /* Don't try to install tracepoints until we've relocated our
12053      symbols, and fetched and merged the target's tracepoint list with
12054      ours.  */
12055   if (rs->starting_up)
12056     return 0;
12057
12058   ts = current_trace_status ();
12059   status = remote_get_trace_status (self, ts);
12060
12061   if (status == -1 || !ts->running_known || !ts->running)
12062     return 0;
12063
12064   /* If we are in a tracing experiment, but remote stub doesn't support
12065      installing tracepoint in trace, we have to return.  */
12066   if (!remote_supports_install_in_trace ())
12067     return 0;
12068
12069   return 1;
12070 }
12071
12072
12073 static void
12074 remote_download_trace_state_variable (struct target_ops *self,
12075                                       struct trace_state_variable *tsv)
12076 {
12077   struct remote_state *rs = get_remote_state ();
12078   char *p;
12079
12080   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12081              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12082              tsv->builtin);
12083   p = rs->buf + strlen (rs->buf);
12084   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12085     error (_("Trace state variable name too long for tsv definition packet"));
12086   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12087   *p++ = '\0';
12088   putpkt (rs->buf);
12089   remote_get_noisy_reply (&target_buf, &target_buf_size);
12090   if (*target_buf == '\0')
12091     error (_("Target does not support this command."));
12092   if (strcmp (target_buf, "OK") != 0)
12093     error (_("Error on target while downloading trace state variable."));
12094 }
12095
12096 static void
12097 remote_enable_tracepoint (struct target_ops *self,
12098                           struct bp_location *location)
12099 {
12100   struct remote_state *rs = get_remote_state ();
12101   char addr_buf[40];
12102
12103   sprintf_vma (addr_buf, location->address);
12104   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12105              location->owner->number, addr_buf);
12106   putpkt (rs->buf);
12107   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12108   if (*rs->buf == '\0')
12109     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12110   if (strcmp (rs->buf, "OK") != 0)
12111     error (_("Error on target while enabling tracepoint."));
12112 }
12113
12114 static void
12115 remote_disable_tracepoint (struct target_ops *self,
12116                            struct bp_location *location)
12117 {
12118   struct remote_state *rs = get_remote_state ();
12119   char addr_buf[40];
12120
12121   sprintf_vma (addr_buf, location->address);
12122   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12123              location->owner->number, addr_buf);
12124   putpkt (rs->buf);
12125   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12126   if (*rs->buf == '\0')
12127     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12128   if (strcmp (rs->buf, "OK") != 0)
12129     error (_("Error on target while disabling tracepoint."));
12130 }
12131
12132 static void
12133 remote_trace_set_readonly_regions (struct target_ops *self)
12134 {
12135   asection *s;
12136   bfd *abfd = NULL;
12137   bfd_size_type size;
12138   bfd_vma vma;
12139   int anysecs = 0;
12140   int offset = 0;
12141
12142   if (!exec_bfd)
12143     return;                     /* No information to give.  */
12144
12145   strcpy (target_buf, "QTro");
12146   offset = strlen (target_buf);
12147   for (s = exec_bfd->sections; s; s = s->next)
12148     {
12149       char tmp1[40], tmp2[40];
12150       int sec_length;
12151
12152       if ((s->flags & SEC_LOAD) == 0 ||
12153       /*  (s->flags & SEC_CODE) == 0 || */
12154           (s->flags & SEC_READONLY) == 0)
12155         continue;
12156
12157       anysecs = 1;
12158       vma = bfd_get_section_vma (abfd, s);
12159       size = bfd_get_section_size (s);
12160       sprintf_vma (tmp1, vma);
12161       sprintf_vma (tmp2, vma + size);
12162       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12163       if (offset + sec_length + 1 > target_buf_size)
12164         {
12165           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12166             warning (_("\
12167 Too many sections for read-only sections definition packet."));
12168           break;
12169         }
12170       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12171                  tmp1, tmp2);
12172       offset += sec_length;
12173     }
12174   if (anysecs)
12175     {
12176       putpkt (target_buf);
12177       getpkt (&target_buf, &target_buf_size, 0);
12178     }
12179 }
12180
12181 static void
12182 remote_trace_start (struct target_ops *self)
12183 {
12184   putpkt ("QTStart");
12185   remote_get_noisy_reply (&target_buf, &target_buf_size);
12186   if (*target_buf == '\0')
12187     error (_("Target does not support this command."));
12188   if (strcmp (target_buf, "OK") != 0)
12189     error (_("Bogus reply from target: %s"), target_buf);
12190 }
12191
12192 static int
12193 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12194 {
12195   /* Initialize it just to avoid a GCC false warning.  */
12196   char *p = NULL;
12197   /* FIXME we need to get register block size some other way.  */
12198   extern int trace_regblock_size;
12199   enum packet_result result;
12200
12201   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12202     return -1;
12203
12204   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12205
12206   putpkt ("qTStatus");
12207
12208   TRY
12209     {
12210       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12211     }
12212   CATCH (ex, RETURN_MASK_ERROR)
12213     {
12214       if (ex.error != TARGET_CLOSE_ERROR)
12215         {
12216           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12217           return -1;
12218         }
12219       throw_exception (ex);
12220     }
12221   END_CATCH
12222
12223   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12224
12225   /* If the remote target doesn't do tracing, flag it.  */
12226   if (result == PACKET_UNKNOWN)
12227     return -1;
12228
12229   /* We're working with a live target.  */
12230   ts->filename = NULL;
12231
12232   if (*p++ != 'T')
12233     error (_("Bogus trace status reply from target: %s"), target_buf);
12234
12235   /* Function 'parse_trace_status' sets default value of each field of
12236      'ts' at first, so we don't have to do it here.  */
12237   parse_trace_status (p, ts);
12238
12239   return ts->running;
12240 }
12241
12242 static void
12243 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12244                               struct uploaded_tp *utp)
12245 {
12246   struct remote_state *rs = get_remote_state ();
12247   char *reply;
12248   struct bp_location *loc;
12249   struct tracepoint *tp = (struct tracepoint *) bp;
12250   size_t size = get_remote_packet_size ();
12251
12252   if (tp)
12253     {
12254       tp->base.hit_count = 0;
12255       tp->traceframe_usage = 0;
12256       for (loc = tp->base.loc; loc; loc = loc->next)
12257         {
12258           /* If the tracepoint was never downloaded, don't go asking for
12259              any status.  */
12260           if (tp->number_on_target == 0)
12261             continue;
12262           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12263                      phex_nz (loc->address, 0));
12264           putpkt (rs->buf);
12265           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12266           if (reply && *reply)
12267             {
12268               if (*reply == 'V')
12269                 parse_tracepoint_status (reply + 1, bp, utp);
12270             }
12271         }
12272     }
12273   else if (utp)
12274     {
12275       utp->hit_count = 0;
12276       utp->traceframe_usage = 0;
12277       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12278                  phex_nz (utp->addr, 0));
12279       putpkt (rs->buf);
12280       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12281       if (reply && *reply)
12282         {
12283           if (*reply == 'V')
12284             parse_tracepoint_status (reply + 1, bp, utp);
12285         }
12286     }
12287 }
12288
12289 static void
12290 remote_trace_stop (struct target_ops *self)
12291 {
12292   putpkt ("QTStop");
12293   remote_get_noisy_reply (&target_buf, &target_buf_size);
12294   if (*target_buf == '\0')
12295     error (_("Target does not support this command."));
12296   if (strcmp (target_buf, "OK") != 0)
12297     error (_("Bogus reply from target: %s"), target_buf);
12298 }
12299
12300 static int
12301 remote_trace_find (struct target_ops *self,
12302                    enum trace_find_type type, int num,
12303                    CORE_ADDR addr1, CORE_ADDR addr2,
12304                    int *tpp)
12305 {
12306   struct remote_state *rs = get_remote_state ();
12307   char *endbuf = rs->buf + get_remote_packet_size ();
12308   char *p, *reply;
12309   int target_frameno = -1, target_tracept = -1;
12310
12311   /* Lookups other than by absolute frame number depend on the current
12312      trace selected, so make sure it is correct on the remote end
12313      first.  */
12314   if (type != tfind_number)
12315     set_remote_traceframe ();
12316
12317   p = rs->buf;
12318   strcpy (p, "QTFrame:");
12319   p = strchr (p, '\0');
12320   switch (type)
12321     {
12322     case tfind_number:
12323       xsnprintf (p, endbuf - p, "%x", num);
12324       break;
12325     case tfind_pc:
12326       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12327       break;
12328     case tfind_tp:
12329       xsnprintf (p, endbuf - p, "tdp:%x", num);
12330       break;
12331     case tfind_range:
12332       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12333                  phex_nz (addr2, 0));
12334       break;
12335     case tfind_outside:
12336       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12337                  phex_nz (addr2, 0));
12338       break;
12339     default:
12340       error (_("Unknown trace find type %d"), type);
12341     }
12342
12343   putpkt (rs->buf);
12344   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12345   if (*reply == '\0')
12346     error (_("Target does not support this command."));
12347
12348   while (reply && *reply)
12349     switch (*reply)
12350       {
12351       case 'F':
12352         p = ++reply;
12353         target_frameno = (int) strtol (p, &reply, 16);
12354         if (reply == p)
12355           error (_("Unable to parse trace frame number"));
12356         /* Don't update our remote traceframe number cache on failure
12357            to select a remote traceframe.  */
12358         if (target_frameno == -1)
12359           return -1;
12360         break;
12361       case 'T':
12362         p = ++reply;
12363         target_tracept = (int) strtol (p, &reply, 16);
12364         if (reply == p)
12365           error (_("Unable to parse tracepoint number"));
12366         break;
12367       case 'O':         /* "OK"? */
12368         if (reply[1] == 'K' && reply[2] == '\0')
12369           reply += 2;
12370         else
12371           error (_("Bogus reply from target: %s"), reply);
12372         break;
12373       default:
12374         error (_("Bogus reply from target: %s"), reply);
12375       }
12376   if (tpp)
12377     *tpp = target_tracept;
12378
12379   rs->remote_traceframe_number = target_frameno;
12380   return target_frameno;
12381 }
12382
12383 static int
12384 remote_get_trace_state_variable_value (struct target_ops *self,
12385                                        int tsvnum, LONGEST *val)
12386 {
12387   struct remote_state *rs = get_remote_state ();
12388   char *reply;
12389   ULONGEST uval;
12390
12391   set_remote_traceframe ();
12392
12393   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12394   putpkt (rs->buf);
12395   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12396   if (reply && *reply)
12397     {
12398       if (*reply == 'V')
12399         {
12400           unpack_varlen_hex (reply + 1, &uval);
12401           *val = (LONGEST) uval;
12402           return 1;
12403         }
12404     }
12405   return 0;
12406 }
12407
12408 static int
12409 remote_save_trace_data (struct target_ops *self, const char *filename)
12410 {
12411   struct remote_state *rs = get_remote_state ();
12412   char *p, *reply;
12413
12414   p = rs->buf;
12415   strcpy (p, "QTSave:");
12416   p += strlen (p);
12417   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12418     error (_("Remote file name too long for trace save packet"));
12419   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12420   *p++ = '\0';
12421   putpkt (rs->buf);
12422   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12423   if (*reply == '\0')
12424     error (_("Target does not support this command."));
12425   if (strcmp (reply, "OK") != 0)
12426     error (_("Bogus reply from target: %s"), reply);
12427   return 0;
12428 }
12429
12430 /* This is basically a memory transfer, but needs to be its own packet
12431    because we don't know how the target actually organizes its trace
12432    memory, plus we want to be able to ask for as much as possible, but
12433    not be unhappy if we don't get as much as we ask for.  */
12434
12435 static LONGEST
12436 remote_get_raw_trace_data (struct target_ops *self,
12437                            gdb_byte *buf, ULONGEST offset, LONGEST len)
12438 {
12439   struct remote_state *rs = get_remote_state ();
12440   char *reply;
12441   char *p;
12442   int rslt;
12443
12444   p = rs->buf;
12445   strcpy (p, "qTBuffer:");
12446   p += strlen (p);
12447   p += hexnumstr (p, offset);
12448   *p++ = ',';
12449   p += hexnumstr (p, len);
12450   *p++ = '\0';
12451
12452   putpkt (rs->buf);
12453   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12454   if (reply && *reply)
12455     {
12456       /* 'l' by itself means we're at the end of the buffer and
12457          there is nothing more to get.  */
12458       if (*reply == 'l')
12459         return 0;
12460
12461       /* Convert the reply into binary.  Limit the number of bytes to
12462          convert according to our passed-in buffer size, rather than
12463          what was returned in the packet; if the target is
12464          unexpectedly generous and gives us a bigger reply than we
12465          asked for, we don't want to crash.  */
12466       rslt = hex2bin (target_buf, buf, len);
12467       return rslt;
12468     }
12469
12470   /* Something went wrong, flag as an error.  */
12471   return -1;
12472 }
12473
12474 static void
12475 remote_set_disconnected_tracing (struct target_ops *self, int val)
12476 {
12477   struct remote_state *rs = get_remote_state ();
12478
12479   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12480     {
12481       char *reply;
12482
12483       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12484       putpkt (rs->buf);
12485       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12486       if (*reply == '\0')
12487         error (_("Target does not support this command."));
12488       if (strcmp (reply, "OK") != 0)
12489         error (_("Bogus reply from target: %s"), reply);
12490     }
12491   else if (val)
12492     warning (_("Target does not support disconnected tracing."));
12493 }
12494
12495 static int
12496 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12497 {
12498   struct thread_info *info = find_thread_ptid (ptid);
12499
12500   if (info && info->priv)
12501     return info->priv->core;
12502   return -1;
12503 }
12504
12505 static void
12506 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12507 {
12508   struct remote_state *rs = get_remote_state ();
12509   char *reply;
12510
12511   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12512   putpkt (rs->buf);
12513   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12514   if (*reply == '\0')
12515     error (_("Target does not support this command."));
12516   if (strcmp (reply, "OK") != 0)
12517     error (_("Bogus reply from target: %s"), reply);
12518 }
12519
12520 static struct traceframe_info *
12521 remote_traceframe_info (struct target_ops *self)
12522 {
12523   char *text;
12524
12525   text = target_read_stralloc (&current_target,
12526                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12527   if (text != NULL)
12528     {
12529       struct traceframe_info *info;
12530       struct cleanup *back_to = make_cleanup (xfree, text);
12531
12532       info = parse_traceframe_info (text);
12533       do_cleanups (back_to);
12534       return info;
12535     }
12536
12537   return NULL;
12538 }
12539
12540 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
12541    instruction on which a fast tracepoint may be placed.  Returns -1
12542    if the packet is not supported, and 0 if the minimum instruction
12543    length is unknown.  */
12544
12545 static int
12546 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12547 {
12548   struct remote_state *rs = get_remote_state ();
12549   char *reply;
12550
12551   /* If we're not debugging a process yet, the IPA can't be
12552      loaded.  */
12553   if (!target_has_execution)
12554     return 0;
12555
12556   /* Make sure the remote is pointing at the right process.  */
12557   set_general_process ();
12558
12559   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12560   putpkt (rs->buf);
12561   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12562   if (*reply == '\0')
12563     return -1;
12564   else
12565     {
12566       ULONGEST min_insn_len;
12567
12568       unpack_varlen_hex (reply, &min_insn_len);
12569
12570       return (int) min_insn_len;
12571     }
12572 }
12573
12574 static void
12575 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12576 {
12577   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12578     {
12579       struct remote_state *rs = get_remote_state ();
12580       char *buf = rs->buf;
12581       char *endbuf = rs->buf + get_remote_packet_size ();
12582       enum packet_result result;
12583
12584       gdb_assert (val >= 0 || val == -1);
12585       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12586       /* Send -1 as literal "-1" to avoid host size dependency.  */
12587       if (val < 0)
12588         {
12589           *buf++ = '-';
12590           buf += hexnumstr (buf, (ULONGEST) -val);
12591         }
12592       else
12593         buf += hexnumstr (buf, (ULONGEST) val);
12594
12595       putpkt (rs->buf);
12596       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12597       result = packet_ok (rs->buf,
12598                   &remote_protocol_packets[PACKET_QTBuffer_size]);
12599
12600       if (result != PACKET_OK)
12601         warning (_("Bogus reply from target: %s"), rs->buf);
12602     }
12603 }
12604
12605 static int
12606 remote_set_trace_notes (struct target_ops *self,
12607                         const char *user, const char *notes,
12608                         const char *stop_notes)
12609 {
12610   struct remote_state *rs = get_remote_state ();
12611   char *reply;
12612   char *buf = rs->buf;
12613   char *endbuf = rs->buf + get_remote_packet_size ();
12614   int nbytes;
12615
12616   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12617   if (user)
12618     {
12619       buf += xsnprintf (buf, endbuf - buf, "user:");
12620       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12621       buf += 2 * nbytes;
12622       *buf++ = ';';
12623     }
12624   if (notes)
12625     {
12626       buf += xsnprintf (buf, endbuf - buf, "notes:");
12627       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12628       buf += 2 * nbytes;
12629       *buf++ = ';';
12630     }
12631   if (stop_notes)
12632     {
12633       buf += xsnprintf (buf, endbuf - buf, "tstop:");
12634       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12635       buf += 2 * nbytes;
12636       *buf++ = ';';
12637     }
12638   /* Ensure the buffer is terminated.  */
12639   *buf = '\0';
12640
12641   putpkt (rs->buf);
12642   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12643   if (*reply == '\0')
12644     return 0;
12645
12646   if (strcmp (reply, "OK") != 0)
12647     error (_("Bogus reply from target: %s"), reply);
12648
12649   return 1;
12650 }
12651
12652 static int
12653 remote_use_agent (struct target_ops *self, int use)
12654 {
12655   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12656     {
12657       struct remote_state *rs = get_remote_state ();
12658
12659       /* If the stub supports QAgent.  */
12660       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12661       putpkt (rs->buf);
12662       getpkt (&rs->buf, &rs->buf_size, 0);
12663
12664       if (strcmp (rs->buf, "OK") == 0)
12665         {
12666           use_agent = use;
12667           return 1;
12668         }
12669     }
12670
12671   return 0;
12672 }
12673
12674 static int
12675 remote_can_use_agent (struct target_ops *self)
12676 {
12677   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12678 }
12679
12680 struct btrace_target_info
12681 {
12682   /* The ptid of the traced thread.  */
12683   ptid_t ptid;
12684
12685   /* The obtained branch trace configuration.  */
12686   struct btrace_config conf;
12687 };
12688
12689 /* Reset our idea of our target's btrace configuration.  */
12690
12691 static void
12692 remote_btrace_reset (void)
12693 {
12694   struct remote_state *rs = get_remote_state ();
12695
12696   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12697 }
12698
12699 /* Check whether the target supports branch tracing.  */
12700
12701 static int
12702 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12703 {
12704   if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12705     return 0;
12706   if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12707     return 0;
12708
12709   switch (format)
12710     {
12711       case BTRACE_FORMAT_NONE:
12712         return 0;
12713
12714       case BTRACE_FORMAT_BTS:
12715         return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12716
12717       case BTRACE_FORMAT_PT:
12718         /* The trace is decoded on the host.  Even if our target supports it,
12719            we still need to have libipt to decode the trace.  */
12720 #if defined (HAVE_LIBIPT)
12721         return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12722 #else /* !defined (HAVE_LIBIPT)  */
12723         return 0;
12724 #endif /* !defined (HAVE_LIBIPT)  */
12725     }
12726
12727   internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12728 }
12729
12730 /* Synchronize the configuration with the target.  */
12731
12732 static void
12733 btrace_sync_conf (const struct btrace_config *conf)
12734 {
12735   struct packet_config *packet;
12736   struct remote_state *rs;
12737   char *buf, *pos, *endbuf;
12738
12739   rs = get_remote_state ();
12740   buf = rs->buf;
12741   endbuf = buf + get_remote_packet_size ();
12742
12743   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12744   if (packet_config_support (packet) == PACKET_ENABLE
12745       && conf->bts.size != rs->btrace_config.bts.size)
12746     {
12747       pos = buf;
12748       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12749                         conf->bts.size);
12750
12751       putpkt (buf);
12752       getpkt (&buf, &rs->buf_size, 0);
12753
12754       if (packet_ok (buf, packet) == PACKET_ERROR)
12755         {
12756           if (buf[0] == 'E' && buf[1] == '.')
12757             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12758           else
12759             error (_("Failed to configure the BTS buffer size."));
12760         }
12761
12762       rs->btrace_config.bts.size = conf->bts.size;
12763     }
12764
12765   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12766   if (packet_config_support (packet) == PACKET_ENABLE
12767       && conf->pt.size != rs->btrace_config.pt.size)
12768     {
12769       pos = buf;
12770       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12771                         conf->pt.size);
12772
12773       putpkt (buf);
12774       getpkt (&buf, &rs->buf_size, 0);
12775
12776       if (packet_ok (buf, packet) == PACKET_ERROR)
12777         {
12778           if (buf[0] == 'E' && buf[1] == '.')
12779             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12780           else
12781             error (_("Failed to configure the trace buffer size."));
12782         }
12783
12784       rs->btrace_config.pt.size = conf->pt.size;
12785     }
12786 }
12787
12788 /* Read the current thread's btrace configuration from the target and
12789    store it into CONF.  */
12790
12791 static void
12792 btrace_read_config (struct btrace_config *conf)
12793 {
12794   char *xml;
12795
12796   xml = target_read_stralloc (&current_target,
12797                               TARGET_OBJECT_BTRACE_CONF, "");
12798   if (xml != NULL)
12799     {
12800       struct cleanup *cleanup;
12801
12802       cleanup = make_cleanup (xfree, xml);
12803       parse_xml_btrace_conf (conf, xml);
12804       do_cleanups (cleanup);
12805     }
12806 }
12807
12808 /* Enable branch tracing.  */
12809
12810 static struct btrace_target_info *
12811 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12812                       const struct btrace_config *conf)
12813 {
12814   struct btrace_target_info *tinfo = NULL;
12815   struct packet_config *packet = NULL;
12816   struct remote_state *rs = get_remote_state ();
12817   char *buf = rs->buf;
12818   char *endbuf = rs->buf + get_remote_packet_size ();
12819
12820   switch (conf->format)
12821     {
12822       case BTRACE_FORMAT_BTS:
12823         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12824         break;
12825
12826       case BTRACE_FORMAT_PT:
12827         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12828         break;
12829     }
12830
12831   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12832     error (_("Target does not support branch tracing."));
12833
12834   btrace_sync_conf (conf);
12835
12836   set_general_thread (ptid);
12837
12838   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12839   putpkt (rs->buf);
12840   getpkt (&rs->buf, &rs->buf_size, 0);
12841
12842   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12843     {
12844       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12845         error (_("Could not enable branch tracing for %s: %s"),
12846                target_pid_to_str (ptid), rs->buf + 2);
12847       else
12848         error (_("Could not enable branch tracing for %s."),
12849                target_pid_to_str (ptid));
12850     }
12851
12852   tinfo = XCNEW (struct btrace_target_info);
12853   tinfo->ptid = ptid;
12854
12855   /* If we fail to read the configuration, we lose some information, but the
12856      tracing itself is not impacted.  */
12857   TRY
12858     {
12859       btrace_read_config (&tinfo->conf);
12860     }
12861   CATCH (err, RETURN_MASK_ERROR)
12862     {
12863       if (err.message != NULL)
12864         warning ("%s", err.message);
12865     }
12866   END_CATCH
12867
12868   return tinfo;
12869 }
12870
12871 /* Disable branch tracing.  */
12872
12873 static void
12874 remote_disable_btrace (struct target_ops *self,
12875                        struct btrace_target_info *tinfo)
12876 {
12877   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12878   struct remote_state *rs = get_remote_state ();
12879   char *buf = rs->buf;
12880   char *endbuf = rs->buf + get_remote_packet_size ();
12881
12882   if (packet_config_support (packet) != PACKET_ENABLE)
12883     error (_("Target does not support branch tracing."));
12884
12885   set_general_thread (tinfo->ptid);
12886
12887   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12888   putpkt (rs->buf);
12889   getpkt (&rs->buf, &rs->buf_size, 0);
12890
12891   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12892     {
12893       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12894         error (_("Could not disable branch tracing for %s: %s"),
12895                target_pid_to_str (tinfo->ptid), rs->buf + 2);
12896       else
12897         error (_("Could not disable branch tracing for %s."),
12898                target_pid_to_str (tinfo->ptid));
12899     }
12900
12901   xfree (tinfo);
12902 }
12903
12904 /* Teardown branch tracing.  */
12905
12906 static void
12907 remote_teardown_btrace (struct target_ops *self,
12908                         struct btrace_target_info *tinfo)
12909 {
12910   /* We must not talk to the target during teardown.  */
12911   xfree (tinfo);
12912 }
12913
12914 /* Read the branch trace.  */
12915
12916 static enum btrace_error
12917 remote_read_btrace (struct target_ops *self,
12918                     struct btrace_data *btrace,
12919                     struct btrace_target_info *tinfo,
12920                     enum btrace_read_type type)
12921 {
12922   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12923   struct remote_state *rs = get_remote_state ();
12924   struct cleanup *cleanup;
12925   const char *annex;
12926   char *xml;
12927
12928   if (packet_config_support (packet) != PACKET_ENABLE)
12929     error (_("Target does not support branch tracing."));
12930
12931 #if !defined(HAVE_LIBEXPAT)
12932   error (_("Cannot process branch tracing result. XML parsing not supported."));
12933 #endif
12934
12935   switch (type)
12936     {
12937     case BTRACE_READ_ALL:
12938       annex = "all";
12939       break;
12940     case BTRACE_READ_NEW:
12941       annex = "new";
12942       break;
12943     case BTRACE_READ_DELTA:
12944       annex = "delta";
12945       break;
12946     default:
12947       internal_error (__FILE__, __LINE__,
12948                       _("Bad branch tracing read type: %u."),
12949                       (unsigned int) type);
12950     }
12951
12952   xml = target_read_stralloc (&current_target,
12953                               TARGET_OBJECT_BTRACE, annex);
12954   if (xml == NULL)
12955     return BTRACE_ERR_UNKNOWN;
12956
12957   cleanup = make_cleanup (xfree, xml);
12958   parse_xml_btrace (btrace, xml);
12959   do_cleanups (cleanup);
12960
12961   return BTRACE_ERR_NONE;
12962 }
12963
12964 static const struct btrace_config *
12965 remote_btrace_conf (struct target_ops *self,
12966                     const struct btrace_target_info *tinfo)
12967 {
12968   return &tinfo->conf;
12969 }
12970
12971 static int
12972 remote_augmented_libraries_svr4_read (struct target_ops *self)
12973 {
12974   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12975           == PACKET_ENABLE);
12976 }
12977
12978 /* Implementation of to_load.  */
12979
12980 static void
12981 remote_load (struct target_ops *self, const char *name, int from_tty)
12982 {
12983   generic_load (name, from_tty);
12984 }
12985
12986 /* Accepts an integer PID; returns a string representing a file that
12987    can be opened on the remote side to get the symbols for the child
12988    process.  Returns NULL if the operation is not supported.  */
12989
12990 static char *
12991 remote_pid_to_exec_file (struct target_ops *self, int pid)
12992 {
12993   static char *filename = NULL;
12994   struct inferior *inf;
12995   char *annex = NULL;
12996
12997   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12998     return NULL;
12999
13000   if (filename != NULL)
13001     xfree (filename);
13002
13003   inf = find_inferior_pid (pid);
13004   if (inf == NULL)
13005     internal_error (__FILE__, __LINE__,
13006                     _("not currently attached to process %d"), pid);
13007
13008   if (!inf->fake_pid_p)
13009     {
13010       const int annex_size = 9;
13011
13012       annex = (char *) alloca (annex_size);
13013       xsnprintf (annex, annex_size, "%x", pid);
13014     }
13015
13016   filename = target_read_stralloc (&current_target,
13017                                    TARGET_OBJECT_EXEC_FILE, annex);
13018
13019   return filename;
13020 }
13021
13022 /* Implement the to_can_do_single_step target_ops method.  */
13023
13024 static int
13025 remote_can_do_single_step (struct target_ops *ops)
13026 {
13027   /* We can only tell whether target supports single step or not by
13028      supported s and S vCont actions if the stub supports vContSupported
13029      feature.  If the stub doesn't support vContSupported feature,
13030      we have conservatively to think target doesn't supports single
13031      step.  */
13032   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13033     {
13034       struct remote_state *rs = get_remote_state ();
13035
13036       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13037         remote_vcont_probe (rs);
13038
13039       return rs->supports_vCont.s && rs->supports_vCont.S;
13040     }
13041   else
13042     return 0;
13043 }
13044
13045 static void
13046 init_remote_ops (void)
13047 {
13048   remote_ops.to_shortname = "remote";
13049   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13050   remote_ops.to_doc =
13051     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13052 Specify the serial device it is connected to\n\
13053 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13054   remote_ops.to_open = remote_open;
13055   remote_ops.to_close = remote_close;
13056   remote_ops.to_detach = remote_detach;
13057   remote_ops.to_disconnect = remote_disconnect;
13058   remote_ops.to_resume = remote_resume;
13059   remote_ops.to_wait = remote_wait;
13060   remote_ops.to_fetch_registers = remote_fetch_registers;
13061   remote_ops.to_store_registers = remote_store_registers;
13062   remote_ops.to_prepare_to_store = remote_prepare_to_store;
13063   remote_ops.to_files_info = remote_files_info;
13064   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13065   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13066   remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13067   remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13068   remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13069   remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13070   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13071   remote_ops.to_stopped_data_address = remote_stopped_data_address;
13072   remote_ops.to_watchpoint_addr_within_range =
13073     remote_watchpoint_addr_within_range;
13074   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13075   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13076   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13077   remote_ops.to_region_ok_for_hw_watchpoint
13078      = remote_region_ok_for_hw_watchpoint;
13079   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13080   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13081   remote_ops.to_kill = remote_kill;
13082   remote_ops.to_load = remote_load;
13083   remote_ops.to_mourn_inferior = remote_mourn;
13084   remote_ops.to_pass_signals = remote_pass_signals;
13085   remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13086   remote_ops.to_program_signals = remote_program_signals;
13087   remote_ops.to_thread_alive = remote_thread_alive;
13088   remote_ops.to_thread_name = remote_thread_name;
13089   remote_ops.to_update_thread_list = remote_update_thread_list;
13090   remote_ops.to_pid_to_str = remote_pid_to_str;
13091   remote_ops.to_extra_thread_info = remote_threads_extra_info;
13092   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13093   remote_ops.to_stop = remote_stop;
13094   remote_ops.to_interrupt = remote_interrupt;
13095   remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
13096   remote_ops.to_xfer_partial = remote_xfer_partial;
13097   remote_ops.to_rcmd = remote_rcmd;
13098   remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13099   remote_ops.to_log_command = serial_log_command;
13100   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13101   remote_ops.to_stratum = process_stratum;
13102   remote_ops.to_has_all_memory = default_child_has_all_memory;
13103   remote_ops.to_has_memory = default_child_has_memory;
13104   remote_ops.to_has_stack = default_child_has_stack;
13105   remote_ops.to_has_registers = default_child_has_registers;
13106   remote_ops.to_has_execution = default_child_has_execution;
13107   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
13108   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13109   remote_ops.to_magic = OPS_MAGIC;
13110   remote_ops.to_memory_map = remote_memory_map;
13111   remote_ops.to_flash_erase = remote_flash_erase;
13112   remote_ops.to_flash_done = remote_flash_done;
13113   remote_ops.to_read_description = remote_read_description;
13114   remote_ops.to_search_memory = remote_search_memory;
13115   remote_ops.to_can_async_p = remote_can_async_p;
13116   remote_ops.to_is_async_p = remote_is_async_p;
13117   remote_ops.to_async = remote_async;
13118   remote_ops.to_thread_events = remote_thread_events;
13119   remote_ops.to_can_do_single_step = remote_can_do_single_step;
13120   remote_ops.to_terminal_inferior = remote_terminal_inferior;
13121   remote_ops.to_terminal_ours = remote_terminal_ours;
13122   remote_ops.to_supports_non_stop = remote_supports_non_stop;
13123   remote_ops.to_supports_multi_process = remote_supports_multi_process;
13124   remote_ops.to_supports_disable_randomization
13125     = remote_supports_disable_randomization;
13126   remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13127   remote_ops.to_fileio_open = remote_hostio_open;
13128   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13129   remote_ops.to_fileio_pread = remote_hostio_pread;
13130   remote_ops.to_fileio_fstat = remote_hostio_fstat;
13131   remote_ops.to_fileio_close = remote_hostio_close;
13132   remote_ops.to_fileio_unlink = remote_hostio_unlink;
13133   remote_ops.to_fileio_readlink = remote_hostio_readlink;
13134   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13135   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13136   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13137   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13138   remote_ops.to_trace_init = remote_trace_init;
13139   remote_ops.to_download_tracepoint = remote_download_tracepoint;
13140   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13141   remote_ops.to_download_trace_state_variable
13142     = remote_download_trace_state_variable;
13143   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13144   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13145   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13146   remote_ops.to_trace_start = remote_trace_start;
13147   remote_ops.to_get_trace_status = remote_get_trace_status;
13148   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13149   remote_ops.to_trace_stop = remote_trace_stop;
13150   remote_ops.to_trace_find = remote_trace_find;
13151   remote_ops.to_get_trace_state_variable_value
13152     = remote_get_trace_state_variable_value;
13153   remote_ops.to_save_trace_data = remote_save_trace_data;
13154   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13155   remote_ops.to_upload_trace_state_variables
13156     = remote_upload_trace_state_variables;
13157   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13158   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13159   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13160   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13161   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13162   remote_ops.to_set_trace_notes = remote_set_trace_notes;
13163   remote_ops.to_core_of_thread = remote_core_of_thread;
13164   remote_ops.to_verify_memory = remote_verify_memory;
13165   remote_ops.to_get_tib_address = remote_get_tib_address;
13166   remote_ops.to_set_permissions = remote_set_permissions;
13167   remote_ops.to_static_tracepoint_marker_at
13168     = remote_static_tracepoint_marker_at;
13169   remote_ops.to_static_tracepoint_markers_by_strid
13170     = remote_static_tracepoint_markers_by_strid;
13171   remote_ops.to_traceframe_info = remote_traceframe_info;
13172   remote_ops.to_use_agent = remote_use_agent;
13173   remote_ops.to_can_use_agent = remote_can_use_agent;
13174   remote_ops.to_supports_btrace = remote_supports_btrace;
13175   remote_ops.to_enable_btrace = remote_enable_btrace;
13176   remote_ops.to_disable_btrace = remote_disable_btrace;
13177   remote_ops.to_teardown_btrace = remote_teardown_btrace;
13178   remote_ops.to_read_btrace = remote_read_btrace;
13179   remote_ops.to_btrace_conf = remote_btrace_conf;
13180   remote_ops.to_augmented_libraries_svr4_read =
13181     remote_augmented_libraries_svr4_read;
13182   remote_ops.to_follow_fork = remote_follow_fork;
13183   remote_ops.to_follow_exec = remote_follow_exec;
13184   remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13185   remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13186   remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13187   remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13188   remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13189   remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13190 }
13191
13192 /* Set up the extended remote vector by making a copy of the standard
13193    remote vector and adding to it.  */
13194
13195 static void
13196 init_extended_remote_ops (void)
13197 {
13198   extended_remote_ops = remote_ops;
13199
13200   extended_remote_ops.to_shortname = "extended-remote";
13201   extended_remote_ops.to_longname =
13202     "Extended remote serial target in gdb-specific protocol";
13203   extended_remote_ops.to_doc =
13204     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13205 Specify the serial device it is connected to (e.g. /dev/ttya).";
13206   extended_remote_ops.to_open = extended_remote_open;
13207   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13208   extended_remote_ops.to_detach = extended_remote_detach;
13209   extended_remote_ops.to_attach = extended_remote_attach;
13210   extended_remote_ops.to_post_attach = extended_remote_post_attach;
13211   extended_remote_ops.to_supports_disable_randomization
13212     = extended_remote_supports_disable_randomization;
13213 }
13214
13215 static int
13216 remote_can_async_p (struct target_ops *ops)
13217 {
13218   struct remote_state *rs = get_remote_state ();
13219
13220   if (!target_async_permitted)
13221     /* We only enable async when the user specifically asks for it.  */
13222     return 0;
13223
13224   /* We're async whenever the serial device is.  */
13225   return serial_can_async_p (rs->remote_desc);
13226 }
13227
13228 static int
13229 remote_is_async_p (struct target_ops *ops)
13230 {
13231   struct remote_state *rs = get_remote_state ();
13232
13233   if (!target_async_permitted)
13234     /* We only enable async when the user specifically asks for it.  */
13235     return 0;
13236
13237   /* We're async whenever the serial device is.  */
13238   return serial_is_async_p (rs->remote_desc);
13239 }
13240
13241 /* Pass the SERIAL event on and up to the client.  One day this code
13242    will be able to delay notifying the client of an event until the
13243    point where an entire packet has been received.  */
13244
13245 static serial_event_ftype remote_async_serial_handler;
13246
13247 static void
13248 remote_async_serial_handler (struct serial *scb, void *context)
13249 {
13250   struct remote_state *rs = (struct remote_state *) context;
13251
13252   /* Don't propogate error information up to the client.  Instead let
13253      the client find out about the error by querying the target.  */
13254   inferior_event_handler (INF_REG_EVENT, NULL);
13255 }
13256
13257 static void
13258 remote_async_inferior_event_handler (gdb_client_data data)
13259 {
13260   inferior_event_handler (INF_REG_EVENT, NULL);
13261 }
13262
13263 static void
13264 remote_async (struct target_ops *ops, int enable)
13265 {
13266   struct remote_state *rs = get_remote_state ();
13267
13268   if (enable)
13269     {
13270       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13271
13272       /* If there are pending events in the stop reply queue tell the
13273          event loop to process them.  */
13274       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13275         mark_async_event_handler (remote_async_inferior_event_token);
13276       /* For simplicity, below we clear the pending events token
13277          without remembering whether it is marked, so here we always
13278          mark it.  If there's actually no pending notification to
13279          process, this ends up being a no-op (other than a spurious
13280          event-loop wakeup).  */
13281       if (target_is_non_stop_p ())
13282         mark_async_event_handler (rs->notif_state->get_pending_events_token);
13283     }
13284   else
13285     {
13286       serial_async (rs->remote_desc, NULL, NULL);
13287       /* If the core is disabling async, it doesn't want to be
13288          disturbed with target events.  Clear all async event sources
13289          too.  */
13290       clear_async_event_handler (remote_async_inferior_event_token);
13291       if (target_is_non_stop_p ())
13292         clear_async_event_handler (rs->notif_state->get_pending_events_token);
13293     }
13294 }
13295
13296 /* Implementation of the to_thread_events method.  */
13297
13298 static void
13299 remote_thread_events (struct target_ops *ops, int enable)
13300 {
13301   struct remote_state *rs = get_remote_state ();
13302   size_t size = get_remote_packet_size ();
13303   char *p = rs->buf;
13304
13305   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13306     return;
13307
13308   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13309   putpkt (rs->buf);
13310   getpkt (&rs->buf, &rs->buf_size, 0);
13311
13312   switch (packet_ok (rs->buf,
13313                      &remote_protocol_packets[PACKET_QThreadEvents]))
13314     {
13315     case PACKET_OK:
13316       if (strcmp (rs->buf, "OK") != 0)
13317         error (_("Remote refused setting thread events: %s"), rs->buf);
13318       break;
13319     case PACKET_ERROR:
13320       warning (_("Remote failure reply: %s"), rs->buf);
13321       break;
13322     case PACKET_UNKNOWN:
13323       break;
13324     }
13325 }
13326
13327 static void
13328 set_remote_cmd (char *args, int from_tty)
13329 {
13330   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13331 }
13332
13333 static void
13334 show_remote_cmd (char *args, int from_tty)
13335 {
13336   /* We can't just use cmd_show_list here, because we want to skip
13337      the redundant "show remote Z-packet" and the legacy aliases.  */
13338   struct cleanup *showlist_chain;
13339   struct cmd_list_element *list = remote_show_cmdlist;
13340   struct ui_out *uiout = current_uiout;
13341
13342   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13343   for (; list != NULL; list = list->next)
13344     if (strcmp (list->name, "Z-packet") == 0)
13345       continue;
13346     else if (list->type == not_set_cmd)
13347       /* Alias commands are exactly like the original, except they
13348          don't have the normal type.  */
13349       continue;
13350     else
13351       {
13352         struct cleanup *option_chain
13353           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13354
13355         ui_out_field_string (uiout, "name", list->name);
13356         ui_out_text (uiout, ":  ");
13357         if (list->type == show_cmd)
13358           do_show_command ((char *) NULL, from_tty, list);
13359         else
13360           cmd_func (list, NULL, from_tty);
13361         /* Close the tuple.  */
13362         do_cleanups (option_chain);
13363       }
13364
13365   /* Close the tuple.  */
13366   do_cleanups (showlist_chain);
13367 }
13368
13369
13370 /* Function to be called whenever a new objfile (shlib) is detected.  */
13371 static void
13372 remote_new_objfile (struct objfile *objfile)
13373 {
13374   struct remote_state *rs = get_remote_state ();
13375
13376   if (rs->remote_desc != 0)             /* Have a remote connection.  */
13377     remote_check_symbols ();
13378 }
13379
13380 /* Pull all the tracepoints defined on the target and create local
13381    data structures representing them.  We don't want to create real
13382    tracepoints yet, we don't want to mess up the user's existing
13383    collection.  */
13384   
13385 static int
13386 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13387 {
13388   struct remote_state *rs = get_remote_state ();
13389   char *p;
13390
13391   /* Ask for a first packet of tracepoint definition.  */
13392   putpkt ("qTfP");
13393   getpkt (&rs->buf, &rs->buf_size, 0);
13394   p = rs->buf;
13395   while (*p && *p != 'l')
13396     {
13397       parse_tracepoint_definition (p, utpp);
13398       /* Ask for another packet of tracepoint definition.  */
13399       putpkt ("qTsP");
13400       getpkt (&rs->buf, &rs->buf_size, 0);
13401       p = rs->buf;
13402     }
13403   return 0;
13404 }
13405
13406 static int
13407 remote_upload_trace_state_variables (struct target_ops *self,
13408                                      struct uploaded_tsv **utsvp)
13409 {
13410   struct remote_state *rs = get_remote_state ();
13411   char *p;
13412
13413   /* Ask for a first packet of variable definition.  */
13414   putpkt ("qTfV");
13415   getpkt (&rs->buf, &rs->buf_size, 0);
13416   p = rs->buf;
13417   while (*p && *p != 'l')
13418     {
13419       parse_tsv_definition (p, utsvp);
13420       /* Ask for another packet of variable definition.  */
13421       putpkt ("qTsV");
13422       getpkt (&rs->buf, &rs->buf_size, 0);
13423       p = rs->buf;
13424     }
13425   return 0;
13426 }
13427
13428 /* The "set/show range-stepping" show hook.  */
13429
13430 static void
13431 show_range_stepping (struct ui_file *file, int from_tty,
13432                      struct cmd_list_element *c,
13433                      const char *value)
13434 {
13435   fprintf_filtered (file,
13436                     _("Debugger's willingness to use range stepping "
13437                       "is %s.\n"), value);
13438 }
13439
13440 /* The "set/show range-stepping" set hook.  */
13441
13442 static void
13443 set_range_stepping (char *ignore_args, int from_tty,
13444                     struct cmd_list_element *c)
13445 {
13446   struct remote_state *rs = get_remote_state ();
13447
13448   /* Whene enabling, check whether range stepping is actually
13449      supported by the target, and warn if not.  */
13450   if (use_range_stepping)
13451     {
13452       if (rs->remote_desc != NULL)
13453         {
13454           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13455             remote_vcont_probe (rs);
13456
13457           if (packet_support (PACKET_vCont) == PACKET_ENABLE
13458               && rs->supports_vCont.r)
13459             return;
13460         }
13461
13462       warning (_("Range stepping is not supported by the current target"));
13463     }
13464 }
13465
13466 void
13467 _initialize_remote (void)
13468 {
13469   struct remote_state *rs;
13470   struct cmd_list_element *cmd;
13471   const char *cmd_name;
13472
13473   /* architecture specific data */
13474   remote_gdbarch_data_handle =
13475     gdbarch_data_register_post_init (init_remote_state);
13476   remote_g_packet_data_handle =
13477     gdbarch_data_register_pre_init (remote_g_packet_data_init);
13478
13479   remote_pspace_data
13480     = register_program_space_data_with_cleanup (NULL,
13481                                                 remote_pspace_data_cleanup);
13482
13483   /* Initialize the per-target state.  At the moment there is only one
13484      of these, not one per target.  Only one target is active at a
13485      time.  */
13486   remote_state = new_remote_state ();
13487
13488   init_remote_ops ();
13489   add_target (&remote_ops);
13490
13491   init_extended_remote_ops ();
13492   add_target (&extended_remote_ops);
13493
13494   /* Hook into new objfile notification.  */
13495   observer_attach_new_objfile (remote_new_objfile);
13496   /* We're no longer interested in notification events of an inferior
13497      when it exits.  */
13498   observer_attach_inferior_exit (discard_pending_stop_replies);
13499
13500   /* Set up signal handlers.  */
13501   async_sigint_remote_token =
13502     create_async_signal_handler (async_remote_interrupt, NULL);
13503   async_sigint_remote_twice_token =
13504     create_async_signal_handler (async_remote_interrupt_twice, NULL);
13505
13506 #if 0
13507   init_remote_threadtests ();
13508 #endif
13509
13510   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13511   /* set/show remote ...  */
13512
13513   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13514 Remote protocol specific variables\n\
13515 Configure various remote-protocol specific variables such as\n\
13516 the packets being used"),
13517                   &remote_set_cmdlist, "set remote ",
13518                   0 /* allow-unknown */, &setlist);
13519   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13520 Remote protocol specific variables\n\
13521 Configure various remote-protocol specific variables such as\n\
13522 the packets being used"),
13523                   &remote_show_cmdlist, "show remote ",
13524                   0 /* allow-unknown */, &showlist);
13525
13526   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13527 Compare section data on target to the exec file.\n\
13528 Argument is a single section name (default: all loaded sections).\n\
13529 To compare only read-only loaded sections, specify the -r option."),
13530            &cmdlist);
13531
13532   add_cmd ("packet", class_maintenance, packet_command, _("\
13533 Send an arbitrary packet to a remote target.\n\
13534    maintenance packet TEXT\n\
13535 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13536 this command sends the string TEXT to the inferior, and displays the\n\
13537 response packet.  GDB supplies the initial `$' character, and the\n\
13538 terminating `#' character and checksum."),
13539            &maintenancelist);
13540
13541   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13542 Set whether to send break if interrupted."), _("\
13543 Show whether to send break if interrupted."), _("\
13544 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13545                            set_remotebreak, show_remotebreak,
13546                            &setlist, &showlist);
13547   cmd_name = "remotebreak";
13548   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13549   deprecate_cmd (cmd, "set remote interrupt-sequence");
13550   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13551   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13552   deprecate_cmd (cmd, "show remote interrupt-sequence");
13553
13554   add_setshow_enum_cmd ("interrupt-sequence", class_support,
13555                         interrupt_sequence_modes, &interrupt_sequence_mode,
13556                         _("\
13557 Set interrupt sequence to remote target."), _("\
13558 Show interrupt sequence to remote target."), _("\
13559 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13560                         NULL, show_interrupt_sequence,
13561                         &remote_set_cmdlist,
13562                         &remote_show_cmdlist);
13563
13564   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13565                            &interrupt_on_connect, _("\
13566 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
13567 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
13568 If set, interrupt sequence is sent to remote target."),
13569                            NULL, NULL,
13570                            &remote_set_cmdlist, &remote_show_cmdlist);
13571
13572   /* Install commands for configuring memory read/write packets.  */
13573
13574   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13575 Set the maximum number of bytes per memory write packet (deprecated)."),
13576            &setlist);
13577   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13578 Show the maximum number of bytes per memory write packet (deprecated)."),
13579            &showlist);
13580   add_cmd ("memory-write-packet-size", no_class,
13581            set_memory_write_packet_size, _("\
13582 Set the maximum number of bytes per memory-write packet.\n\
13583 Specify the number of bytes in a packet or 0 (zero) for the\n\
13584 default packet size.  The actual limit is further reduced\n\
13585 dependent on the target.  Specify ``fixed'' to disable the\n\
13586 further restriction and ``limit'' to enable that restriction."),
13587            &remote_set_cmdlist);
13588   add_cmd ("memory-read-packet-size", no_class,
13589            set_memory_read_packet_size, _("\
13590 Set the maximum number of bytes per memory-read packet.\n\
13591 Specify the number of bytes in a packet or 0 (zero) for the\n\
13592 default packet size.  The actual limit is further reduced\n\
13593 dependent on the target.  Specify ``fixed'' to disable the\n\
13594 further restriction and ``limit'' to enable that restriction."),
13595            &remote_set_cmdlist);
13596   add_cmd ("memory-write-packet-size", no_class,
13597            show_memory_write_packet_size,
13598            _("Show the maximum number of bytes per memory-write packet."),
13599            &remote_show_cmdlist);
13600   add_cmd ("memory-read-packet-size", no_class,
13601            show_memory_read_packet_size,
13602            _("Show the maximum number of bytes per memory-read packet."),
13603            &remote_show_cmdlist);
13604
13605   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13606                             &remote_hw_watchpoint_limit, _("\
13607 Set the maximum number of target hardware watchpoints."), _("\
13608 Show the maximum number of target hardware watchpoints."), _("\
13609 Specify a negative limit for unlimited."),
13610                             NULL, NULL, /* FIXME: i18n: The maximum
13611                                            number of target hardware
13612                                            watchpoints is %s.  */
13613                             &remote_set_cmdlist, &remote_show_cmdlist);
13614   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13615                             &remote_hw_watchpoint_length_limit, _("\
13616 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13617 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13618 Specify a negative limit for unlimited."),
13619                             NULL, NULL, /* FIXME: i18n: The maximum
13620                                            length (in bytes) of a target
13621                                            hardware watchpoint is %s.  */
13622                             &remote_set_cmdlist, &remote_show_cmdlist);
13623   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13624                             &remote_hw_breakpoint_limit, _("\
13625 Set the maximum number of target hardware breakpoints."), _("\
13626 Show the maximum number of target hardware breakpoints."), _("\
13627 Specify a negative limit for unlimited."),
13628                             NULL, NULL, /* FIXME: i18n: The maximum
13629                                            number of target hardware
13630                                            breakpoints is %s.  */
13631                             &remote_set_cmdlist, &remote_show_cmdlist);
13632
13633   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13634                              &remote_address_size, _("\
13635 Set the maximum size of the address (in bits) in a memory packet."), _("\
13636 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13637                              NULL,
13638                              NULL, /* FIXME: i18n: */
13639                              &setlist, &showlist);
13640
13641   init_all_packet_configs ();
13642
13643   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13644                          "X", "binary-download", 1);
13645
13646   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13647                          "vCont", "verbose-resume", 0);
13648
13649   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13650                          "QPassSignals", "pass-signals", 0);
13651
13652   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13653                          "QCatchSyscalls", "catch-syscalls", 0);
13654
13655   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13656                          "QProgramSignals", "program-signals", 0);
13657
13658   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13659                          "qSymbol", "symbol-lookup", 0);
13660
13661   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13662                          "P", "set-register", 1);
13663
13664   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13665                          "p", "fetch-register", 1);
13666
13667   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13668                          "Z0", "software-breakpoint", 0);
13669
13670   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13671                          "Z1", "hardware-breakpoint", 0);
13672
13673   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13674                          "Z2", "write-watchpoint", 0);
13675
13676   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13677                          "Z3", "read-watchpoint", 0);
13678
13679   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13680                          "Z4", "access-watchpoint", 0);
13681
13682   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13683                          "qXfer:auxv:read", "read-aux-vector", 0);
13684
13685   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13686                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
13687
13688   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13689                          "qXfer:features:read", "target-features", 0);
13690
13691   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13692                          "qXfer:libraries:read", "library-info", 0);
13693
13694   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13695                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13696
13697   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13698                          "qXfer:memory-map:read", "memory-map", 0);
13699
13700   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13701                          "qXfer:spu:read", "read-spu-object", 0);
13702
13703   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13704                          "qXfer:spu:write", "write-spu-object", 0);
13705
13706   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13707                         "qXfer:osdata:read", "osdata", 0);
13708
13709   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13710                          "qXfer:threads:read", "threads", 0);
13711
13712   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13713                          "qXfer:siginfo:read", "read-siginfo-object", 0);
13714
13715   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13716                          "qXfer:siginfo:write", "write-siginfo-object", 0);
13717
13718   add_packet_config_cmd
13719     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13720      "qXfer:traceframe-info:read", "traceframe-info", 0);
13721
13722   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13723                          "qXfer:uib:read", "unwind-info-block", 0);
13724
13725   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13726                          "qGetTLSAddr", "get-thread-local-storage-address",
13727                          0);
13728
13729   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13730                          "qGetTIBAddr", "get-thread-information-block-address",
13731                          0);
13732
13733   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13734                          "bc", "reverse-continue", 0);
13735
13736   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13737                          "bs", "reverse-step", 0);
13738
13739   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13740                          "qSupported", "supported-packets", 0);
13741
13742   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13743                          "qSearch:memory", "search-memory", 0);
13744
13745   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13746                          "qTStatus", "trace-status", 0);
13747
13748   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13749                          "vFile:setfs", "hostio-setfs", 0);
13750
13751   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13752                          "vFile:open", "hostio-open", 0);
13753
13754   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13755                          "vFile:pread", "hostio-pread", 0);
13756
13757   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13758                          "vFile:pwrite", "hostio-pwrite", 0);
13759
13760   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13761                          "vFile:close", "hostio-close", 0);
13762
13763   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13764                          "vFile:unlink", "hostio-unlink", 0);
13765
13766   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13767                          "vFile:readlink", "hostio-readlink", 0);
13768
13769   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13770                          "vFile:fstat", "hostio-fstat", 0);
13771
13772   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13773                          "vAttach", "attach", 0);
13774
13775   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13776                          "vRun", "run", 0);
13777
13778   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13779                          "QStartNoAckMode", "noack", 0);
13780
13781   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13782                          "vKill", "kill", 0);
13783
13784   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13785                          "qAttached", "query-attached", 0);
13786
13787   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13788                          "ConditionalTracepoints",
13789                          "conditional-tracepoints", 0);
13790
13791   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13792                          "ConditionalBreakpoints",
13793                          "conditional-breakpoints", 0);
13794
13795   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13796                          "BreakpointCommands",
13797                          "breakpoint-commands", 0);
13798
13799   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13800                          "FastTracepoints", "fast-tracepoints", 0);
13801
13802   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13803                          "TracepointSource", "TracepointSource", 0);
13804
13805   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13806                          "QAllow", "allow", 0);
13807
13808   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13809                          "StaticTracepoints", "static-tracepoints", 0);
13810
13811   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13812                          "InstallInTrace", "install-in-trace", 0);
13813
13814   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13815                          "qXfer:statictrace:read", "read-sdata-object", 0);
13816
13817   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13818                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13819
13820   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13821                          "QDisableRandomization", "disable-randomization", 0);
13822
13823   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13824                          "QAgent", "agent", 0);
13825
13826   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13827                          "QTBuffer:size", "trace-buffer-size", 0);
13828
13829   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13830        "Qbtrace:off", "disable-btrace", 0);
13831
13832   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13833        "Qbtrace:bts", "enable-btrace-bts", 0);
13834
13835   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13836        "Qbtrace:pt", "enable-btrace-pt", 0);
13837
13838   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13839        "qXfer:btrace", "read-btrace", 0);
13840
13841   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13842        "qXfer:btrace-conf", "read-btrace-conf", 0);
13843
13844   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13845        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13846
13847   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13848        "multiprocess-feature", "multiprocess-feature", 0);
13849
13850   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13851                          "swbreak-feature", "swbreak-feature", 0);
13852
13853   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13854                          "hwbreak-feature", "hwbreak-feature", 0);
13855
13856   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13857                          "fork-event-feature", "fork-event-feature", 0);
13858
13859   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13860                          "vfork-event-feature", "vfork-event-feature", 0);
13861
13862   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13863        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13864
13865   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13866                          "vContSupported", "verbose-resume-supported", 0);
13867
13868   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13869                          "exec-event-feature", "exec-event-feature", 0);
13870
13871   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13872                          "vCtrlC", "ctrl-c", 0);
13873
13874   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13875                          "QThreadEvents", "thread-events", 0);
13876
13877   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13878                          "N stop reply", "no-resumed-stop-reply", 0);
13879
13880   /* Assert that we've registered "set remote foo-packet" commands
13881      for all packet configs.  */
13882   {
13883     int i;
13884
13885     for (i = 0; i < PACKET_MAX; i++)
13886       {
13887         /* Ideally all configs would have a command associated.  Some
13888            still don't though.  */
13889         int excepted;
13890
13891         switch (i)
13892           {
13893           case PACKET_QNonStop:
13894           case PACKET_EnableDisableTracepoints_feature:
13895           case PACKET_tracenz_feature:
13896           case PACKET_DisconnectedTracing_feature:
13897           case PACKET_augmented_libraries_svr4_read_feature:
13898           case PACKET_qCRC:
13899             /* Additions to this list need to be well justified:
13900                pre-existing packets are OK; new packets are not.  */
13901             excepted = 1;
13902             break;
13903           default:
13904             excepted = 0;
13905             break;
13906           }
13907
13908         /* This catches both forgetting to add a config command, and
13909            forgetting to remove a packet from the exception list.  */
13910         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13911       }
13912   }
13913
13914   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
13915      Z sub-packet has its own set and show commands, but users may
13916      have sets to this variable in their .gdbinit files (or in their
13917      documentation).  */
13918   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13919                                 &remote_Z_packet_detect, _("\
13920 Set use of remote protocol `Z' packets"), _("\
13921 Show use of remote protocol `Z' packets "), _("\
13922 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13923 packets."),
13924                                 set_remote_protocol_Z_packet_cmd,
13925                                 show_remote_protocol_Z_packet_cmd,
13926                                 /* FIXME: i18n: Use of remote protocol
13927                                    `Z' packets is %s.  */
13928                                 &remote_set_cmdlist, &remote_show_cmdlist);
13929
13930   add_prefix_cmd ("remote", class_files, remote_command, _("\
13931 Manipulate files on the remote system\n\
13932 Transfer files to and from the remote target system."),
13933                   &remote_cmdlist, "remote ",
13934                   0 /* allow-unknown */, &cmdlist);
13935
13936   add_cmd ("put", class_files, remote_put_command,
13937            _("Copy a local file to the remote system."),
13938            &remote_cmdlist);
13939
13940   add_cmd ("get", class_files, remote_get_command,
13941            _("Copy a remote file to the local system."),
13942            &remote_cmdlist);
13943
13944   add_cmd ("delete", class_files, remote_delete_command,
13945            _("Delete a remote file."),
13946            &remote_cmdlist);
13947
13948   add_setshow_string_noescape_cmd ("exec-file", class_files,
13949                                    &remote_exec_file_var, _("\
13950 Set the remote pathname for \"run\""), _("\
13951 Show the remote pathname for \"run\""), NULL,
13952                                    set_remote_exec_file,
13953                                    show_remote_exec_file,
13954                                    &remote_set_cmdlist,
13955                                    &remote_show_cmdlist);
13956
13957   add_setshow_boolean_cmd ("range-stepping", class_run,
13958                            &use_range_stepping, _("\
13959 Enable or disable range stepping."), _("\
13960 Show whether target-assisted range stepping is enabled."), _("\
13961 If on, and the target supports it, when stepping a source line, GDB\n\
13962 tells the target to step the corresponding range of addresses itself instead\n\
13963 of issuing multiple single-steps.  This speeds up source level\n\
13964 stepping.  If off, GDB always issues single-steps, even if range\n\
13965 stepping is supported by the target.  The default is on."),
13966                            set_range_stepping,
13967                            show_range_stepping,
13968                            &setlist,
13969                            &showlist);
13970
13971   /* Eventually initialize fileio.  See fileio.c */
13972   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13973
13974   /* Take advantage of the fact that the TID field is not used, to tag
13975      special ptids with it set to != 0.  */
13976   magic_null_ptid = ptid_build (42000, -1, 1);
13977   not_sent_ptid = ptid_build (42000, -2, 1);
13978   any_thread_ptid = ptid_build (42000, 0, 1);
13979
13980   target_buf_size = 2048;
13981   target_buf = (char *) xmalloc (target_buf_size);
13982 }
13983