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