Make input_fd be per UI
[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 int getpkt_sane (char **buf, long *sizeof_buf, int forever);
101 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
102                                  int forever, int *is_notif);
103
104 static void remote_files_info (struct target_ops *ignore);
105
106 static void remote_prepare_to_store (struct target_ops *self,
107                                      struct regcache *regcache);
108
109 static void remote_open_1 (const char *, int, struct target_ops *,
110                            int extended_p);
111
112 static void remote_close (struct target_ops *self);
113
114 struct remote_state;
115
116 static int remote_vkill (int pid, struct remote_state *rs);
117
118 static void remote_kill_k (void);
119
120 static void remote_mourn (struct target_ops *ops);
121
122 static void extended_remote_restart (void);
123
124 static void remote_send (char **buf, long *sizeof_buf_p);
125
126 static int readchar (int timeout);
127
128 static void remote_serial_write (const char *str, int len);
129
130 static void remote_kill (struct target_ops *ops);
131
132 static int remote_can_async_p (struct target_ops *);
133
134 static int remote_is_async_p (struct target_ops *);
135
136 static void remote_async (struct target_ops *ops, int enable);
137
138 static void remote_thread_events (struct target_ops *ops, int enable);
139
140 static void interrupt_query (void);
141
142 static void set_general_thread (struct ptid ptid);
143 static void set_continue_thread (struct ptid ptid);
144
145 static void get_offsets (void);
146
147 static void skip_frame (void);
148
149 static long read_frame (char **buf_p, long *sizeof_buf);
150
151 static int hexnumlen (ULONGEST num);
152
153 static void init_remote_ops (void);
154
155 static void init_extended_remote_ops (void);
156
157 static void remote_stop (struct target_ops *self, ptid_t);
158
159 static int stubhex (int ch);
160
161 static int hexnumstr (char *, ULONGEST);
162
163 static int hexnumnstr (char *, ULONGEST, int);
164
165 static CORE_ADDR remote_address_masked (CORE_ADDR);
166
167 static void print_packet (const char *);
168
169 static void compare_sections_command (char *, int);
170
171 static void packet_command (char *, int);
172
173 static int stub_unpack_int (char *buff, int fieldlength);
174
175 static ptid_t remote_current_thread (ptid_t oldptid);
176
177 static int putpkt_binary (const char *buf, int cnt);
178
179 static void check_binary_download (CORE_ADDR addr);
180
181 struct packet_config;
182
183 static void show_packet_config_cmd (struct packet_config *config);
184
185 static void show_remote_protocol_packet_cmd (struct ui_file *file,
186                                              int from_tty,
187                                              struct cmd_list_element *c,
188                                              const char *value);
189
190 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
191 static ptid_t read_ptid (char *buf, char **obuf);
192
193 static void remote_set_permissions (struct target_ops *self);
194
195 static int remote_get_trace_status (struct target_ops *self,
196                                     struct trace_status *ts);
197
198 static int remote_upload_tracepoints (struct target_ops *self,
199                                       struct uploaded_tp **utpp);
200
201 static int remote_upload_trace_state_variables (struct target_ops *self,
202                                                 struct uploaded_tsv **utsvp);
203   
204 static void remote_query_supported (void);
205
206 static void remote_check_symbols (void);
207
208 void _initialize_remote (void);
209
210 struct stop_reply;
211 static void stop_reply_xfree (struct stop_reply *);
212 static void remote_parse_stop_reply (char *, struct stop_reply *);
213 static void push_stop_reply (struct stop_reply *);
214 static void discard_pending_stop_replies_in_queue (struct remote_state *);
215 static int peek_stop_reply (ptid_t ptid);
216
217 struct threads_listing_context;
218 static void remove_new_fork_children (struct threads_listing_context *);
219
220 static void remote_async_inferior_event_handler (gdb_client_data);
221
222 static void remote_terminal_ours (struct target_ops *self);
223
224 static int remote_read_description_p (struct target_ops *target);
225
226 static void remote_console_output (char *msg);
227
228 static int remote_supports_cond_breakpoints (struct target_ops *self);
229
230 static int remote_can_run_breakpoint_commands (struct target_ops *self);
231
232 static void remote_btrace_reset (void);
233
234 static int stop_reply_queue_length (void);
235
236 static void readahead_cache_invalidate (void);
237
238 static void remote_unpush_and_throw (void);
239
240 /* For "remote".  */
241
242 static struct cmd_list_element *remote_cmdlist;
243
244 /* For "set remote" and "show remote".  */
245
246 static struct cmd_list_element *remote_set_cmdlist;
247 static struct cmd_list_element *remote_show_cmdlist;
248
249 /* Stub vCont actions support.
250
251    Each field is a boolean flag indicating whether the stub reports
252    support for the corresponding action.  */
253
254 struct vCont_action_support
255 {
256   /* vCont;t */
257   int t;
258
259   /* vCont;r */
260   int r;
261
262   /* vCont;s */
263   int s;
264
265   /* vCont;S */
266   int S;
267 };
268
269 /* Controls whether GDB is willing to use range stepping.  */
270
271 static int use_range_stepping = 1;
272
273 #define OPAQUETHREADBYTES 8
274
275 /* a 64 bit opaque identifier */
276 typedef unsigned char threadref[OPAQUETHREADBYTES];
277
278 /* About this many threadisds fit in a packet.  */
279
280 #define MAXTHREADLISTRESULTS 32
281
282 /* Data for the vFile:pread readahead cache.  */
283
284 struct readahead_cache
285 {
286   /* The file descriptor for the file that is being cached.  -1 if the
287      cache is invalid.  */
288   int fd;
289
290   /* The offset into the file that the cache buffer corresponds
291      to.  */
292   ULONGEST offset;
293
294   /* The buffer holding the cache contents.  */
295   gdb_byte *buf;
296   /* The buffer's size.  We try to read as much as fits into a packet
297      at a time.  */
298   size_t bufsize;
299
300   /* Cache hit and miss counters.  */
301   ULONGEST hit_count;
302   ULONGEST miss_count;
303 };
304
305 /* Description of the remote protocol state for the currently
306    connected target.  This is per-target state, and independent of the
307    selected architecture.  */
308
309 struct remote_state
310 {
311   /* A buffer to use for incoming packets, and its current size.  The
312      buffer is grown dynamically for larger incoming packets.
313      Outgoing packets may also be constructed in this buffer.
314      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
315      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
316      packets.  */
317   char *buf;
318   long buf_size;
319
320   /* True if we're going through initial connection setup (finding out
321      about the remote side's threads, relocating symbols, etc.).  */
322   int starting_up;
323
324   /* If we negotiated packet size explicitly (and thus can bypass
325      heuristics for the largest packet size that will not overflow
326      a buffer in the stub), this will be set to that packet size.
327      Otherwise zero, meaning to use the guessed size.  */
328   long explicit_packet_size;
329
330   /* remote_wait is normally called when the target is running and
331      waits for a stop reply packet.  But sometimes we need to call it
332      when the target is already stopped.  We can send a "?" packet
333      and have remote_wait read the response.  Or, if we already have
334      the response, we can stash it in BUF and tell remote_wait to
335      skip calling getpkt.  This flag is set when BUF contains a
336      stop reply packet and the target is not waiting.  */
337   int cached_wait_status;
338
339   /* True, if in no ack mode.  That is, neither GDB nor the stub will
340      expect acks from each other.  The connection is assumed to be
341      reliable.  */
342   int noack_mode;
343
344   /* True if we're connected in extended remote mode.  */
345   int extended;
346
347   /* True if we resumed the target and we're waiting for the target to
348      stop.  In the mean time, we can't start another command/query.
349      The remote server wouldn't be ready to process it, so we'd
350      timeout waiting for a reply that would never come and eventually
351      we'd close the connection.  This can happen in asynchronous mode
352      because we allow GDB commands while the target is running.  */
353   int waiting_for_stop_reply;
354
355   /* The status of the stub support for the various vCont actions.  */
356   struct vCont_action_support supports_vCont;
357
358   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
359      responded to that.  */
360   int ctrlc_pending_p;
361
362   /* True if we saw a Ctrl-C while reading or writing from/to the
363      remote descriptor.  At that point it is not safe to send a remote
364      interrupt packet, so we instead remember we saw the Ctrl-C and
365      process it once we're done with sending/receiving the current
366      packet, which should be shortly.  If however that takes too long,
367      and the user presses Ctrl-C again, we offer to disconnect.  */
368   int got_ctrlc_during_io;
369
370   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
371      remote_open knows that we don't have a file open when the program
372      starts.  */
373   struct serial *remote_desc;
374
375   /* These are the threads which we last sent to the remote system.  The
376      TID member will be -1 for all or -2 for not sent yet.  */
377   ptid_t general_thread;
378   ptid_t continue_thread;
379
380   /* This is the traceframe which we last selected on the remote system.
381      It will be -1 if no traceframe is selected.  */
382   int remote_traceframe_number;
383
384   char *last_pass_packet;
385
386   /* The last QProgramSignals packet sent to the target.  We bypass
387      sending a new program signals list down to the target if the new
388      packet is exactly the same as the last we sent.  IOW, we only let
389      the target know about program signals list changes.  */
390   char *last_program_signals_packet;
391
392   enum gdb_signal last_sent_signal;
393
394   int last_sent_step;
395
396   /* The execution direction of the last resume we got.  */
397   enum exec_direction_kind last_resume_exec_dir;
398
399   char *finished_object;
400   char *finished_annex;
401   ULONGEST finished_offset;
402
403   /* Should we try the 'ThreadInfo' query packet?
404
405      This variable (NOT available to the user: auto-detect only!)
406      determines whether GDB will use the new, simpler "ThreadInfo"
407      query or the older, more complex syntax for thread queries.
408      This is an auto-detect variable (set to true at each connect,
409      and set to false when the target fails to recognize it).  */
410   int use_threadinfo_query;
411   int use_threadextra_query;
412
413   threadref echo_nextthread;
414   threadref nextthread;
415   threadref resultthreadlist[MAXTHREADLISTRESULTS];
416
417   /* The state of remote notification.  */
418   struct remote_notif_state *notif_state;
419
420   /* The branch trace configuration.  */
421   struct btrace_config btrace_config;
422
423   /* The argument to the last "vFile:setfs:" packet we sent, used
424      to avoid sending repeated unnecessary "vFile:setfs:" packets.
425      Initialized to -1 to indicate that no "vFile:setfs:" packet
426      has yet been sent.  */
427   int fs_pid;
428
429   /* A readahead cache for vFile:pread.  Often, reading a binary
430      involves a sequence of small reads.  E.g., when parsing an ELF
431      file.  A readahead cache helps mostly the case of remote
432      debugging on a connection with higher latency, due to the
433      request/reply nature of the RSP.  We only cache data for a single
434      file descriptor at a time.  */
435   struct readahead_cache readahead_cache;
436 };
437
438 /* Private data that we'll store in (struct thread_info)->private.  */
439 struct private_thread_info
440 {
441   char *extra;
442   char *name;
443   int core;
444
445   /* Whether the target stopped for a breakpoint/watchpoint.  */
446   enum target_stop_reason stop_reason;
447
448   /* This is set to the data address of the access causing the target
449      to stop for a watchpoint.  */
450   CORE_ADDR watch_data_address;
451 };
452
453 static void
454 free_private_thread_info (struct private_thread_info *info)
455 {
456   xfree (info->extra);
457   xfree (info->name);
458   xfree (info);
459 }
460
461 /* This data could be associated with a target, but we do not always
462    have access to the current target when we need it, so for now it is
463    static.  This will be fine for as long as only one target is in use
464    at a time.  */
465 static struct remote_state *remote_state;
466
467 static struct remote_state *
468 get_remote_state_raw (void)
469 {
470   return remote_state;
471 }
472
473 /* Allocate a new struct remote_state with xmalloc, initialize it, and
474    return it.  */
475
476 static struct remote_state *
477 new_remote_state (void)
478 {
479   struct remote_state *result = XCNEW (struct remote_state);
480
481   /* The default buffer size is unimportant; it will be expanded
482      whenever a larger buffer is needed. */
483   result->buf_size = 400;
484   result->buf = (char *) xmalloc (result->buf_size);
485   result->remote_traceframe_number = -1;
486   result->last_sent_signal = GDB_SIGNAL_0;
487   result->last_resume_exec_dir = EXEC_FORWARD;
488   result->fs_pid = -1;
489
490   return result;
491 }
492
493 /* Description of the remote protocol for a given architecture.  */
494
495 struct packet_reg
496 {
497   long offset; /* Offset into G packet.  */
498   long regnum; /* GDB's internal register number.  */
499   LONGEST pnum; /* Remote protocol register number.  */
500   int in_g_packet; /* Always part of G packet.  */
501   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
502      at present.  */
503   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
504      at present.  */
505 };
506
507 struct remote_arch_state
508 {
509   /* Description of the remote protocol registers.  */
510   long sizeof_g_packet;
511
512   /* Description of the remote protocol registers indexed by REGNUM
513      (making an array gdbarch_num_regs in size).  */
514   struct packet_reg *regs;
515
516   /* This is the size (in chars) of the first response to the ``g''
517      packet.  It is used as a heuristic when determining the maximum
518      size of memory-read and memory-write packets.  A target will
519      typically only reserve a buffer large enough to hold the ``g''
520      packet.  The size does not include packet overhead (headers and
521      trailers).  */
522   long actual_register_packet_size;
523
524   /* This is the maximum size (in chars) of a non read/write packet.
525      It is also used as a cap on the size of read/write packets.  */
526   long remote_packet_size;
527 };
528
529 /* Utility: generate error from an incoming stub packet.  */
530 static void
531 trace_error (char *buf)
532 {
533   if (*buf++ != 'E')
534     return;                     /* not an error msg */
535   switch (*buf)
536     {
537     case '1':                   /* malformed packet error */
538       if (*++buf == '0')        /*   general case: */
539         error (_("remote.c: error in outgoing packet."));
540       else
541         error (_("remote.c: error in outgoing packet at field #%ld."),
542                strtol (buf, NULL, 16));
543     default:
544       error (_("Target returns error code '%s'."), buf);
545     }
546 }
547
548 /* Utility: wait for reply from stub, while accepting "O" packets.  */
549 static char *
550 remote_get_noisy_reply (char **buf_p,
551                         long *sizeof_buf)
552 {
553   do                            /* Loop on reply from remote stub.  */
554     {
555       char *buf;
556
557       QUIT;                     /* Allow user to bail out with ^C.  */
558       getpkt (buf_p, sizeof_buf, 0);
559       buf = *buf_p;
560       if (buf[0] == 'E')
561         trace_error (buf);
562       else if (startswith (buf, "qRelocInsn:"))
563         {
564           ULONGEST ul;
565           CORE_ADDR from, to, org_to;
566           char *p, *pp;
567           int adjusted_size = 0;
568           int relocated = 0;
569
570           p = buf + strlen ("qRelocInsn:");
571           pp = unpack_varlen_hex (p, &ul);
572           if (*pp != ';')
573             error (_("invalid qRelocInsn packet: %s"), buf);
574           from = ul;
575
576           p = pp + 1;
577           unpack_varlen_hex (p, &ul);
578           to = ul;
579
580           org_to = to;
581
582           TRY
583             {
584               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
585               relocated = 1;
586             }
587           CATCH (ex, RETURN_MASK_ALL)
588             {
589               if (ex.error == MEMORY_ERROR)
590                 {
591                   /* Propagate memory errors silently back to the
592                      target.  The stub may have limited the range of
593                      addresses we can write to, for example.  */
594                 }
595               else
596                 {
597                   /* Something unexpectedly bad happened.  Be verbose
598                      so we can tell what, and propagate the error back
599                      to the stub, so it doesn't get stuck waiting for
600                      a response.  */
601                   exception_fprintf (gdb_stderr, ex,
602                                      _("warning: relocating instruction: "));
603                 }
604               putpkt ("E01");
605             }
606           END_CATCH
607
608           if (relocated)
609             {
610               adjusted_size = to - org_to;
611
612               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
613               putpkt (buf);
614             }
615         }
616       else if (buf[0] == 'O' && buf[1] != 'K')
617         remote_console_output (buf + 1);        /* 'O' message from stub */
618       else
619         return buf;             /* Here's the actual reply.  */
620     }
621   while (1);
622 }
623
624 /* Handle for retreving the remote protocol data from gdbarch.  */
625 static struct gdbarch_data *remote_gdbarch_data_handle;
626
627 static struct remote_arch_state *
628 get_remote_arch_state (void)
629 {
630   gdb_assert (target_gdbarch () != NULL);
631   return ((struct remote_arch_state *)
632           gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
633 }
634
635 /* Fetch the global remote target state.  */
636
637 static struct remote_state *
638 get_remote_state (void)
639 {
640   /* Make sure that the remote architecture state has been
641      initialized, because doing so might reallocate rs->buf.  Any
642      function which calls getpkt also needs to be mindful of changes
643      to rs->buf, but this call limits the number of places which run
644      into trouble.  */
645   get_remote_arch_state ();
646
647   return get_remote_state_raw ();
648 }
649
650 /* Cleanup routine for the remote module's pspace data.  */
651
652 static void
653 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
654 {
655   char *remote_exec_file = (char *) arg;
656
657   xfree (remote_exec_file);
658 }
659
660 /* Fetch the remote exec-file from the current program space.  */
661
662 static const char *
663 get_remote_exec_file (void)
664 {
665   char *remote_exec_file;
666
667   remote_exec_file
668     = (char *) program_space_data (current_program_space,
669                                    remote_pspace_data);
670   if (remote_exec_file == NULL)
671     return "";
672
673   return remote_exec_file;
674 }
675
676 /* Set the remote exec file for PSPACE.  */
677
678 static void
679 set_pspace_remote_exec_file (struct program_space *pspace,
680                         char *remote_exec_file)
681 {
682   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
683
684   xfree (old_file);
685   set_program_space_data (pspace, remote_pspace_data,
686                           xstrdup (remote_exec_file));
687 }
688
689 /* The "set/show remote exec-file" set command hook.  */
690
691 static void
692 set_remote_exec_file (char *ignored, int from_tty,
693                       struct cmd_list_element *c)
694 {
695   gdb_assert (remote_exec_file_var != NULL);
696   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
697 }
698
699 /* The "set/show remote exec-file" show command hook.  */
700
701 static void
702 show_remote_exec_file (struct ui_file *file, int from_tty,
703                        struct cmd_list_element *cmd, const char *value)
704 {
705   fprintf_filtered (file, "%s\n", remote_exec_file_var);
706 }
707
708 static int
709 compare_pnums (const void *lhs_, const void *rhs_)
710 {
711   const struct packet_reg * const *lhs
712     = (const struct packet_reg * const *) lhs_;
713   const struct packet_reg * const *rhs
714     = (const struct packet_reg * const *) rhs_;
715
716   if ((*lhs)->pnum < (*rhs)->pnum)
717     return -1;
718   else if ((*lhs)->pnum == (*rhs)->pnum)
719     return 0;
720   else
721     return 1;
722 }
723
724 static int
725 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
726 {
727   int regnum, num_remote_regs, offset;
728   struct packet_reg **remote_regs;
729
730   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
731     {
732       struct packet_reg *r = &regs[regnum];
733
734       if (register_size (gdbarch, regnum) == 0)
735         /* Do not try to fetch zero-sized (placeholder) registers.  */
736         r->pnum = -1;
737       else
738         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
739
740       r->regnum = regnum;
741     }
742
743   /* Define the g/G packet format as the contents of each register
744      with a remote protocol number, in order of ascending protocol
745      number.  */
746
747   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
748   for (num_remote_regs = 0, regnum = 0;
749        regnum < gdbarch_num_regs (gdbarch);
750        regnum++)
751     if (regs[regnum].pnum != -1)
752       remote_regs[num_remote_regs++] = &regs[regnum];
753
754   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
755          compare_pnums);
756
757   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
758     {
759       remote_regs[regnum]->in_g_packet = 1;
760       remote_regs[regnum]->offset = offset;
761       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
762     }
763
764   return offset;
765 }
766
767 /* Given the architecture described by GDBARCH, return the remote
768    protocol register's number and the register's offset in the g/G
769    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
770    If the target does not have a mapping for REGNUM, return false,
771    otherwise, return true.  */
772
773 int
774 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
775                                    int *pnum, int *poffset)
776 {
777   struct packet_reg *regs;
778   struct cleanup *old_chain;
779
780   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
781
782   regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
783   old_chain = make_cleanup (xfree, regs);
784
785   map_regcache_remote_table (gdbarch, regs);
786
787   *pnum = regs[regnum].pnum;
788   *poffset = regs[regnum].offset;
789
790   do_cleanups (old_chain);
791
792   return *pnum != -1;
793 }
794
795 static void *
796 init_remote_state (struct gdbarch *gdbarch)
797 {
798   struct remote_state *rs = get_remote_state_raw ();
799   struct remote_arch_state *rsa;
800
801   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
802
803   /* Use the architecture to build a regnum<->pnum table, which will be
804      1:1 unless a feature set specifies otherwise.  */
805   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
806                                       gdbarch_num_regs (gdbarch),
807                                       struct packet_reg);
808
809   /* Record the maximum possible size of the g packet - it may turn out
810      to be smaller.  */
811   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
812
813   /* Default maximum number of characters in a packet body.  Many
814      remote stubs have a hardwired buffer size of 400 bytes
815      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
816      as the maximum packet-size to ensure that the packet and an extra
817      NUL character can always fit in the buffer.  This stops GDB
818      trashing stubs that try to squeeze an extra NUL into what is
819      already a full buffer (As of 1999-12-04 that was most stubs).  */
820   rsa->remote_packet_size = 400 - 1;
821
822   /* This one is filled in when a ``g'' packet is received.  */
823   rsa->actual_register_packet_size = 0;
824
825   /* Should rsa->sizeof_g_packet needs more space than the
826      default, adjust the size accordingly.  Remember that each byte is
827      encoded as two characters.  32 is the overhead for the packet
828      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
829      (``$NN:G...#NN'') is a better guess, the below has been padded a
830      little.  */
831   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
832     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
833
834   /* Make sure that the packet buffer is plenty big enough for
835      this architecture.  */
836   if (rs->buf_size < rsa->remote_packet_size)
837     {
838       rs->buf_size = 2 * rsa->remote_packet_size;
839       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
840     }
841
842   return rsa;
843 }
844
845 /* Return the current allowed size of a remote packet.  This is
846    inferred from the current architecture, and should be used to
847    limit the length of outgoing packets.  */
848 static long
849 get_remote_packet_size (void)
850 {
851   struct remote_state *rs = get_remote_state ();
852   struct remote_arch_state *rsa = get_remote_arch_state ();
853
854   if (rs->explicit_packet_size)
855     return rs->explicit_packet_size;
856
857   return rsa->remote_packet_size;
858 }
859
860 static struct packet_reg *
861 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
862 {
863   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
864     return NULL;
865   else
866     {
867       struct packet_reg *r = &rsa->regs[regnum];
868
869       gdb_assert (r->regnum == regnum);
870       return r;
871     }
872 }
873
874 static struct packet_reg *
875 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
876 {
877   int i;
878
879   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
880     {
881       struct packet_reg *r = &rsa->regs[i];
882
883       if (r->pnum == pnum)
884         return r;
885     }
886   return NULL;
887 }
888
889 static struct target_ops remote_ops;
890
891 static struct target_ops extended_remote_ops;
892
893 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
894    ``forever'' still use the normal timeout mechanism.  This is
895    currently used by the ASYNC code to guarentee that target reads
896    during the initial connect always time-out.  Once getpkt has been
897    modified to return a timeout indication and, in turn
898    remote_wait()/wait_for_inferior() have gained a timeout parameter
899    this can go away.  */
900 static int wait_forever_enabled_p = 1;
901
902 /* Allow the user to specify what sequence to send to the remote
903    when he requests a program interruption: Although ^C is usually
904    what remote systems expect (this is the default, here), it is
905    sometimes preferable to send a break.  On other systems such
906    as the Linux kernel, a break followed by g, which is Magic SysRq g
907    is required in order to interrupt the execution.  */
908 const char interrupt_sequence_control_c[] = "Ctrl-C";
909 const char interrupt_sequence_break[] = "BREAK";
910 const char interrupt_sequence_break_g[] = "BREAK-g";
911 static const char *const interrupt_sequence_modes[] =
912   {
913     interrupt_sequence_control_c,
914     interrupt_sequence_break,
915     interrupt_sequence_break_g,
916     NULL
917   };
918 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
919
920 static void
921 show_interrupt_sequence (struct ui_file *file, int from_tty,
922                          struct cmd_list_element *c,
923                          const char *value)
924 {
925   if (interrupt_sequence_mode == interrupt_sequence_control_c)
926     fprintf_filtered (file,
927                       _("Send the ASCII ETX character (Ctrl-c) "
928                         "to the remote target to interrupt the "
929                         "execution of the program.\n"));
930   else if (interrupt_sequence_mode == interrupt_sequence_break)
931     fprintf_filtered (file,
932                       _("send a break signal to the remote target "
933                         "to interrupt the execution of the program.\n"));
934   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
935     fprintf_filtered (file,
936                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
937                         "the remote target to interrupt the execution "
938                         "of Linux kernel.\n"));
939   else
940     internal_error (__FILE__, __LINE__,
941                     _("Invalid value for interrupt_sequence_mode: %s."),
942                     interrupt_sequence_mode);
943 }
944
945 /* This boolean variable specifies whether interrupt_sequence is sent
946    to the remote target when gdb connects to it.
947    This is mostly needed when you debug the Linux kernel: The Linux kernel
948    expects BREAK g which is Magic SysRq g for connecting gdb.  */
949 static int interrupt_on_connect = 0;
950
951 /* This variable is used to implement the "set/show remotebreak" commands.
952    Since these commands are now deprecated in favor of "set/show remote
953    interrupt-sequence", it no longer has any effect on the code.  */
954 static int remote_break;
955
956 static void
957 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
958 {
959   if (remote_break)
960     interrupt_sequence_mode = interrupt_sequence_break;
961   else
962     interrupt_sequence_mode = interrupt_sequence_control_c;
963 }
964
965 static void
966 show_remotebreak (struct ui_file *file, int from_tty,
967                   struct cmd_list_element *c,
968                   const char *value)
969 {
970 }
971
972 /* This variable sets the number of bits in an address that are to be
973    sent in a memory ("M" or "m") packet.  Normally, after stripping
974    leading zeros, the entire address would be sent.  This variable
975    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
976    initial implementation of remote.c restricted the address sent in
977    memory packets to ``host::sizeof long'' bytes - (typically 32
978    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
979    address was never sent.  Since fixing this bug may cause a break in
980    some remote targets this variable is principly provided to
981    facilitate backward compatibility.  */
982
983 static unsigned int remote_address_size;
984
985 /* Temporary to track who currently owns the terminal.  See
986    remote_terminal_* for more details.  */
987
988 static int remote_async_terminal_ours_p;
989
990 \f
991 /* User configurable variables for the number of characters in a
992    memory read/write packet.  MIN (rsa->remote_packet_size,
993    rsa->sizeof_g_packet) is the default.  Some targets need smaller
994    values (fifo overruns, et.al.) and some users need larger values
995    (speed up transfers).  The variables ``preferred_*'' (the user
996    request), ``current_*'' (what was actually set) and ``forced_*''
997    (Positive - a soft limit, negative - a hard limit).  */
998
999 struct memory_packet_config
1000 {
1001   char *name;
1002   long size;
1003   int fixed_p;
1004 };
1005
1006 /* The default max memory-write-packet-size.  The 16k is historical.
1007    (It came from older GDB's using alloca for buffers and the
1008    knowledge (folklore?) that some hosts don't cope very well with
1009    large alloca calls.)  */
1010 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1011
1012 /* The minimum remote packet size for memory transfers.  Ensures we
1013    can write at least one byte.  */
1014 #define MIN_MEMORY_PACKET_SIZE 20
1015
1016 /* Compute the current size of a read/write packet.  Since this makes
1017    use of ``actual_register_packet_size'' the computation is dynamic.  */
1018
1019 static long
1020 get_memory_packet_size (struct memory_packet_config *config)
1021 {
1022   struct remote_state *rs = get_remote_state ();
1023   struct remote_arch_state *rsa = get_remote_arch_state ();
1024
1025   long what_they_get;
1026   if (config->fixed_p)
1027     {
1028       if (config->size <= 0)
1029         what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1030       else
1031         what_they_get = config->size;
1032     }
1033   else
1034     {
1035       what_they_get = get_remote_packet_size ();
1036       /* Limit the packet to the size specified by the user.  */
1037       if (config->size > 0
1038           && what_they_get > config->size)
1039         what_they_get = config->size;
1040
1041       /* Limit it to the size of the targets ``g'' response unless we have
1042          permission from the stub to use a larger packet size.  */
1043       if (rs->explicit_packet_size == 0
1044           && rsa->actual_register_packet_size > 0
1045           && what_they_get > rsa->actual_register_packet_size)
1046         what_they_get = rsa->actual_register_packet_size;
1047     }
1048   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1049     what_they_get = MIN_MEMORY_PACKET_SIZE;
1050
1051   /* Make sure there is room in the global buffer for this packet
1052      (including its trailing NUL byte).  */
1053   if (rs->buf_size < what_they_get + 1)
1054     {
1055       rs->buf_size = 2 * what_they_get;
1056       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1057     }
1058
1059   return what_they_get;
1060 }
1061
1062 /* Update the size of a read/write packet.  If they user wants
1063    something really big then do a sanity check.  */
1064
1065 static void
1066 set_memory_packet_size (char *args, struct memory_packet_config *config)
1067 {
1068   int fixed_p = config->fixed_p;
1069   long size = config->size;
1070
1071   if (args == NULL)
1072     error (_("Argument required (integer, `fixed' or `limited')."));
1073   else if (strcmp (args, "hard") == 0
1074       || strcmp (args, "fixed") == 0)
1075     fixed_p = 1;
1076   else if (strcmp (args, "soft") == 0
1077            || strcmp (args, "limit") == 0)
1078     fixed_p = 0;
1079   else
1080     {
1081       char *end;
1082
1083       size = strtoul (args, &end, 0);
1084       if (args == end)
1085         error (_("Invalid %s (bad syntax)."), config->name);
1086
1087       /* Instead of explicitly capping the size of a packet to or
1088          disallowing it, the user is allowed to set the size to
1089          something arbitrarily large.  */
1090     }
1091
1092   /* So that the query shows the correct value.  */
1093   if (size <= 0)
1094     size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1095
1096   /* Extra checks?  */
1097   if (fixed_p && !config->fixed_p)
1098     {
1099       if (! query (_("The target may not be able to correctly handle a %s\n"
1100                    "of %ld bytes. Change the packet size? "),
1101                    config->name, size))
1102         error (_("Packet size not changed."));
1103     }
1104   /* Update the config.  */
1105   config->fixed_p = fixed_p;
1106   config->size = size;
1107 }
1108
1109 static void
1110 show_memory_packet_size (struct memory_packet_config *config)
1111 {
1112   printf_filtered (_("The %s is %ld. "), config->name, config->size);
1113   if (config->fixed_p)
1114     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1115                      get_memory_packet_size (config));
1116   else
1117     printf_filtered (_("Packets are limited to %ld bytes.\n"),
1118                      get_memory_packet_size (config));
1119 }
1120
1121 static struct memory_packet_config memory_write_packet_config =
1122 {
1123   "memory-write-packet-size",
1124 };
1125
1126 static void
1127 set_memory_write_packet_size (char *args, int from_tty)
1128 {
1129   set_memory_packet_size (args, &memory_write_packet_config);
1130 }
1131
1132 static void
1133 show_memory_write_packet_size (char *args, int from_tty)
1134 {
1135   show_memory_packet_size (&memory_write_packet_config);
1136 }
1137
1138 static long
1139 get_memory_write_packet_size (void)
1140 {
1141   return get_memory_packet_size (&memory_write_packet_config);
1142 }
1143
1144 static struct memory_packet_config memory_read_packet_config =
1145 {
1146   "memory-read-packet-size",
1147 };
1148
1149 static void
1150 set_memory_read_packet_size (char *args, int from_tty)
1151 {
1152   set_memory_packet_size (args, &memory_read_packet_config);
1153 }
1154
1155 static void
1156 show_memory_read_packet_size (char *args, int from_tty)
1157 {
1158   show_memory_packet_size (&memory_read_packet_config);
1159 }
1160
1161 static long
1162 get_memory_read_packet_size (void)
1163 {
1164   long size = get_memory_packet_size (&memory_read_packet_config);
1165
1166   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1167      extra buffer size argument before the memory read size can be
1168      increased beyond this.  */
1169   if (size > get_remote_packet_size ())
1170     size = get_remote_packet_size ();
1171   return size;
1172 }
1173
1174 \f
1175 /* Generic configuration support for packets the stub optionally
1176    supports.  Allows the user to specify the use of the packet as well
1177    as allowing GDB to auto-detect support in the remote stub.  */
1178
1179 enum packet_support
1180   {
1181     PACKET_SUPPORT_UNKNOWN = 0,
1182     PACKET_ENABLE,
1183     PACKET_DISABLE
1184   };
1185
1186 struct packet_config
1187   {
1188     const char *name;
1189     const char *title;
1190
1191     /* If auto, GDB auto-detects support for this packet or feature,
1192        either through qSupported, or by trying the packet and looking
1193        at the response.  If true, GDB assumes the target supports this
1194        packet.  If false, the packet is disabled.  Configs that don't
1195        have an associated command always have this set to auto.  */
1196     enum auto_boolean detect;
1197
1198     /* Does the target support this packet?  */
1199     enum packet_support support;
1200   };
1201
1202 /* Analyze a packet's return value and update the packet config
1203    accordingly.  */
1204
1205 enum packet_result
1206 {
1207   PACKET_ERROR,
1208   PACKET_OK,
1209   PACKET_UNKNOWN
1210 };
1211
1212 static enum packet_support packet_config_support (struct packet_config *config);
1213 static enum packet_support packet_support (int packet);
1214
1215 static void
1216 show_packet_config_cmd (struct packet_config *config)
1217 {
1218   char *support = "internal-error";
1219
1220   switch (packet_config_support (config))
1221     {
1222     case PACKET_ENABLE:
1223       support = "enabled";
1224       break;
1225     case PACKET_DISABLE:
1226       support = "disabled";
1227       break;
1228     case PACKET_SUPPORT_UNKNOWN:
1229       support = "unknown";
1230       break;
1231     }
1232   switch (config->detect)
1233     {
1234     case AUTO_BOOLEAN_AUTO:
1235       printf_filtered (_("Support for the `%s' packet "
1236                          "is auto-detected, currently %s.\n"),
1237                        config->name, support);
1238       break;
1239     case AUTO_BOOLEAN_TRUE:
1240     case AUTO_BOOLEAN_FALSE:
1241       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1242                        config->name, support);
1243       break;
1244     }
1245 }
1246
1247 static void
1248 add_packet_config_cmd (struct packet_config *config, const char *name,
1249                        const char *title, int legacy)
1250 {
1251   char *set_doc;
1252   char *show_doc;
1253   char *cmd_name;
1254
1255   config->name = name;
1256   config->title = title;
1257   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1258                         name, title);
1259   show_doc = xstrprintf ("Show current use of remote "
1260                          "protocol `%s' (%s) packet",
1261                          name, title);
1262   /* set/show TITLE-packet {auto,on,off} */
1263   cmd_name = xstrprintf ("%s-packet", title);
1264   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1265                                 &config->detect, set_doc,
1266                                 show_doc, NULL, /* help_doc */
1267                                 NULL,
1268                                 show_remote_protocol_packet_cmd,
1269                                 &remote_set_cmdlist, &remote_show_cmdlist);
1270   /* The command code copies the documentation strings.  */
1271   xfree (set_doc);
1272   xfree (show_doc);
1273   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1274   if (legacy)
1275     {
1276       char *legacy_name;
1277
1278       legacy_name = xstrprintf ("%s-packet", name);
1279       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1280                      &remote_set_cmdlist);
1281       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1282                      &remote_show_cmdlist);
1283     }
1284 }
1285
1286 static enum packet_result
1287 packet_check_result (const char *buf)
1288 {
1289   if (buf[0] != '\0')
1290     {
1291       /* The stub recognized the packet request.  Check that the
1292          operation succeeded.  */
1293       if (buf[0] == 'E'
1294           && isxdigit (buf[1]) && isxdigit (buf[2])
1295           && buf[3] == '\0')
1296         /* "Enn"  - definitly an error.  */
1297         return PACKET_ERROR;
1298
1299       /* Always treat "E." as an error.  This will be used for
1300          more verbose error messages, such as E.memtypes.  */
1301       if (buf[0] == 'E' && buf[1] == '.')
1302         return PACKET_ERROR;
1303
1304       /* The packet may or may not be OK.  Just assume it is.  */
1305       return PACKET_OK;
1306     }
1307   else
1308     /* The stub does not support the packet.  */
1309     return PACKET_UNKNOWN;
1310 }
1311
1312 static enum packet_result
1313 packet_ok (const char *buf, struct packet_config *config)
1314 {
1315   enum packet_result result;
1316
1317   if (config->detect != AUTO_BOOLEAN_TRUE
1318       && config->support == PACKET_DISABLE)
1319     internal_error (__FILE__, __LINE__,
1320                     _("packet_ok: attempt to use a disabled packet"));
1321
1322   result = packet_check_result (buf);
1323   switch (result)
1324     {
1325     case PACKET_OK:
1326     case PACKET_ERROR:
1327       /* The stub recognized the packet request.  */
1328       if (config->support == PACKET_SUPPORT_UNKNOWN)
1329         {
1330           if (remote_debug)
1331             fprintf_unfiltered (gdb_stdlog,
1332                                 "Packet %s (%s) is supported\n",
1333                                 config->name, config->title);
1334           config->support = PACKET_ENABLE;
1335         }
1336       break;
1337     case PACKET_UNKNOWN:
1338       /* The stub does not support the packet.  */
1339       if (config->detect == AUTO_BOOLEAN_AUTO
1340           && config->support == PACKET_ENABLE)
1341         {
1342           /* If the stub previously indicated that the packet was
1343              supported then there is a protocol error.  */
1344           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1345                  config->name, config->title);
1346         }
1347       else if (config->detect == AUTO_BOOLEAN_TRUE)
1348         {
1349           /* The user set it wrong.  */
1350           error (_("Enabled packet %s (%s) not recognized by stub"),
1351                  config->name, config->title);
1352         }
1353
1354       if (remote_debug)
1355         fprintf_unfiltered (gdb_stdlog,
1356                             "Packet %s (%s) is NOT supported\n",
1357                             config->name, config->title);
1358       config->support = PACKET_DISABLE;
1359       break;
1360     }
1361
1362   return result;
1363 }
1364
1365 enum {
1366   PACKET_vCont = 0,
1367   PACKET_X,
1368   PACKET_qSymbol,
1369   PACKET_P,
1370   PACKET_p,
1371   PACKET_Z0,
1372   PACKET_Z1,
1373   PACKET_Z2,
1374   PACKET_Z3,
1375   PACKET_Z4,
1376   PACKET_vFile_setfs,
1377   PACKET_vFile_open,
1378   PACKET_vFile_pread,
1379   PACKET_vFile_pwrite,
1380   PACKET_vFile_close,
1381   PACKET_vFile_unlink,
1382   PACKET_vFile_readlink,
1383   PACKET_vFile_fstat,
1384   PACKET_qXfer_auxv,
1385   PACKET_qXfer_features,
1386   PACKET_qXfer_exec_file,
1387   PACKET_qXfer_libraries,
1388   PACKET_qXfer_libraries_svr4,
1389   PACKET_qXfer_memory_map,
1390   PACKET_qXfer_spu_read,
1391   PACKET_qXfer_spu_write,
1392   PACKET_qXfer_osdata,
1393   PACKET_qXfer_threads,
1394   PACKET_qXfer_statictrace_read,
1395   PACKET_qXfer_traceframe_info,
1396   PACKET_qXfer_uib,
1397   PACKET_qGetTIBAddr,
1398   PACKET_qGetTLSAddr,
1399   PACKET_qSupported,
1400   PACKET_qTStatus,
1401   PACKET_QPassSignals,
1402   PACKET_QCatchSyscalls,
1403   PACKET_QProgramSignals,
1404   PACKET_qCRC,
1405   PACKET_qSearch_memory,
1406   PACKET_vAttach,
1407   PACKET_vRun,
1408   PACKET_QStartNoAckMode,
1409   PACKET_vKill,
1410   PACKET_qXfer_siginfo_read,
1411   PACKET_qXfer_siginfo_write,
1412   PACKET_qAttached,
1413
1414   /* Support for conditional tracepoints.  */
1415   PACKET_ConditionalTracepoints,
1416
1417   /* Support for target-side breakpoint conditions.  */
1418   PACKET_ConditionalBreakpoints,
1419
1420   /* Support for target-side breakpoint commands.  */
1421   PACKET_BreakpointCommands,
1422
1423   /* Support for fast tracepoints.  */
1424   PACKET_FastTracepoints,
1425
1426   /* Support for static tracepoints.  */
1427   PACKET_StaticTracepoints,
1428
1429   /* Support for installing tracepoints while a trace experiment is
1430      running.  */
1431   PACKET_InstallInTrace,
1432
1433   PACKET_bc,
1434   PACKET_bs,
1435   PACKET_TracepointSource,
1436   PACKET_QAllow,
1437   PACKET_qXfer_fdpic,
1438   PACKET_QDisableRandomization,
1439   PACKET_QAgent,
1440   PACKET_QTBuffer_size,
1441   PACKET_Qbtrace_off,
1442   PACKET_Qbtrace_bts,
1443   PACKET_Qbtrace_pt,
1444   PACKET_qXfer_btrace,
1445
1446   /* Support for the QNonStop packet.  */
1447   PACKET_QNonStop,
1448
1449   /* Support for the QThreadEvents packet.  */
1450   PACKET_QThreadEvents,
1451
1452   /* Support for multi-process extensions.  */
1453   PACKET_multiprocess_feature,
1454
1455   /* Support for enabling and disabling tracepoints while a trace
1456      experiment is running.  */
1457   PACKET_EnableDisableTracepoints_feature,
1458
1459   /* Support for collecting strings using the tracenz bytecode.  */
1460   PACKET_tracenz_feature,
1461
1462   /* Support for continuing to run a trace experiment while GDB is
1463      disconnected.  */
1464   PACKET_DisconnectedTracing_feature,
1465
1466   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1467   PACKET_augmented_libraries_svr4_read_feature,
1468
1469   /* Support for the qXfer:btrace-conf:read packet.  */
1470   PACKET_qXfer_btrace_conf,
1471
1472   /* Support for the Qbtrace-conf:bts:size packet.  */
1473   PACKET_Qbtrace_conf_bts_size,
1474
1475   /* Support for swbreak+ feature.  */
1476   PACKET_swbreak_feature,
1477
1478   /* Support for hwbreak+ feature.  */
1479   PACKET_hwbreak_feature,
1480
1481   /* Support for fork events.  */
1482   PACKET_fork_event_feature,
1483
1484   /* Support for vfork events.  */
1485   PACKET_vfork_event_feature,
1486
1487   /* Support for the Qbtrace-conf:pt:size packet.  */
1488   PACKET_Qbtrace_conf_pt_size,
1489
1490   /* Support for exec events.  */
1491   PACKET_exec_event_feature,
1492
1493   /* Support for query supported vCont actions.  */
1494   PACKET_vContSupported,
1495
1496   /* Support remote CTRL-C.  */
1497   PACKET_vCtrlC,
1498
1499   /* Support TARGET_WAITKIND_NO_RESUMED.  */
1500   PACKET_no_resumed,
1501
1502   PACKET_MAX
1503 };
1504
1505 static struct packet_config remote_protocol_packets[PACKET_MAX];
1506
1507 /* Returns the packet's corresponding "set remote foo-packet" command
1508    state.  See struct packet_config for more details.  */
1509
1510 static enum auto_boolean
1511 packet_set_cmd_state (int packet)
1512 {
1513   return remote_protocol_packets[packet].detect;
1514 }
1515
1516 /* Returns whether a given packet or feature is supported.  This takes
1517    into account the state of the corresponding "set remote foo-packet"
1518    command, which may be used to bypass auto-detection.  */
1519
1520 static enum packet_support
1521 packet_config_support (struct packet_config *config)
1522 {
1523   switch (config->detect)
1524     {
1525     case AUTO_BOOLEAN_TRUE:
1526       return PACKET_ENABLE;
1527     case AUTO_BOOLEAN_FALSE:
1528       return PACKET_DISABLE;
1529     case AUTO_BOOLEAN_AUTO:
1530       return config->support;
1531     default:
1532       gdb_assert_not_reached (_("bad switch"));
1533     }
1534 }
1535
1536 /* Same as packet_config_support, but takes the packet's enum value as
1537    argument.  */
1538
1539 static enum packet_support
1540 packet_support (int packet)
1541 {
1542   struct packet_config *config = &remote_protocol_packets[packet];
1543
1544   return packet_config_support (config);
1545 }
1546
1547 static void
1548 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1549                                  struct cmd_list_element *c,
1550                                  const char *value)
1551 {
1552   struct packet_config *packet;
1553
1554   for (packet = remote_protocol_packets;
1555        packet < &remote_protocol_packets[PACKET_MAX];
1556        packet++)
1557     {
1558       if (&packet->detect == c->var)
1559         {
1560           show_packet_config_cmd (packet);
1561           return;
1562         }
1563     }
1564   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1565                   c->name);
1566 }
1567
1568 /* Should we try one of the 'Z' requests?  */
1569
1570 enum Z_packet_type
1571 {
1572   Z_PACKET_SOFTWARE_BP,
1573   Z_PACKET_HARDWARE_BP,
1574   Z_PACKET_WRITE_WP,
1575   Z_PACKET_READ_WP,
1576   Z_PACKET_ACCESS_WP,
1577   NR_Z_PACKET_TYPES
1578 };
1579
1580 /* For compatibility with older distributions.  Provide a ``set remote
1581    Z-packet ...'' command that updates all the Z packet types.  */
1582
1583 static enum auto_boolean remote_Z_packet_detect;
1584
1585 static void
1586 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1587                                   struct cmd_list_element *c)
1588 {
1589   int i;
1590
1591   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1592     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1593 }
1594
1595 static void
1596 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1597                                    struct cmd_list_element *c,
1598                                    const char *value)
1599 {
1600   int i;
1601
1602   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1603     {
1604       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1605     }
1606 }
1607
1608 /* Returns true if the multi-process extensions are in effect.  */
1609
1610 static int
1611 remote_multi_process_p (struct remote_state *rs)
1612 {
1613   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1614 }
1615
1616 /* Returns true if fork events are supported.  */
1617
1618 static int
1619 remote_fork_event_p (struct remote_state *rs)
1620 {
1621   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1622 }
1623
1624 /* Returns true if vfork events are supported.  */
1625
1626 static int
1627 remote_vfork_event_p (struct remote_state *rs)
1628 {
1629   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1630 }
1631
1632 /* Returns true if exec events are supported.  */
1633
1634 static int
1635 remote_exec_event_p (struct remote_state *rs)
1636 {
1637   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1638 }
1639
1640 /* Insert fork catchpoint target routine.  If fork events are enabled
1641    then return success, nothing more to do.  */
1642
1643 static int
1644 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1645 {
1646   struct remote_state *rs = get_remote_state ();
1647
1648   return !remote_fork_event_p (rs);
1649 }
1650
1651 /* Remove fork catchpoint target routine.  Nothing to do, just
1652    return success.  */
1653
1654 static int
1655 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1656 {
1657   return 0;
1658 }
1659
1660 /* Insert vfork catchpoint target routine.  If vfork events are enabled
1661    then return success, nothing more to do.  */
1662
1663 static int
1664 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1665 {
1666   struct remote_state *rs = get_remote_state ();
1667
1668   return !remote_vfork_event_p (rs);
1669 }
1670
1671 /* Remove vfork catchpoint target routine.  Nothing to do, just
1672    return success.  */
1673
1674 static int
1675 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1676 {
1677   return 0;
1678 }
1679
1680 /* Insert exec catchpoint target routine.  If exec events are
1681    enabled, just return success.  */
1682
1683 static int
1684 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1685 {
1686   struct remote_state *rs = get_remote_state ();
1687
1688   return !remote_exec_event_p (rs);
1689 }
1690
1691 /* Remove exec catchpoint target routine.  Nothing to do, just
1692    return success.  */
1693
1694 static int
1695 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1696 {
1697   return 0;
1698 }
1699
1700 \f
1701 /* Asynchronous signal handle registered as event loop source for
1702    when we have pending events ready to be passed to the core.  */
1703
1704 static struct async_event_handler *remote_async_inferior_event_token;
1705
1706 \f
1707
1708 static ptid_t magic_null_ptid;
1709 static ptid_t not_sent_ptid;
1710 static ptid_t any_thread_ptid;
1711
1712 /* Find out if the stub attached to PID (and hence GDB should offer to
1713    detach instead of killing it when bailing out).  */
1714
1715 static int
1716 remote_query_attached (int pid)
1717 {
1718   struct remote_state *rs = get_remote_state ();
1719   size_t size = get_remote_packet_size ();
1720
1721   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1722     return 0;
1723
1724   if (remote_multi_process_p (rs))
1725     xsnprintf (rs->buf, size, "qAttached:%x", pid);
1726   else
1727     xsnprintf (rs->buf, size, "qAttached");
1728
1729   putpkt (rs->buf);
1730   getpkt (&rs->buf, &rs->buf_size, 0);
1731
1732   switch (packet_ok (rs->buf,
1733                      &remote_protocol_packets[PACKET_qAttached]))
1734     {
1735     case PACKET_OK:
1736       if (strcmp (rs->buf, "1") == 0)
1737         return 1;
1738       break;
1739     case PACKET_ERROR:
1740       warning (_("Remote failure reply: %s"), rs->buf);
1741       break;
1742     case PACKET_UNKNOWN:
1743       break;
1744     }
1745
1746   return 0;
1747 }
1748
1749 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
1750    has been invented by GDB, instead of reported by the target.  Since
1751    we can be connected to a remote system before before knowing about
1752    any inferior, mark the target with execution when we find the first
1753    inferior.  If ATTACHED is 1, then we had just attached to this
1754    inferior.  If it is 0, then we just created this inferior.  If it
1755    is -1, then try querying the remote stub to find out if it had
1756    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
1757    attempt to open this inferior's executable as the main executable
1758    if no main executable is open already.  */
1759
1760 static struct inferior *
1761 remote_add_inferior (int fake_pid_p, int pid, int attached,
1762                      int try_open_exec)
1763 {
1764   struct inferior *inf;
1765
1766   /* Check whether this process we're learning about is to be
1767      considered attached, or if is to be considered to have been
1768      spawned by the stub.  */
1769   if (attached == -1)
1770     attached = remote_query_attached (pid);
1771
1772   if (gdbarch_has_global_solist (target_gdbarch ()))
1773     {
1774       /* If the target shares code across all inferiors, then every
1775          attach adds a new inferior.  */
1776       inf = add_inferior (pid);
1777
1778       /* ... and every inferior is bound to the same program space.
1779          However, each inferior may still have its own address
1780          space.  */
1781       inf->aspace = maybe_new_address_space ();
1782       inf->pspace = current_program_space;
1783     }
1784   else
1785     {
1786       /* In the traditional debugging scenario, there's a 1-1 match
1787          between program/address spaces.  We simply bind the inferior
1788          to the program space's address space.  */
1789       inf = current_inferior ();
1790       inferior_appeared (inf, pid);
1791     }
1792
1793   inf->attach_flag = attached;
1794   inf->fake_pid_p = fake_pid_p;
1795
1796   /* If no main executable is currently open then attempt to
1797      open the file that was executed to create this inferior.  */
1798   if (try_open_exec && get_exec_file (0) == NULL)
1799     exec_file_locate_attach (pid, 1);
1800
1801   return inf;
1802 }
1803
1804 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1805    according to RUNNING.  */
1806
1807 static void
1808 remote_add_thread (ptid_t ptid, int running, int executing)
1809 {
1810   struct remote_state *rs = get_remote_state ();
1811
1812   /* GDB historically didn't pull threads in the initial connection
1813      setup.  If the remote target doesn't even have a concept of
1814      threads (e.g., a bare-metal target), even if internally we
1815      consider that a single-threaded target, mentioning a new thread
1816      might be confusing to the user.  Be silent then, preserving the
1817      age old behavior.  */
1818   if (rs->starting_up)
1819     add_thread_silent (ptid);
1820   else
1821     add_thread (ptid);
1822
1823   set_executing (ptid, executing);
1824   set_running (ptid, running);
1825 }
1826
1827 /* Come here when we learn about a thread id from the remote target.
1828    It may be the first time we hear about such thread, so take the
1829    opportunity to add it to GDB's thread list.  In case this is the
1830    first time we're noticing its corresponding inferior, add it to
1831    GDB's inferior list as well.  EXECUTING indicates whether the
1832    thread is (internally) executing or stopped.  */
1833
1834 static void
1835 remote_notice_new_inferior (ptid_t currthread, int executing)
1836 {
1837   /* In non-stop mode, we assume new found threads are (externally)
1838      running until proven otherwise with a stop reply.  In all-stop,
1839      we can only get here if all threads are stopped.  */
1840   int running = target_is_non_stop_p () ? 1 : 0;
1841
1842   /* If this is a new thread, add it to GDB's thread list.
1843      If we leave it up to WFI to do this, bad things will happen.  */
1844
1845   if (in_thread_list (currthread) && is_exited (currthread))
1846     {
1847       /* We're seeing an event on a thread id we knew had exited.
1848          This has to be a new thread reusing the old id.  Add it.  */
1849       remote_add_thread (currthread, running, executing);
1850       return;
1851     }
1852
1853   if (!in_thread_list (currthread))
1854     {
1855       struct inferior *inf = NULL;
1856       int pid = ptid_get_pid (currthread);
1857
1858       if (ptid_is_pid (inferior_ptid)
1859           && pid == ptid_get_pid (inferior_ptid))
1860         {
1861           /* inferior_ptid has no thread member yet.  This can happen
1862              with the vAttach -> remote_wait,"TAAthread:" path if the
1863              stub doesn't support qC.  This is the first stop reported
1864              after an attach, so this is the main thread.  Update the
1865              ptid in the thread list.  */
1866           if (in_thread_list (pid_to_ptid (pid)))
1867             thread_change_ptid (inferior_ptid, currthread);
1868           else
1869             {
1870               remote_add_thread (currthread, running, executing);
1871               inferior_ptid = currthread;
1872             }
1873           return;
1874         }
1875
1876       if (ptid_equal (magic_null_ptid, inferior_ptid))
1877         {
1878           /* inferior_ptid is not set yet.  This can happen with the
1879              vRun -> remote_wait,"TAAthread:" path if the stub
1880              doesn't support qC.  This is the first stop reported
1881              after an attach, so this is the main thread.  Update the
1882              ptid in the thread list.  */
1883           thread_change_ptid (inferior_ptid, currthread);
1884           return;
1885         }
1886
1887       /* When connecting to a target remote, or to a target
1888          extended-remote which already was debugging an inferior, we
1889          may not know about it yet.  Add it before adding its child
1890          thread, so notifications are emitted in a sensible order.  */
1891       if (!in_inferior_list (ptid_get_pid (currthread)))
1892         {
1893           struct remote_state *rs = get_remote_state ();
1894           int fake_pid_p = !remote_multi_process_p (rs);
1895
1896           inf = remote_add_inferior (fake_pid_p,
1897                                      ptid_get_pid (currthread), -1, 1);
1898         }
1899
1900       /* This is really a new thread.  Add it.  */
1901       remote_add_thread (currthread, running, executing);
1902
1903       /* If we found a new inferior, let the common code do whatever
1904          it needs to with it (e.g., read shared libraries, insert
1905          breakpoints), unless we're just setting up an all-stop
1906          connection.  */
1907       if (inf != NULL)
1908         {
1909           struct remote_state *rs = get_remote_state ();
1910
1911           if (!rs->starting_up)
1912             notice_new_inferior (currthread, executing, 0);
1913         }
1914     }
1915 }
1916
1917 /* Return the private thread data, creating it if necessary.  */
1918
1919 static struct private_thread_info *
1920 demand_private_info (ptid_t ptid)
1921 {
1922   struct thread_info *info = find_thread_ptid (ptid);
1923
1924   gdb_assert (info);
1925
1926   if (!info->priv)
1927     {
1928       info->priv = XNEW (struct private_thread_info);
1929       info->private_dtor = free_private_thread_info;
1930       info->priv->core = -1;
1931       info->priv->extra = NULL;
1932       info->priv->name = NULL;
1933     }
1934
1935   return info->priv;
1936 }
1937
1938 /* Call this function as a result of
1939    1) A halt indication (T packet) containing a thread id
1940    2) A direct query of currthread
1941    3) Successful execution of set thread */
1942
1943 static void
1944 record_currthread (struct remote_state *rs, ptid_t currthread)
1945 {
1946   rs->general_thread = currthread;
1947 }
1948
1949 /* If 'QPassSignals' is supported, tell the remote stub what signals
1950    it can simply pass through to the inferior without reporting.  */
1951
1952 static void
1953 remote_pass_signals (struct target_ops *self,
1954                      int numsigs, unsigned char *pass_signals)
1955 {
1956   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1957     {
1958       char *pass_packet, *p;
1959       int count = 0, i;
1960       struct remote_state *rs = get_remote_state ();
1961
1962       gdb_assert (numsigs < 256);
1963       for (i = 0; i < numsigs; i++)
1964         {
1965           if (pass_signals[i])
1966             count++;
1967         }
1968       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1969       strcpy (pass_packet, "QPassSignals:");
1970       p = pass_packet + strlen (pass_packet);
1971       for (i = 0; i < numsigs; i++)
1972         {
1973           if (pass_signals[i])
1974             {
1975               if (i >= 16)
1976                 *p++ = tohex (i >> 4);
1977               *p++ = tohex (i & 15);
1978               if (count)
1979                 *p++ = ';';
1980               else
1981                 break;
1982               count--;
1983             }
1984         }
1985       *p = 0;
1986       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1987         {
1988           putpkt (pass_packet);
1989           getpkt (&rs->buf, &rs->buf_size, 0);
1990           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1991           if (rs->last_pass_packet)
1992             xfree (rs->last_pass_packet);
1993           rs->last_pass_packet = pass_packet;
1994         }
1995       else
1996         xfree (pass_packet);
1997     }
1998 }
1999
2000 /* If 'QCatchSyscalls' is supported, tell the remote stub
2001    to report syscalls to GDB.  */
2002
2003 static int
2004 remote_set_syscall_catchpoint (struct target_ops *self,
2005                                int pid, int needed, int any_count,
2006                                int table_size, int *table)
2007 {
2008   char *catch_packet;
2009   enum packet_result result;
2010   int n_sysno = 0;
2011
2012   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2013     {
2014       /* Not supported.  */
2015       return 1;
2016     }
2017
2018   if (needed && !any_count)
2019     {
2020       int i;
2021
2022       /* Count how many syscalls are to be caught (table[sysno] != 0).  */
2023       for (i = 0; i < table_size; i++)
2024         {
2025           if (table[i] != 0)
2026             n_sysno++;
2027         }
2028     }
2029
2030   if (remote_debug)
2031     {
2032       fprintf_unfiltered (gdb_stdlog,
2033                           "remote_set_syscall_catchpoint "
2034                           "pid %d needed %d any_count %d n_sysno %d\n",
2035                           pid, needed, any_count, n_sysno);
2036     }
2037
2038   if (needed)
2039     {
2040       /* Prepare a packet with the sysno list, assuming max 8+1
2041          characters for a sysno.  If the resulting packet size is too
2042          big, fallback on the non-selective packet.  */
2043       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2044
2045       catch_packet = (char *) xmalloc (maxpktsz);
2046       strcpy (catch_packet, "QCatchSyscalls:1");
2047       if (!any_count)
2048         {
2049           int i;
2050           char *p;
2051
2052           p = catch_packet;
2053           p += strlen (p);
2054
2055           /* Add in catch_packet each syscall to be caught (table[i] != 0).  */
2056           for (i = 0; i < table_size; i++)
2057             {
2058               if (table[i] != 0)
2059                 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2060             }
2061         }
2062       if (strlen (catch_packet) > get_remote_packet_size ())
2063         {
2064           /* catch_packet too big.  Fallback to less efficient
2065              non selective mode, with GDB doing the filtering.  */
2066           catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2067         }
2068     }
2069   else
2070     catch_packet = xstrdup ("QCatchSyscalls:0");
2071
2072   {
2073     struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2074     struct remote_state *rs = get_remote_state ();
2075
2076     putpkt (catch_packet);
2077     getpkt (&rs->buf, &rs->buf_size, 0);
2078     result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2079     do_cleanups (old_chain);
2080     if (result == PACKET_OK)
2081       return 0;
2082     else
2083       return -1;
2084   }
2085 }
2086
2087 /* If 'QProgramSignals' is supported, tell the remote stub what
2088    signals it should pass through to the inferior when detaching.  */
2089
2090 static void
2091 remote_program_signals (struct target_ops *self,
2092                         int numsigs, unsigned char *signals)
2093 {
2094   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2095     {
2096       char *packet, *p;
2097       int count = 0, i;
2098       struct remote_state *rs = get_remote_state ();
2099
2100       gdb_assert (numsigs < 256);
2101       for (i = 0; i < numsigs; i++)
2102         {
2103           if (signals[i])
2104             count++;
2105         }
2106       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2107       strcpy (packet, "QProgramSignals:");
2108       p = packet + strlen (packet);
2109       for (i = 0; i < numsigs; i++)
2110         {
2111           if (signal_pass_state (i))
2112             {
2113               if (i >= 16)
2114                 *p++ = tohex (i >> 4);
2115               *p++ = tohex (i & 15);
2116               if (count)
2117                 *p++ = ';';
2118               else
2119                 break;
2120               count--;
2121             }
2122         }
2123       *p = 0;
2124       if (!rs->last_program_signals_packet
2125           || strcmp (rs->last_program_signals_packet, packet) != 0)
2126         {
2127           putpkt (packet);
2128           getpkt (&rs->buf, &rs->buf_size, 0);
2129           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2130           xfree (rs->last_program_signals_packet);
2131           rs->last_program_signals_packet = packet;
2132         }
2133       else
2134         xfree (packet);
2135     }
2136 }
2137
2138 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2139    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2140    thread.  If GEN is set, set the general thread, if not, then set
2141    the step/continue thread.  */
2142 static void
2143 set_thread (struct ptid ptid, int gen)
2144 {
2145   struct remote_state *rs = get_remote_state ();
2146   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2147   char *buf = rs->buf;
2148   char *endbuf = rs->buf + get_remote_packet_size ();
2149
2150   if (ptid_equal (state, ptid))
2151     return;
2152
2153   *buf++ = 'H';
2154   *buf++ = gen ? 'g' : 'c';
2155   if (ptid_equal (ptid, magic_null_ptid))
2156     xsnprintf (buf, endbuf - buf, "0");
2157   else if (ptid_equal (ptid, any_thread_ptid))
2158     xsnprintf (buf, endbuf - buf, "0");
2159   else if (ptid_equal (ptid, minus_one_ptid))
2160     xsnprintf (buf, endbuf - buf, "-1");
2161   else
2162     write_ptid (buf, endbuf, ptid);
2163   putpkt (rs->buf);
2164   getpkt (&rs->buf, &rs->buf_size, 0);
2165   if (gen)
2166     rs->general_thread = ptid;
2167   else
2168     rs->continue_thread = ptid;
2169 }
2170
2171 static void
2172 set_general_thread (struct ptid ptid)
2173 {
2174   set_thread (ptid, 1);
2175 }
2176
2177 static void
2178 set_continue_thread (struct ptid ptid)
2179 {
2180   set_thread (ptid, 0);
2181 }
2182
2183 /* Change the remote current process.  Which thread within the process
2184    ends up selected isn't important, as long as it is the same process
2185    as what INFERIOR_PTID points to.
2186
2187    This comes from that fact that there is no explicit notion of
2188    "selected process" in the protocol.  The selected process for
2189    general operations is the process the selected general thread
2190    belongs to.  */
2191
2192 static void
2193 set_general_process (void)
2194 {
2195   struct remote_state *rs = get_remote_state ();
2196
2197   /* If the remote can't handle multiple processes, don't bother.  */
2198   if (!remote_multi_process_p (rs))
2199     return;
2200
2201   /* We only need to change the remote current thread if it's pointing
2202      at some other process.  */
2203   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2204     set_general_thread (inferior_ptid);
2205 }
2206
2207 \f
2208 /* Return nonzero if this is the main thread that we made up ourselves
2209    to model non-threaded targets as single-threaded.  */
2210
2211 static int
2212 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2213 {
2214   if (ptid_equal (ptid, magic_null_ptid))
2215     /* The main thread is always alive.  */
2216     return 1;
2217
2218   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2219     /* The main thread is always alive.  This can happen after a
2220        vAttach, if the remote side doesn't support
2221        multi-threading.  */
2222     return 1;
2223
2224   return 0;
2225 }
2226
2227 /* Return nonzero if the thread PTID is still alive on the remote
2228    system.  */
2229
2230 static int
2231 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2232 {
2233   struct remote_state *rs = get_remote_state ();
2234   char *p, *endp;
2235
2236   /* Check if this is a thread that we made up ourselves to model
2237      non-threaded targets as single-threaded.  */
2238   if (remote_thread_always_alive (ops, ptid))
2239     return 1;
2240
2241   p = rs->buf;
2242   endp = rs->buf + get_remote_packet_size ();
2243
2244   *p++ = 'T';
2245   write_ptid (p, endp, ptid);
2246
2247   putpkt (rs->buf);
2248   getpkt (&rs->buf, &rs->buf_size, 0);
2249   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2250 }
2251
2252 /* Return a pointer to a thread name if we know it and NULL otherwise.
2253    The thread_info object owns the memory for the name.  */
2254
2255 static const char *
2256 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2257 {
2258   if (info->priv != NULL)
2259     return info->priv->name;
2260
2261   return NULL;
2262 }
2263
2264 /* About these extended threadlist and threadinfo packets.  They are
2265    variable length packets but, the fields within them are often fixed
2266    length.  They are redundent enough to send over UDP as is the
2267    remote protocol in general.  There is a matching unit test module
2268    in libstub.  */
2269
2270 /* WARNING: This threadref data structure comes from the remote O.S.,
2271    libstub protocol encoding, and remote.c.  It is not particularly
2272    changable.  */
2273
2274 /* Right now, the internal structure is int. We want it to be bigger.
2275    Plan to fix this.  */
2276
2277 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2278
2279 /* gdb_ext_thread_info is an internal GDB data structure which is
2280    equivalent to the reply of the remote threadinfo packet.  */
2281
2282 struct gdb_ext_thread_info
2283   {
2284     threadref threadid;         /* External form of thread reference.  */
2285     int active;                 /* Has state interesting to GDB?
2286                                    regs, stack.  */
2287     char display[256];          /* Brief state display, name,
2288                                    blocked/suspended.  */
2289     char shortname[32];         /* To be used to name threads.  */
2290     char more_display[256];     /* Long info, statistics, queue depth,
2291                                    whatever.  */
2292   };
2293
2294 /* The volume of remote transfers can be limited by submitting
2295    a mask containing bits specifying the desired information.
2296    Use a union of these values as the 'selection' parameter to
2297    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2298
2299 #define TAG_THREADID 1
2300 #define TAG_EXISTS 2
2301 #define TAG_DISPLAY 4
2302 #define TAG_THREADNAME 8
2303 #define TAG_MOREDISPLAY 16
2304
2305 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2306
2307 static char *unpack_nibble (char *buf, int *val);
2308
2309 static char *unpack_byte (char *buf, int *value);
2310
2311 static char *pack_int (char *buf, int value);
2312
2313 static char *unpack_int (char *buf, int *value);
2314
2315 static char *unpack_string (char *src, char *dest, int length);
2316
2317 static char *pack_threadid (char *pkt, threadref *id);
2318
2319 static char *unpack_threadid (char *inbuf, threadref *id);
2320
2321 void int_to_threadref (threadref *id, int value);
2322
2323 static int threadref_to_int (threadref *ref);
2324
2325 static void copy_threadref (threadref *dest, threadref *src);
2326
2327 static int threadmatch (threadref *dest, threadref *src);
2328
2329 static char *pack_threadinfo_request (char *pkt, int mode,
2330                                       threadref *id);
2331
2332 static int remote_unpack_thread_info_response (char *pkt,
2333                                                threadref *expectedref,
2334                                                struct gdb_ext_thread_info
2335                                                *info);
2336
2337
2338 static int remote_get_threadinfo (threadref *threadid,
2339                                   int fieldset, /*TAG mask */
2340                                   struct gdb_ext_thread_info *info);
2341
2342 static char *pack_threadlist_request (char *pkt, int startflag,
2343                                       int threadcount,
2344                                       threadref *nextthread);
2345
2346 static int parse_threadlist_response (char *pkt,
2347                                       int result_limit,
2348                                       threadref *original_echo,
2349                                       threadref *resultlist,
2350                                       int *doneflag);
2351
2352 static int remote_get_threadlist (int startflag,
2353                                   threadref *nextthread,
2354                                   int result_limit,
2355                                   int *done,
2356                                   int *result_count,
2357                                   threadref *threadlist);
2358
2359 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2360
2361 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2362                                        void *context, int looplimit);
2363
2364 static int remote_newthread_step (threadref *ref, void *context);
2365
2366
2367 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2368    buffer we're allowed to write to.  Returns
2369    BUF+CHARACTERS_WRITTEN.  */
2370
2371 static char *
2372 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2373 {
2374   int pid, tid;
2375   struct remote_state *rs = get_remote_state ();
2376
2377   if (remote_multi_process_p (rs))
2378     {
2379       pid = ptid_get_pid (ptid);
2380       if (pid < 0)
2381         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2382       else
2383         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2384     }
2385   tid = ptid_get_lwp (ptid);
2386   if (tid < 0)
2387     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2388   else
2389     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2390
2391   return buf;
2392 }
2393
2394 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
2395    passed the last parsed char.  Returns null_ptid on error.  */
2396
2397 static ptid_t
2398 read_ptid (char *buf, char **obuf)
2399 {
2400   char *p = buf;
2401   char *pp;
2402   ULONGEST pid = 0, tid = 0;
2403
2404   if (*p == 'p')
2405     {
2406       /* Multi-process ptid.  */
2407       pp = unpack_varlen_hex (p + 1, &pid);
2408       if (*pp != '.')
2409         error (_("invalid remote ptid: %s"), p);
2410
2411       p = pp;
2412       pp = unpack_varlen_hex (p + 1, &tid);
2413       if (obuf)
2414         *obuf = pp;
2415       return ptid_build (pid, tid, 0);
2416     }
2417
2418   /* No multi-process.  Just a tid.  */
2419   pp = unpack_varlen_hex (p, &tid);
2420
2421   /* Return null_ptid when no thread id is found.  */
2422   if (p == pp)
2423     {
2424       if (obuf)
2425         *obuf = pp;
2426       return null_ptid;
2427     }
2428
2429   /* Since the stub is not sending a process id, then default to
2430      what's in inferior_ptid, unless it's null at this point.  If so,
2431      then since there's no way to know the pid of the reported
2432      threads, use the magic number.  */
2433   if (ptid_equal (inferior_ptid, null_ptid))
2434     pid = ptid_get_pid (magic_null_ptid);
2435   else
2436     pid = ptid_get_pid (inferior_ptid);
2437
2438   if (obuf)
2439     *obuf = pp;
2440   return ptid_build (pid, tid, 0);
2441 }
2442
2443 static int
2444 stubhex (int ch)
2445 {
2446   if (ch >= 'a' && ch <= 'f')
2447     return ch - 'a' + 10;
2448   if (ch >= '0' && ch <= '9')
2449     return ch - '0';
2450   if (ch >= 'A' && ch <= 'F')
2451     return ch - 'A' + 10;
2452   return -1;
2453 }
2454
2455 static int
2456 stub_unpack_int (char *buff, int fieldlength)
2457 {
2458   int nibble;
2459   int retval = 0;
2460
2461   while (fieldlength)
2462     {
2463       nibble = stubhex (*buff++);
2464       retval |= nibble;
2465       fieldlength--;
2466       if (fieldlength)
2467         retval = retval << 4;
2468     }
2469   return retval;
2470 }
2471
2472 static char *
2473 unpack_nibble (char *buf, int *val)
2474 {
2475   *val = fromhex (*buf++);
2476   return buf;
2477 }
2478
2479 static char *
2480 unpack_byte (char *buf, int *value)
2481 {
2482   *value = stub_unpack_int (buf, 2);
2483   return buf + 2;
2484 }
2485
2486 static char *
2487 pack_int (char *buf, int value)
2488 {
2489   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2490   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2491   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2492   buf = pack_hex_byte (buf, (value & 0xff));
2493   return buf;
2494 }
2495
2496 static char *
2497 unpack_int (char *buf, int *value)
2498 {
2499   *value = stub_unpack_int (buf, 8);
2500   return buf + 8;
2501 }
2502
2503 #if 0                   /* Currently unused, uncomment when needed.  */
2504 static char *pack_string (char *pkt, char *string);
2505
2506 static char *
2507 pack_string (char *pkt, char *string)
2508 {
2509   char ch;
2510   int len;
2511
2512   len = strlen (string);
2513   if (len > 200)
2514     len = 200;          /* Bigger than most GDB packets, junk???  */
2515   pkt = pack_hex_byte (pkt, len);
2516   while (len-- > 0)
2517     {
2518       ch = *string++;
2519       if ((ch == '\0') || (ch == '#'))
2520         ch = '*';               /* Protect encapsulation.  */
2521       *pkt++ = ch;
2522     }
2523   return pkt;
2524 }
2525 #endif /* 0 (unused) */
2526
2527 static char *
2528 unpack_string (char *src, char *dest, int length)
2529 {
2530   while (length--)
2531     *dest++ = *src++;
2532   *dest = '\0';
2533   return src;
2534 }
2535
2536 static char *
2537 pack_threadid (char *pkt, threadref *id)
2538 {
2539   char *limit;
2540   unsigned char *altid;
2541
2542   altid = (unsigned char *) id;
2543   limit = pkt + BUF_THREAD_ID_SIZE;
2544   while (pkt < limit)
2545     pkt = pack_hex_byte (pkt, *altid++);
2546   return pkt;
2547 }
2548
2549
2550 static char *
2551 unpack_threadid (char *inbuf, threadref *id)
2552 {
2553   char *altref;
2554   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2555   int x, y;
2556
2557   altref = (char *) id;
2558
2559   while (inbuf < limit)
2560     {
2561       x = stubhex (*inbuf++);
2562       y = stubhex (*inbuf++);
2563       *altref++ = (x << 4) | y;
2564     }
2565   return inbuf;
2566 }
2567
2568 /* Externally, threadrefs are 64 bits but internally, they are still
2569    ints.  This is due to a mismatch of specifications.  We would like
2570    to use 64bit thread references internally.  This is an adapter
2571    function.  */
2572
2573 void
2574 int_to_threadref (threadref *id, int value)
2575 {
2576   unsigned char *scan;
2577
2578   scan = (unsigned char *) id;
2579   {
2580     int i = 4;
2581     while (i--)
2582       *scan++ = 0;
2583   }
2584   *scan++ = (value >> 24) & 0xff;
2585   *scan++ = (value >> 16) & 0xff;
2586   *scan++ = (value >> 8) & 0xff;
2587   *scan++ = (value & 0xff);
2588 }
2589
2590 static int
2591 threadref_to_int (threadref *ref)
2592 {
2593   int i, value = 0;
2594   unsigned char *scan;
2595
2596   scan = *ref;
2597   scan += 4;
2598   i = 4;
2599   while (i-- > 0)
2600     value = (value << 8) | ((*scan++) & 0xff);
2601   return value;
2602 }
2603
2604 static void
2605 copy_threadref (threadref *dest, threadref *src)
2606 {
2607   int i;
2608   unsigned char *csrc, *cdest;
2609
2610   csrc = (unsigned char *) src;
2611   cdest = (unsigned char *) dest;
2612   i = 8;
2613   while (i--)
2614     *cdest++ = *csrc++;
2615 }
2616
2617 static int
2618 threadmatch (threadref *dest, threadref *src)
2619 {
2620   /* Things are broken right now, so just assume we got a match.  */
2621 #if 0
2622   unsigned char *srcp, *destp;
2623   int i, result;
2624   srcp = (char *) src;
2625   destp = (char *) dest;
2626
2627   result = 1;
2628   while (i-- > 0)
2629     result &= (*srcp++ == *destp++) ? 1 : 0;
2630   return result;
2631 #endif
2632   return 1;
2633 }
2634
2635 /*
2636    threadid:1,        # always request threadid
2637    context_exists:2,
2638    display:4,
2639    unique_name:8,
2640    more_display:16
2641  */
2642
2643 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2644
2645 static char *
2646 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2647 {
2648   *pkt++ = 'q';                         /* Info Query */
2649   *pkt++ = 'P';                         /* process or thread info */
2650   pkt = pack_int (pkt, mode);           /* mode */
2651   pkt = pack_threadid (pkt, id);        /* threadid */
2652   *pkt = '\0';                          /* terminate */
2653   return pkt;
2654 }
2655
2656 /* These values tag the fields in a thread info response packet.  */
2657 /* Tagging the fields allows us to request specific fields and to
2658    add more fields as time goes by.  */
2659
2660 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2661 #define TAG_EXISTS 2            /* Is this process defined enough to
2662                                    fetch registers and its stack?  */
2663 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2664 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2665 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2666                                    the process.  */
2667
2668 static int
2669 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2670                                     struct gdb_ext_thread_info *info)
2671 {
2672   struct remote_state *rs = get_remote_state ();
2673   int mask, length;
2674   int tag;
2675   threadref ref;
2676   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2677   int retval = 1;
2678
2679   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2680   info->active = 0;
2681   info->display[0] = '\0';
2682   info->shortname[0] = '\0';
2683   info->more_display[0] = '\0';
2684
2685   /* Assume the characters indicating the packet type have been
2686      stripped.  */
2687   pkt = unpack_int (pkt, &mask);        /* arg mask */
2688   pkt = unpack_threadid (pkt, &ref);
2689
2690   if (mask == 0)
2691     warning (_("Incomplete response to threadinfo request."));
2692   if (!threadmatch (&ref, expectedref))
2693     {                   /* This is an answer to a different request.  */
2694       warning (_("ERROR RMT Thread info mismatch."));
2695       return 0;
2696     }
2697   copy_threadref (&info->threadid, &ref);
2698
2699   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
2700
2701   /* Packets are terminated with nulls.  */
2702   while ((pkt < limit) && mask && *pkt)
2703     {
2704       pkt = unpack_int (pkt, &tag);     /* tag */
2705       pkt = unpack_byte (pkt, &length); /* length */
2706       if (!(tag & mask))                /* Tags out of synch with mask.  */
2707         {
2708           warning (_("ERROR RMT: threadinfo tag mismatch."));
2709           retval = 0;
2710           break;
2711         }
2712       if (tag == TAG_THREADID)
2713         {
2714           if (length != 16)
2715             {
2716               warning (_("ERROR RMT: length of threadid is not 16."));
2717               retval = 0;
2718               break;
2719             }
2720           pkt = unpack_threadid (pkt, &ref);
2721           mask = mask & ~TAG_THREADID;
2722           continue;
2723         }
2724       if (tag == TAG_EXISTS)
2725         {
2726           info->active = stub_unpack_int (pkt, length);
2727           pkt += length;
2728           mask = mask & ~(TAG_EXISTS);
2729           if (length > 8)
2730             {
2731               warning (_("ERROR RMT: 'exists' length too long."));
2732               retval = 0;
2733               break;
2734             }
2735           continue;
2736         }
2737       if (tag == TAG_THREADNAME)
2738         {
2739           pkt = unpack_string (pkt, &info->shortname[0], length);
2740           mask = mask & ~TAG_THREADNAME;
2741           continue;
2742         }
2743       if (tag == TAG_DISPLAY)
2744         {
2745           pkt = unpack_string (pkt, &info->display[0], length);
2746           mask = mask & ~TAG_DISPLAY;
2747           continue;
2748         }
2749       if (tag == TAG_MOREDISPLAY)
2750         {
2751           pkt = unpack_string (pkt, &info->more_display[0], length);
2752           mask = mask & ~TAG_MOREDISPLAY;
2753           continue;
2754         }
2755       warning (_("ERROR RMT: unknown thread info tag."));
2756       break;                    /* Not a tag we know about.  */
2757     }
2758   return retval;
2759 }
2760
2761 static int
2762 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2763                        struct gdb_ext_thread_info *info)
2764 {
2765   struct remote_state *rs = get_remote_state ();
2766   int result;
2767
2768   pack_threadinfo_request (rs->buf, fieldset, threadid);
2769   putpkt (rs->buf);
2770   getpkt (&rs->buf, &rs->buf_size, 0);
2771
2772   if (rs->buf[0] == '\0')
2773     return 0;
2774
2775   result = remote_unpack_thread_info_response (rs->buf + 2,
2776                                                threadid, info);
2777   return result;
2778 }
2779
2780 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2781
2782 static char *
2783 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2784                          threadref *nextthread)
2785 {
2786   *pkt++ = 'q';                 /* info query packet */
2787   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2788   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2789   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2790   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2791   *pkt = '\0';
2792   return pkt;
2793 }
2794
2795 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2796
2797 static int
2798 parse_threadlist_response (char *pkt, int result_limit,
2799                            threadref *original_echo, threadref *resultlist,
2800                            int *doneflag)
2801 {
2802   struct remote_state *rs = get_remote_state ();
2803   char *limit;
2804   int count, resultcount, done;
2805
2806   resultcount = 0;
2807   /* Assume the 'q' and 'M chars have been stripped.  */
2808   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2809   /* done parse past here */
2810   pkt = unpack_byte (pkt, &count);      /* count field */
2811   pkt = unpack_nibble (pkt, &done);
2812   /* The first threadid is the argument threadid.  */
2813   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2814   while ((count-- > 0) && (pkt < limit))
2815     {
2816       pkt = unpack_threadid (pkt, resultlist++);
2817       if (resultcount++ >= result_limit)
2818         break;
2819     }
2820   if (doneflag)
2821     *doneflag = done;
2822   return resultcount;
2823 }
2824
2825 /* Fetch the next batch of threads from the remote.  Returns -1 if the
2826    qL packet is not supported, 0 on error and 1 on success.  */
2827
2828 static int
2829 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2830                        int *done, int *result_count, threadref *threadlist)
2831 {
2832   struct remote_state *rs = get_remote_state ();
2833   int result = 1;
2834
2835   /* Trancate result limit to be smaller than the packet size.  */
2836   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2837       >= get_remote_packet_size ())
2838     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2839
2840   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2841   putpkt (rs->buf);
2842   getpkt (&rs->buf, &rs->buf_size, 0);
2843   if (*rs->buf == '\0')
2844     {
2845       /* Packet not supported.  */
2846       return -1;
2847     }
2848
2849   *result_count =
2850     parse_threadlist_response (rs->buf + 2, result_limit,
2851                                &rs->echo_nextthread, threadlist, done);
2852
2853   if (!threadmatch (&rs->echo_nextthread, nextthread))
2854     {
2855       /* FIXME: This is a good reason to drop the packet.  */
2856       /* Possably, there is a duplicate response.  */
2857       /* Possabilities :
2858          retransmit immediatly - race conditions
2859          retransmit after timeout - yes
2860          exit
2861          wait for packet, then exit
2862        */
2863       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2864       return 0;                 /* I choose simply exiting.  */
2865     }
2866   if (*result_count <= 0)
2867     {
2868       if (*done != 1)
2869         {
2870           warning (_("RMT ERROR : failed to get remote thread list."));
2871           result = 0;
2872         }
2873       return result;            /* break; */
2874     }
2875   if (*result_count > result_limit)
2876     {
2877       *result_count = 0;
2878       warning (_("RMT ERROR: threadlist response longer than requested."));
2879       return 0;
2880     }
2881   return result;
2882 }
2883
2884 /* Fetch the list of remote threads, with the qL packet, and call
2885    STEPFUNCTION for each thread found.  Stops iterating and returns 1
2886    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
2887    STEPFUNCTION returns false.  If the packet is not supported,
2888    returns -1.  */
2889
2890 static int
2891 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2892                             int looplimit)
2893 {
2894   struct remote_state *rs = get_remote_state ();
2895   int done, i, result_count;
2896   int startflag = 1;
2897   int result = 1;
2898   int loopcount = 0;
2899
2900   done = 0;
2901   while (!done)
2902     {
2903       if (loopcount++ > looplimit)
2904         {
2905           result = 0;
2906           warning (_("Remote fetch threadlist -infinite loop-."));
2907           break;
2908         }
2909       result = remote_get_threadlist (startflag, &rs->nextthread,
2910                                       MAXTHREADLISTRESULTS,
2911                                       &done, &result_count,
2912                                       rs->resultthreadlist);
2913       if (result <= 0)
2914         break;
2915       /* Clear for later iterations.  */
2916       startflag = 0;
2917       /* Setup to resume next batch of thread references, set nextthread.  */
2918       if (result_count >= 1)
2919         copy_threadref (&rs->nextthread,
2920                         &rs->resultthreadlist[result_count - 1]);
2921       i = 0;
2922       while (result_count--)
2923         {
2924           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2925             {
2926               result = 0;
2927               break;
2928             }
2929         }
2930     }
2931   return result;
2932 }
2933
2934 /* A thread found on the remote target.  */
2935
2936 typedef struct thread_item
2937 {
2938   /* The thread's PTID.  */
2939   ptid_t ptid;
2940
2941   /* The thread's extra info.  May be NULL.  */
2942   char *extra;
2943
2944   /* The thread's name.  May be NULL.  */
2945   char *name;
2946
2947   /* The core the thread was running on.  -1 if not known.  */
2948   int core;
2949 } thread_item_t;
2950 DEF_VEC_O(thread_item_t);
2951
2952 /* Context passed around to the various methods listing remote
2953    threads.  As new threads are found, they're added to the ITEMS
2954    vector.  */
2955
2956 struct threads_listing_context
2957 {
2958   /* The threads found on the remote target.  */
2959   VEC (thread_item_t) *items;
2960 };
2961
2962 /* Discard the contents of the constructed thread listing context.  */
2963
2964 static void
2965 clear_threads_listing_context (void *p)
2966 {
2967   struct threads_listing_context *context
2968     = (struct threads_listing_context *) p;
2969   int i;
2970   struct thread_item *item;
2971
2972   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2973     {
2974       xfree (item->extra);
2975       xfree (item->name);
2976     }
2977
2978   VEC_free (thread_item_t, context->items);
2979 }
2980
2981 /* Remove the thread specified as the related_pid field of WS
2982    from the CONTEXT list.  */
2983
2984 static void
2985 threads_listing_context_remove (struct target_waitstatus *ws,
2986                                 struct threads_listing_context *context)
2987 {
2988   struct thread_item *item;
2989   int i;
2990   ptid_t child_ptid = ws->value.related_pid;
2991
2992   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2993     {
2994       if (ptid_equal (item->ptid, child_ptid))
2995         {
2996           VEC_ordered_remove (thread_item_t, context->items, i);
2997           break;
2998         }
2999     }
3000 }
3001
3002 static int
3003 remote_newthread_step (threadref *ref, void *data)
3004 {
3005   struct threads_listing_context *context
3006     = (struct threads_listing_context *) data;
3007   struct thread_item item;
3008   int pid = ptid_get_pid (inferior_ptid);
3009
3010   item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3011   item.core = -1;
3012   item.name = NULL;
3013   item.extra = NULL;
3014
3015   VEC_safe_push (thread_item_t, context->items, &item);
3016
3017   return 1;                     /* continue iterator */
3018 }
3019
3020 #define CRAZY_MAX_THREADS 1000
3021
3022 static ptid_t
3023 remote_current_thread (ptid_t oldpid)
3024 {
3025   struct remote_state *rs = get_remote_state ();
3026
3027   putpkt ("qC");
3028   getpkt (&rs->buf, &rs->buf_size, 0);
3029   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3030     {
3031       char *obuf;
3032       ptid_t result;
3033
3034       result = read_ptid (&rs->buf[2], &obuf);
3035       if (*obuf != '\0' && remote_debug)
3036         fprintf_unfiltered (gdb_stdlog,
3037                             "warning: garbage in qC reply\n");
3038
3039       return result;
3040     }
3041   else
3042     return oldpid;
3043 }
3044
3045 /* List remote threads using the deprecated qL packet.  */
3046
3047 static int
3048 remote_get_threads_with_ql (struct target_ops *ops,
3049                             struct threads_listing_context *context)
3050 {
3051   if (remote_threadlist_iterator (remote_newthread_step, context,
3052                                   CRAZY_MAX_THREADS) >= 0)
3053     return 1;
3054
3055   return 0;
3056 }
3057
3058 #if defined(HAVE_LIBEXPAT)
3059
3060 static void
3061 start_thread (struct gdb_xml_parser *parser,
3062               const struct gdb_xml_element *element,
3063               void *user_data, VEC(gdb_xml_value_s) *attributes)
3064 {
3065   struct threads_listing_context *data
3066     = (struct threads_listing_context *) user_data;
3067
3068   struct thread_item item;
3069   char *id;
3070   struct gdb_xml_value *attr;
3071
3072   id = (char *) xml_find_attribute (attributes, "id")->value;
3073   item.ptid = read_ptid (id, NULL);
3074
3075   attr = xml_find_attribute (attributes, "core");
3076   if (attr != NULL)
3077     item.core = *(ULONGEST *) attr->value;
3078   else
3079     item.core = -1;
3080
3081   attr = xml_find_attribute (attributes, "name");
3082   item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3083
3084   item.extra = 0;
3085
3086   VEC_safe_push (thread_item_t, data->items, &item);
3087 }
3088
3089 static void
3090 end_thread (struct gdb_xml_parser *parser,
3091             const struct gdb_xml_element *element,
3092             void *user_data, const char *body_text)
3093 {
3094   struct threads_listing_context *data
3095     = (struct threads_listing_context *) user_data;
3096
3097   if (body_text && *body_text)
3098     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3099 }
3100
3101 const struct gdb_xml_attribute thread_attributes[] = {
3102   { "id", GDB_XML_AF_NONE, NULL, NULL },
3103   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3104   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3105   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3106 };
3107
3108 const struct gdb_xml_element thread_children[] = {
3109   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3110 };
3111
3112 const struct gdb_xml_element threads_children[] = {
3113   { "thread", thread_attributes, thread_children,
3114     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3115     start_thread, end_thread },
3116   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3117 };
3118
3119 const struct gdb_xml_element threads_elements[] = {
3120   { "threads", NULL, threads_children,
3121     GDB_XML_EF_NONE, NULL, NULL },
3122   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3123 };
3124
3125 #endif
3126
3127 /* List remote threads using qXfer:threads:read.  */
3128
3129 static int
3130 remote_get_threads_with_qxfer (struct target_ops *ops,
3131                                struct threads_listing_context *context)
3132 {
3133 #if defined(HAVE_LIBEXPAT)
3134   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3135     {
3136       char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3137       struct cleanup *back_to = make_cleanup (xfree, xml);
3138
3139       if (xml != NULL && *xml != '\0')
3140         {
3141           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3142                                threads_elements, xml, context);
3143         }
3144
3145       do_cleanups (back_to);
3146       return 1;
3147     }
3148 #endif
3149
3150   return 0;
3151 }
3152
3153 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3154
3155 static int
3156 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3157                                      struct threads_listing_context *context)
3158 {
3159   struct remote_state *rs = get_remote_state ();
3160
3161   if (rs->use_threadinfo_query)
3162     {
3163       char *bufp;
3164
3165       putpkt ("qfThreadInfo");
3166       getpkt (&rs->buf, &rs->buf_size, 0);
3167       bufp = rs->buf;
3168       if (bufp[0] != '\0')              /* q packet recognized */
3169         {
3170           while (*bufp++ == 'm')        /* reply contains one or more TID */
3171             {
3172               do
3173                 {
3174                   struct thread_item item;
3175
3176                   item.ptid = read_ptid (bufp, &bufp);
3177                   item.core = -1;
3178                   item.name = NULL;
3179                   item.extra = NULL;
3180
3181                   VEC_safe_push (thread_item_t, context->items, &item);
3182                 }
3183               while (*bufp++ == ',');   /* comma-separated list */
3184               putpkt ("qsThreadInfo");
3185               getpkt (&rs->buf, &rs->buf_size, 0);
3186               bufp = rs->buf;
3187             }
3188           return 1;
3189         }
3190       else
3191         {
3192           /* Packet not recognized.  */
3193           rs->use_threadinfo_query = 0;
3194         }
3195     }
3196
3197   return 0;
3198 }
3199
3200 /* Implement the to_update_thread_list function for the remote
3201    targets.  */
3202
3203 static void
3204 remote_update_thread_list (struct target_ops *ops)
3205 {
3206   struct threads_listing_context context;
3207   struct cleanup *old_chain;
3208   int got_list = 0;
3209
3210   context.items = NULL;
3211   old_chain = make_cleanup (clear_threads_listing_context, &context);
3212
3213   /* We have a few different mechanisms to fetch the thread list.  Try
3214      them all, starting with the most preferred one first, falling
3215      back to older methods.  */
3216   if (remote_get_threads_with_qxfer (ops, &context)
3217       || remote_get_threads_with_qthreadinfo (ops, &context)
3218       || remote_get_threads_with_ql (ops, &context))
3219     {
3220       int i;
3221       struct thread_item *item;
3222       struct thread_info *tp, *tmp;
3223
3224       got_list = 1;
3225
3226       if (VEC_empty (thread_item_t, context.items)
3227           && remote_thread_always_alive (ops, inferior_ptid))
3228         {
3229           /* Some targets don't really support threads, but still
3230              reply an (empty) thread list in response to the thread
3231              listing packets, instead of replying "packet not
3232              supported".  Exit early so we don't delete the main
3233              thread.  */
3234           do_cleanups (old_chain);
3235           return;
3236         }
3237
3238       /* CONTEXT now holds the current thread list on the remote
3239          target end.  Delete GDB-side threads no longer found on the
3240          target.  */
3241       ALL_THREADS_SAFE (tp, tmp)
3242         {
3243           for (i = 0;
3244                VEC_iterate (thread_item_t, context.items, i, item);
3245                ++i)
3246             {
3247               if (ptid_equal (item->ptid, tp->ptid))
3248                 break;
3249             }
3250
3251           if (i == VEC_length (thread_item_t, context.items))
3252             {
3253               /* Not found.  */
3254               delete_thread (tp->ptid);
3255             }
3256         }
3257
3258       /* Remove any unreported fork child threads from CONTEXT so
3259          that we don't interfere with follow fork, which is where
3260          creation of such threads is handled.  */
3261       remove_new_fork_children (&context);
3262
3263       /* And now add threads we don't know about yet to our list.  */
3264       for (i = 0;
3265            VEC_iterate (thread_item_t, context.items, i, item);
3266            ++i)
3267         {
3268           if (!ptid_equal (item->ptid, null_ptid))
3269             {
3270               struct private_thread_info *info;
3271               /* In non-stop mode, we assume new found threads are
3272                  executing until proven otherwise with a stop reply.
3273                  In all-stop, we can only get here if all threads are
3274                  stopped.  */
3275               int executing = target_is_non_stop_p () ? 1 : 0;
3276
3277               remote_notice_new_inferior (item->ptid, executing);
3278
3279               info = demand_private_info (item->ptid);
3280               info->core = item->core;
3281               info->extra = item->extra;
3282               item->extra = NULL;
3283               info->name = item->name;
3284               item->name = NULL;
3285             }
3286         }
3287     }
3288
3289   if (!got_list)
3290     {
3291       /* If no thread listing method is supported, then query whether
3292          each known thread is alive, one by one, with the T packet.
3293          If the target doesn't support threads at all, then this is a
3294          no-op.  See remote_thread_alive.  */
3295       prune_threads ();
3296     }
3297
3298   do_cleanups (old_chain);
3299 }
3300
3301 /*
3302  * Collect a descriptive string about the given thread.
3303  * The target may say anything it wants to about the thread
3304  * (typically info about its blocked / runnable state, name, etc.).
3305  * This string will appear in the info threads display.
3306  *
3307  * Optional: targets are not required to implement this function.
3308  */
3309
3310 static char *
3311 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3312 {
3313   struct remote_state *rs = get_remote_state ();
3314   int result;
3315   int set;
3316   threadref id;
3317   struct gdb_ext_thread_info threadinfo;
3318   static char display_buf[100]; /* arbitrary...  */
3319   int n = 0;                    /* position in display_buf */
3320
3321   if (rs->remote_desc == 0)             /* paranoia */
3322     internal_error (__FILE__, __LINE__,
3323                     _("remote_threads_extra_info"));
3324
3325   if (ptid_equal (tp->ptid, magic_null_ptid)
3326       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3327     /* This is the main thread which was added by GDB.  The remote
3328        server doesn't know about it.  */
3329     return NULL;
3330
3331   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3332     {
3333       struct thread_info *info = find_thread_ptid (tp->ptid);
3334
3335       if (info && info->priv)
3336         return info->priv->extra;
3337       else
3338         return NULL;
3339     }
3340
3341   if (rs->use_threadextra_query)
3342     {
3343       char *b = rs->buf;
3344       char *endb = rs->buf + get_remote_packet_size ();
3345
3346       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3347       b += strlen (b);
3348       write_ptid (b, endb, tp->ptid);
3349
3350       putpkt (rs->buf);
3351       getpkt (&rs->buf, &rs->buf_size, 0);
3352       if (rs->buf[0] != 0)
3353         {
3354           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3355           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3356           display_buf [result] = '\0';
3357           return display_buf;
3358         }
3359     }
3360
3361   /* If the above query fails, fall back to the old method.  */
3362   rs->use_threadextra_query = 0;
3363   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3364     | TAG_MOREDISPLAY | TAG_DISPLAY;
3365   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3366   if (remote_get_threadinfo (&id, set, &threadinfo))
3367     if (threadinfo.active)
3368       {
3369         if (*threadinfo.shortname)
3370           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3371                           " Name: %s,", threadinfo.shortname);
3372         if (*threadinfo.display)
3373           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3374                           " State: %s,", threadinfo.display);
3375         if (*threadinfo.more_display)
3376           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3377                           " Priority: %s", threadinfo.more_display);
3378
3379         if (n > 0)
3380           {
3381             /* For purely cosmetic reasons, clear up trailing commas.  */
3382             if (',' == display_buf[n-1])
3383               display_buf[n-1] = ' ';
3384             return display_buf;
3385           }
3386       }
3387   return NULL;
3388 }
3389 \f
3390
3391 static int
3392 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3393                                     struct static_tracepoint_marker *marker)
3394 {
3395   struct remote_state *rs = get_remote_state ();
3396   char *p = rs->buf;
3397
3398   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3399   p += strlen (p);
3400   p += hexnumstr (p, addr);
3401   putpkt (rs->buf);
3402   getpkt (&rs->buf, &rs->buf_size, 0);
3403   p = rs->buf;
3404
3405   if (*p == 'E')
3406     error (_("Remote failure reply: %s"), p);
3407
3408   if (*p++ == 'm')
3409     {
3410       parse_static_tracepoint_marker_definition (p, &p, marker);
3411       return 1;
3412     }
3413
3414   return 0;
3415 }
3416
3417 static VEC(static_tracepoint_marker_p) *
3418 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3419                                            const char *strid)
3420 {
3421   struct remote_state *rs = get_remote_state ();
3422   VEC(static_tracepoint_marker_p) *markers = NULL;
3423   struct static_tracepoint_marker *marker = NULL;
3424   struct cleanup *old_chain;
3425   char *p;
3426
3427   /* Ask for a first packet of static tracepoint marker
3428      definition.  */
3429   putpkt ("qTfSTM");
3430   getpkt (&rs->buf, &rs->buf_size, 0);
3431   p = rs->buf;
3432   if (*p == 'E')
3433     error (_("Remote failure reply: %s"), p);
3434
3435   old_chain = make_cleanup (free_current_marker, &marker);
3436
3437   while (*p++ == 'm')
3438     {
3439       if (marker == NULL)
3440         marker = XCNEW (struct static_tracepoint_marker);
3441
3442       do
3443         {
3444           parse_static_tracepoint_marker_definition (p, &p, marker);
3445
3446           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3447             {
3448               VEC_safe_push (static_tracepoint_marker_p,
3449                              markers, marker);
3450               marker = NULL;
3451             }
3452           else
3453             {
3454               release_static_tracepoint_marker (marker);
3455               memset (marker, 0, sizeof (*marker));
3456             }
3457         }
3458       while (*p++ == ',');      /* comma-separated list */
3459       /* Ask for another packet of static tracepoint definition.  */
3460       putpkt ("qTsSTM");
3461       getpkt (&rs->buf, &rs->buf_size, 0);
3462       p = rs->buf;
3463     }
3464
3465   do_cleanups (old_chain);
3466   return markers;
3467 }
3468
3469 \f
3470 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3471
3472 static ptid_t
3473 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3474 {
3475   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3476 }
3477 \f
3478
3479 /* Restart the remote side; this is an extended protocol operation.  */
3480
3481 static void
3482 extended_remote_restart (void)
3483 {
3484   struct remote_state *rs = get_remote_state ();
3485
3486   /* Send the restart command; for reasons I don't understand the
3487      remote side really expects a number after the "R".  */
3488   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3489   putpkt (rs->buf);
3490
3491   remote_fileio_reset ();
3492 }
3493 \f
3494 /* Clean up connection to a remote debugger.  */
3495
3496 static void
3497 remote_close (struct target_ops *self)
3498 {
3499   struct remote_state *rs = get_remote_state ();
3500
3501   if (rs->remote_desc == NULL)
3502     return; /* already closed */
3503
3504   /* Make sure we leave stdin registered in the event loop.  */
3505   remote_terminal_ours (self);
3506
3507   serial_close (rs->remote_desc);
3508   rs->remote_desc = NULL;
3509
3510   /* We don't have a connection to the remote stub anymore.  Get rid
3511      of all the inferiors and their threads we were controlling.
3512      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3513      will be unable to find the thread corresponding to (pid, 0, 0).  */
3514   inferior_ptid = null_ptid;
3515   discard_all_inferiors ();
3516
3517   /* We are closing the remote target, so we should discard
3518      everything of this target.  */
3519   discard_pending_stop_replies_in_queue (rs);
3520
3521   if (remote_async_inferior_event_token)
3522     delete_async_event_handler (&remote_async_inferior_event_token);
3523
3524   remote_notif_state_xfree (rs->notif_state);
3525
3526   trace_reset_local_state ();
3527 }
3528
3529 /* Query the remote side for the text, data and bss offsets.  */
3530
3531 static void
3532 get_offsets (void)
3533 {
3534   struct remote_state *rs = get_remote_state ();
3535   char *buf;
3536   char *ptr;
3537   int lose, num_segments = 0, do_sections, do_segments;
3538   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3539   struct section_offsets *offs;
3540   struct symfile_segment_data *data;
3541
3542   if (symfile_objfile == NULL)
3543     return;
3544
3545   putpkt ("qOffsets");
3546   getpkt (&rs->buf, &rs->buf_size, 0);
3547   buf = rs->buf;
3548
3549   if (buf[0] == '\000')
3550     return;                     /* Return silently.  Stub doesn't support
3551                                    this command.  */
3552   if (buf[0] == 'E')
3553     {
3554       warning (_("Remote failure reply: %s"), buf);
3555       return;
3556     }
3557
3558   /* Pick up each field in turn.  This used to be done with scanf, but
3559      scanf will make trouble if CORE_ADDR size doesn't match
3560      conversion directives correctly.  The following code will work
3561      with any size of CORE_ADDR.  */
3562   text_addr = data_addr = bss_addr = 0;
3563   ptr = buf;
3564   lose = 0;
3565
3566   if (startswith (ptr, "Text="))
3567     {
3568       ptr += 5;
3569       /* Don't use strtol, could lose on big values.  */
3570       while (*ptr && *ptr != ';')
3571         text_addr = (text_addr << 4) + fromhex (*ptr++);
3572
3573       if (startswith (ptr, ";Data="))
3574         {
3575           ptr += 6;
3576           while (*ptr && *ptr != ';')
3577             data_addr = (data_addr << 4) + fromhex (*ptr++);
3578         }
3579       else
3580         lose = 1;
3581
3582       if (!lose && startswith (ptr, ";Bss="))
3583         {
3584           ptr += 5;
3585           while (*ptr && *ptr != ';')
3586             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3587
3588           if (bss_addr != data_addr)
3589             warning (_("Target reported unsupported offsets: %s"), buf);
3590         }
3591       else
3592         lose = 1;
3593     }
3594   else if (startswith (ptr, "TextSeg="))
3595     {
3596       ptr += 8;
3597       /* Don't use strtol, could lose on big values.  */
3598       while (*ptr && *ptr != ';')
3599         text_addr = (text_addr << 4) + fromhex (*ptr++);
3600       num_segments = 1;
3601
3602       if (startswith (ptr, ";DataSeg="))
3603         {
3604           ptr += 9;
3605           while (*ptr && *ptr != ';')
3606             data_addr = (data_addr << 4) + fromhex (*ptr++);
3607           num_segments++;
3608         }
3609     }
3610   else
3611     lose = 1;
3612
3613   if (lose)
3614     error (_("Malformed response to offset query, %s"), buf);
3615   else if (*ptr != '\0')
3616     warning (_("Target reported unsupported offsets: %s"), buf);
3617
3618   offs = ((struct section_offsets *)
3619           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3620   memcpy (offs, symfile_objfile->section_offsets,
3621           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3622
3623   data = get_symfile_segment_data (symfile_objfile->obfd);
3624   do_segments = (data != NULL);
3625   do_sections = num_segments == 0;
3626
3627   if (num_segments > 0)
3628     {
3629       segments[0] = text_addr;
3630       segments[1] = data_addr;
3631     }
3632   /* If we have two segments, we can still try to relocate everything
3633      by assuming that the .text and .data offsets apply to the whole
3634      text and data segments.  Convert the offsets given in the packet
3635      to base addresses for symfile_map_offsets_to_segments.  */
3636   else if (data && data->num_segments == 2)
3637     {
3638       segments[0] = data->segment_bases[0] + text_addr;
3639       segments[1] = data->segment_bases[1] + data_addr;
3640       num_segments = 2;
3641     }
3642   /* If the object file has only one segment, assume that it is text
3643      rather than data; main programs with no writable data are rare,
3644      but programs with no code are useless.  Of course the code might
3645      have ended up in the data segment... to detect that we would need
3646      the permissions here.  */
3647   else if (data && data->num_segments == 1)
3648     {
3649       segments[0] = data->segment_bases[0] + text_addr;
3650       num_segments = 1;
3651     }
3652   /* There's no way to relocate by segment.  */
3653   else
3654     do_segments = 0;
3655
3656   if (do_segments)
3657     {
3658       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3659                                                  offs, num_segments, segments);
3660
3661       if (ret == 0 && !do_sections)
3662         error (_("Can not handle qOffsets TextSeg "
3663                  "response with this symbol file"));
3664
3665       if (ret > 0)
3666         do_sections = 0;
3667     }
3668
3669   if (data)
3670     free_symfile_segment_data (data);
3671
3672   if (do_sections)
3673     {
3674       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3675
3676       /* This is a temporary kludge to force data and bss to use the
3677          same offsets because that's what nlmconv does now.  The real
3678          solution requires changes to the stub and remote.c that I
3679          don't have time to do right now.  */
3680
3681       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3682       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3683     }
3684
3685   objfile_relocate (symfile_objfile, offs);
3686 }
3687
3688 /* Send interrupt_sequence to remote target.  */
3689 static void
3690 send_interrupt_sequence (void)
3691 {
3692   struct remote_state *rs = get_remote_state ();
3693
3694   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3695     remote_serial_write ("\x03", 1);
3696   else if (interrupt_sequence_mode == interrupt_sequence_break)
3697     serial_send_break (rs->remote_desc);
3698   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3699     {
3700       serial_send_break (rs->remote_desc);
3701       remote_serial_write ("g", 1);
3702     }
3703   else
3704     internal_error (__FILE__, __LINE__,
3705                     _("Invalid value for interrupt_sequence_mode: %s."),
3706                     interrupt_sequence_mode);
3707 }
3708
3709
3710 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3711    and extract the PTID.  Returns NULL_PTID if not found.  */
3712
3713 static ptid_t
3714 stop_reply_extract_thread (char *stop_reply)
3715 {
3716   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3717     {
3718       char *p;
3719
3720       /* Txx r:val ; r:val (...)  */
3721       p = &stop_reply[3];
3722
3723       /* Look for "register" named "thread".  */
3724       while (*p != '\0')
3725         {
3726           char *p1;
3727
3728           p1 = strchr (p, ':');
3729           if (p1 == NULL)
3730             return null_ptid;
3731
3732           if (strncmp (p, "thread", p1 - p) == 0)
3733             return read_ptid (++p1, &p);
3734
3735           p1 = strchr (p, ';');
3736           if (p1 == NULL)
3737             return null_ptid;
3738           p1++;
3739
3740           p = p1;
3741         }
3742     }
3743
3744   return null_ptid;
3745 }
3746
3747 /* Determine the remote side's current thread.  If we have a stop
3748    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3749    "thread" register we can extract the current thread from.  If not,
3750    ask the remote which is the current thread with qC.  The former
3751    method avoids a roundtrip.  */
3752
3753 static ptid_t
3754 get_current_thread (char *wait_status)
3755 {
3756   ptid_t ptid = null_ptid;
3757
3758   /* Note we don't use remote_parse_stop_reply as that makes use of
3759      the target architecture, which we haven't yet fully determined at
3760      this point.  */
3761   if (wait_status != NULL)
3762     ptid = stop_reply_extract_thread (wait_status);
3763   if (ptid_equal (ptid, null_ptid))
3764     ptid = remote_current_thread (inferior_ptid);
3765
3766   return ptid;
3767 }
3768
3769 /* Query the remote target for which is the current thread/process,
3770    add it to our tables, and update INFERIOR_PTID.  The caller is
3771    responsible for setting the state such that the remote end is ready
3772    to return the current thread.
3773
3774    This function is called after handling the '?' or 'vRun' packets,
3775    whose response is a stop reply from which we can also try
3776    extracting the thread.  If the target doesn't support the explicit
3777    qC query, we infer the current thread from that stop reply, passed
3778    in in WAIT_STATUS, which may be NULL.  */
3779
3780 static void
3781 add_current_inferior_and_thread (char *wait_status)
3782 {
3783   struct remote_state *rs = get_remote_state ();
3784   int fake_pid_p = 0;
3785   ptid_t ptid;
3786
3787   inferior_ptid = null_ptid;
3788
3789   /* Now, if we have thread information, update inferior_ptid.  */
3790   ptid = get_current_thread (wait_status);
3791
3792   if (!ptid_equal (ptid, null_ptid))
3793     {
3794       if (!remote_multi_process_p (rs))
3795         fake_pid_p = 1;
3796
3797       inferior_ptid = ptid;
3798     }
3799   else
3800     {
3801       /* Without this, some commands which require an active target
3802          (such as kill) won't work.  This variable serves (at least)
3803          double duty as both the pid of the target process (if it has
3804          such), and as a flag indicating that a target is active.  */
3805       inferior_ptid = magic_null_ptid;
3806       fake_pid_p = 1;
3807     }
3808
3809   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3810
3811   /* Add the main thread.  */
3812   add_thread_silent (inferior_ptid);
3813 }
3814
3815 /* Print info about a thread that was found already stopped on
3816    connection.  */
3817
3818 static void
3819 print_one_stopped_thread (struct thread_info *thread)
3820 {
3821   struct target_waitstatus *ws = &thread->suspend.waitstatus;
3822
3823   switch_to_thread (thread->ptid);
3824   stop_pc = get_frame_pc (get_current_frame ());
3825   set_current_sal_from_frame (get_current_frame ());
3826
3827   thread->suspend.waitstatus_pending_p = 0;
3828
3829   if (ws->kind == TARGET_WAITKIND_STOPPED)
3830     {
3831       enum gdb_signal sig = ws->value.sig;
3832
3833       if (signal_print_state (sig))
3834         observer_notify_signal_received (sig);
3835     }
3836   observer_notify_normal_stop (NULL, 1);
3837 }
3838
3839 /* Process all initial stop replies the remote side sent in response
3840    to the ? packet.  These indicate threads that were already stopped
3841    on initial connection.  We mark these threads as stopped and print
3842    their current frame before giving the user the prompt.  */
3843
3844 static void
3845 process_initial_stop_replies (int from_tty)
3846 {
3847   int pending_stop_replies = stop_reply_queue_length ();
3848   struct inferior *inf;
3849   struct thread_info *thread;
3850   struct thread_info *selected = NULL;
3851   struct thread_info *lowest_stopped = NULL;
3852   struct thread_info *first = NULL;
3853
3854   /* Consume the initial pending events.  */
3855   while (pending_stop_replies-- > 0)
3856     {
3857       ptid_t waiton_ptid = minus_one_ptid;
3858       ptid_t event_ptid;
3859       struct target_waitstatus ws;
3860       int ignore_event = 0;
3861       struct thread_info *thread;
3862
3863       memset (&ws, 0, sizeof (ws));
3864       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3865       if (remote_debug)
3866         print_target_wait_results (waiton_ptid, event_ptid, &ws);
3867
3868       switch (ws.kind)
3869         {
3870         case TARGET_WAITKIND_IGNORE:
3871         case TARGET_WAITKIND_NO_RESUMED:
3872         case TARGET_WAITKIND_SIGNALLED:
3873         case TARGET_WAITKIND_EXITED:
3874           /* We shouldn't see these, but if we do, just ignore.  */
3875           if (remote_debug)
3876             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3877           ignore_event = 1;
3878           break;
3879
3880         case TARGET_WAITKIND_EXECD:
3881           xfree (ws.value.execd_pathname);
3882           break;
3883         default:
3884           break;
3885         }
3886
3887       if (ignore_event)
3888         continue;
3889
3890       thread = find_thread_ptid (event_ptid);
3891
3892       if (ws.kind == TARGET_WAITKIND_STOPPED)
3893         {
3894           enum gdb_signal sig = ws.value.sig;
3895
3896           /* Stubs traditionally report SIGTRAP as initial signal,
3897              instead of signal 0.  Suppress it.  */
3898           if (sig == GDB_SIGNAL_TRAP)
3899             sig = GDB_SIGNAL_0;
3900           thread->suspend.stop_signal = sig;
3901           ws.value.sig = sig;
3902         }
3903
3904       thread->suspend.waitstatus = ws;
3905
3906       if (ws.kind != TARGET_WAITKIND_STOPPED
3907           || ws.value.sig != GDB_SIGNAL_0)
3908         thread->suspend.waitstatus_pending_p = 1;
3909
3910       set_executing (event_ptid, 0);
3911       set_running (event_ptid, 0);
3912     }
3913
3914   /* "Notice" the new inferiors before anything related to
3915      registers/memory.  */
3916   ALL_INFERIORS (inf)
3917     {
3918       if (inf->pid == 0)
3919         continue;
3920
3921       inf->needs_setup = 1;
3922
3923       if (non_stop)
3924         {
3925           thread = any_live_thread_of_process (inf->pid);
3926           notice_new_inferior (thread->ptid,
3927                                thread->state == THREAD_RUNNING,
3928                                from_tty);
3929         }
3930     }
3931
3932   /* If all-stop on top of non-stop, pause all threads.  Note this
3933      records the threads' stop pc, so must be done after "noticing"
3934      the inferiors.  */
3935   if (!non_stop)
3936     {
3937       stop_all_threads ();
3938
3939       /* If all threads of an inferior were already stopped, we
3940          haven't setup the inferior yet.  */
3941       ALL_INFERIORS (inf)
3942         {
3943           if (inf->pid == 0)
3944             continue;
3945
3946           if (inf->needs_setup)
3947             {
3948               thread = any_live_thread_of_process (inf->pid);
3949               switch_to_thread_no_regs (thread);
3950               setup_inferior (0);
3951             }
3952         }
3953     }
3954
3955   /* Now go over all threads that are stopped, and print their current
3956      frame.  If all-stop, then if there's a signalled thread, pick
3957      that as current.  */
3958   ALL_NON_EXITED_THREADS (thread)
3959     {
3960       if (first == NULL)
3961         first = thread;
3962
3963       if (!non_stop)
3964         set_running (thread->ptid, 0);
3965       else if (thread->state != THREAD_STOPPED)
3966         continue;
3967
3968       if (selected == NULL
3969           && thread->suspend.waitstatus_pending_p)
3970         selected = thread;
3971
3972       if (lowest_stopped == NULL
3973           || thread->inf->num < lowest_stopped->inf->num
3974           || thread->per_inf_num < lowest_stopped->per_inf_num)
3975         lowest_stopped = thread;
3976
3977       if (non_stop)
3978         print_one_stopped_thread (thread);
3979     }
3980
3981   /* In all-stop, we only print the status of one thread, and leave
3982      others with their status pending.  */
3983   if (!non_stop)
3984     {
3985       thread = selected;
3986       if (thread == NULL)
3987         thread = lowest_stopped;
3988       if (thread == NULL)
3989         thread = first;
3990
3991       print_one_stopped_thread (thread);
3992     }
3993
3994   /* For "info program".  */
3995   thread = inferior_thread ();
3996   if (thread->state == THREAD_STOPPED)
3997     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
3998 }
3999
4000 /* Start the remote connection and sync state.  */
4001
4002 static void
4003 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4004 {
4005   struct remote_state *rs = get_remote_state ();
4006   struct packet_config *noack_config;
4007   char *wait_status = NULL;
4008
4009   /* Signal other parts that we're going through the initial setup,
4010      and so things may not be stable yet.  E.g., we don't try to
4011      install tracepoints until we've relocated symbols.  Also, a
4012      Ctrl-C before we're connected and synced up can't interrupt the
4013      target.  Instead, it offers to drop the (potentially wedged)
4014      connection.  */
4015   rs->starting_up = 1;
4016
4017   QUIT;
4018
4019   if (interrupt_on_connect)
4020     send_interrupt_sequence ();
4021
4022   /* Ack any packet which the remote side has already sent.  */
4023   remote_serial_write ("+", 1);
4024
4025   /* The first packet we send to the target is the optional "supported
4026      packets" request.  If the target can answer this, it will tell us
4027      which later probes to skip.  */
4028   remote_query_supported ();
4029
4030   /* If the stub wants to get a QAllow, compose one and send it.  */
4031   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4032     remote_set_permissions (target);
4033
4034   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4035      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
4036      as a reply to known packet.  For packet "vFile:setfs:" it is an
4037      invalid reply and GDB would return error in
4038      remote_hostio_set_filesystem, making remote files access impossible.
4039      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
4040      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
4041   {
4042     const char v_mustreplyempty[] = "vMustReplyEmpty";
4043
4044     putpkt (v_mustreplyempty);
4045     getpkt (&rs->buf, &rs->buf_size, 0);
4046     if (strcmp (rs->buf, "OK") == 0)
4047       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4048     else if (strcmp (rs->buf, "") != 0)
4049       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4050              rs->buf);
4051   }
4052
4053   /* Next, we possibly activate noack mode.
4054
4055      If the QStartNoAckMode packet configuration is set to AUTO,
4056      enable noack mode if the stub reported a wish for it with
4057      qSupported.
4058
4059      If set to TRUE, then enable noack mode even if the stub didn't
4060      report it in qSupported.  If the stub doesn't reply OK, the
4061      session ends with an error.
4062
4063      If FALSE, then don't activate noack mode, regardless of what the
4064      stub claimed should be the default with qSupported.  */
4065
4066   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4067   if (packet_config_support (noack_config) != PACKET_DISABLE)
4068     {
4069       putpkt ("QStartNoAckMode");
4070       getpkt (&rs->buf, &rs->buf_size, 0);
4071       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4072         rs->noack_mode = 1;
4073     }
4074
4075   if (extended_p)
4076     {
4077       /* Tell the remote that we are using the extended protocol.  */
4078       putpkt ("!");
4079       getpkt (&rs->buf, &rs->buf_size, 0);
4080     }
4081
4082   /* Let the target know which signals it is allowed to pass down to
4083      the program.  */
4084   update_signals_program_target ();
4085
4086   /* Next, if the target can specify a description, read it.  We do
4087      this before anything involving memory or registers.  */
4088   target_find_description ();
4089
4090   /* Next, now that we know something about the target, update the
4091      address spaces in the program spaces.  */
4092   update_address_spaces ();
4093
4094   /* On OSs where the list of libraries is global to all
4095      processes, we fetch them early.  */
4096   if (gdbarch_has_global_solist (target_gdbarch ()))
4097     solib_add (NULL, from_tty, target, auto_solib_add);
4098
4099   if (target_is_non_stop_p ())
4100     {
4101       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4102         error (_("Non-stop mode requested, but remote "
4103                  "does not support non-stop"));
4104
4105       putpkt ("QNonStop:1");
4106       getpkt (&rs->buf, &rs->buf_size, 0);
4107
4108       if (strcmp (rs->buf, "OK") != 0)
4109         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4110
4111       /* Find about threads and processes the stub is already
4112          controlling.  We default to adding them in the running state.
4113          The '?' query below will then tell us about which threads are
4114          stopped.  */
4115       remote_update_thread_list (target);
4116     }
4117   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4118     {
4119       /* Don't assume that the stub can operate in all-stop mode.
4120          Request it explicitly.  */
4121       putpkt ("QNonStop:0");
4122       getpkt (&rs->buf, &rs->buf_size, 0);
4123
4124       if (strcmp (rs->buf, "OK") != 0)
4125         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4126     }
4127
4128   /* Upload TSVs regardless of whether the target is running or not.  The
4129      remote stub, such as GDBserver, may have some predefined or builtin
4130      TSVs, even if the target is not running.  */
4131   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4132     {
4133       struct uploaded_tsv *uploaded_tsvs = NULL;
4134
4135       remote_upload_trace_state_variables (target, &uploaded_tsvs);
4136       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4137     }
4138
4139   /* Check whether the target is running now.  */
4140   putpkt ("?");
4141   getpkt (&rs->buf, &rs->buf_size, 0);
4142
4143   if (!target_is_non_stop_p ())
4144     {
4145       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4146         {
4147           if (!extended_p)
4148             error (_("The target is not running (try extended-remote?)"));
4149
4150           /* We're connected, but not running.  Drop out before we
4151              call start_remote.  */
4152           rs->starting_up = 0;
4153           return;
4154         }
4155       else
4156         {
4157           /* Save the reply for later.  */
4158           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4159           strcpy (wait_status, rs->buf);
4160         }
4161
4162       /* Fetch thread list.  */
4163       target_update_thread_list ();
4164
4165       /* Let the stub know that we want it to return the thread.  */
4166       set_continue_thread (minus_one_ptid);
4167
4168       if (thread_count () == 0)
4169         {
4170           /* Target has no concept of threads at all.  GDB treats
4171              non-threaded target as single-threaded; add a main
4172              thread.  */
4173           add_current_inferior_and_thread (wait_status);
4174         }
4175       else
4176         {
4177           /* We have thread information; select the thread the target
4178              says should be current.  If we're reconnecting to a
4179              multi-threaded program, this will ideally be the thread
4180              that last reported an event before GDB disconnected.  */
4181           inferior_ptid = get_current_thread (wait_status);
4182           if (ptid_equal (inferior_ptid, null_ptid))
4183             {
4184               /* Odd... The target was able to list threads, but not
4185                  tell us which thread was current (no "thread"
4186                  register in T stop reply?).  Just pick the first
4187                  thread in the thread list then.  */
4188               
4189               if (remote_debug)
4190                 fprintf_unfiltered (gdb_stdlog,
4191                                     "warning: couldn't determine remote "
4192                                     "current thread; picking first in list.\n");
4193
4194               inferior_ptid = thread_list->ptid;
4195             }
4196         }
4197
4198       /* init_wait_for_inferior should be called before get_offsets in order
4199          to manage `inserted' flag in bp loc in a correct state.
4200          breakpoint_init_inferior, called from init_wait_for_inferior, set
4201          `inserted' flag to 0, while before breakpoint_re_set, called from
4202          start_remote, set `inserted' flag to 1.  In the initialization of
4203          inferior, breakpoint_init_inferior should be called first, and then
4204          breakpoint_re_set can be called.  If this order is broken, state of
4205          `inserted' flag is wrong, and cause some problems on breakpoint
4206          manipulation.  */
4207       init_wait_for_inferior ();
4208
4209       get_offsets ();           /* Get text, data & bss offsets.  */
4210
4211       /* If we could not find a description using qXfer, and we know
4212          how to do it some other way, try again.  This is not
4213          supported for non-stop; it could be, but it is tricky if
4214          there are no stopped threads when we connect.  */
4215       if (remote_read_description_p (target)
4216           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4217         {
4218           target_clear_description ();
4219           target_find_description ();
4220         }
4221
4222       /* Use the previously fetched status.  */
4223       gdb_assert (wait_status != NULL);
4224       strcpy (rs->buf, wait_status);
4225       rs->cached_wait_status = 1;
4226
4227       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4228     }
4229   else
4230     {
4231       /* Clear WFI global state.  Do this before finding about new
4232          threads and inferiors, and setting the current inferior.
4233          Otherwise we would clear the proceed status of the current
4234          inferior when we want its stop_soon state to be preserved
4235          (see notice_new_inferior).  */
4236       init_wait_for_inferior ();
4237
4238       /* In non-stop, we will either get an "OK", meaning that there
4239          are no stopped threads at this time; or, a regular stop
4240          reply.  In the latter case, there may be more than one thread
4241          stopped --- we pull them all out using the vStopped
4242          mechanism.  */
4243       if (strcmp (rs->buf, "OK") != 0)
4244         {
4245           struct notif_client *notif = &notif_client_stop;
4246
4247           /* remote_notif_get_pending_replies acks this one, and gets
4248              the rest out.  */
4249           rs->notif_state->pending_event[notif_client_stop.id]
4250             = remote_notif_parse (notif, rs->buf);
4251           remote_notif_get_pending_events (notif);
4252         }
4253
4254       if (thread_count () == 0)
4255         {
4256           if (!extended_p)
4257             error (_("The target is not running (try extended-remote?)"));
4258
4259           /* We're connected, but not running.  Drop out before we
4260              call start_remote.  */
4261           rs->starting_up = 0;
4262           return;
4263         }
4264
4265       /* In non-stop mode, any cached wait status will be stored in
4266          the stop reply queue.  */
4267       gdb_assert (wait_status == NULL);
4268
4269       /* Report all signals during attach/startup.  */
4270       remote_pass_signals (target, 0, NULL);
4271
4272       /* If there are already stopped threads, mark them stopped and
4273          report their stops before giving the prompt to the user.  */
4274       process_initial_stop_replies (from_tty);
4275
4276       if (target_can_async_p ())
4277         target_async (1);
4278     }
4279
4280   /* If we connected to a live target, do some additional setup.  */
4281   if (target_has_execution)
4282     {
4283       if (symfile_objfile)      /* No use without a symbol-file.  */
4284         remote_check_symbols ();
4285     }
4286
4287   /* Possibly the target has been engaged in a trace run started
4288      previously; find out where things are at.  */
4289   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4290     {
4291       struct uploaded_tp *uploaded_tps = NULL;
4292
4293       if (current_trace_status ()->running)
4294         printf_filtered (_("Trace is already running on the target.\n"));
4295
4296       remote_upload_tracepoints (target, &uploaded_tps);
4297
4298       merge_uploaded_tracepoints (&uploaded_tps);
4299     }
4300
4301   /* The thread and inferior lists are now synchronized with the
4302      target, our symbols have been relocated, and we're merged the
4303      target's tracepoints with ours.  We're done with basic start
4304      up.  */
4305   rs->starting_up = 0;
4306
4307   /* Maybe breakpoints are global and need to be inserted now.  */
4308   if (breakpoints_should_be_inserted_now ())
4309     insert_breakpoints ();
4310 }
4311
4312 /* Open a connection to a remote debugger.
4313    NAME is the filename used for communication.  */
4314
4315 static void
4316 remote_open (const char *name, int from_tty)
4317 {
4318   remote_open_1 (name, from_tty, &remote_ops, 0);
4319 }
4320
4321 /* Open a connection to a remote debugger using the extended
4322    remote gdb protocol.  NAME is the filename used for communication.  */
4323
4324 static void
4325 extended_remote_open (const char *name, int from_tty)
4326 {
4327   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4328 }
4329
4330 /* Reset all packets back to "unknown support".  Called when opening a
4331    new connection to a remote target.  */
4332
4333 static void
4334 reset_all_packet_configs_support (void)
4335 {
4336   int i;
4337
4338   for (i = 0; i < PACKET_MAX; i++)
4339     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4340 }
4341
4342 /* Initialize all packet configs.  */
4343
4344 static void
4345 init_all_packet_configs (void)
4346 {
4347   int i;
4348
4349   for (i = 0; i < PACKET_MAX; i++)
4350     {
4351       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4352       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4353     }
4354 }
4355
4356 /* Symbol look-up.  */
4357
4358 static void
4359 remote_check_symbols (void)
4360 {
4361   struct remote_state *rs = get_remote_state ();
4362   char *msg, *reply, *tmp;
4363   int end;
4364   long reply_size;
4365   struct cleanup *old_chain;
4366
4367   /* The remote side has no concept of inferiors that aren't running
4368      yet, it only knows about running processes.  If we're connected
4369      but our current inferior is not running, we should not invite the
4370      remote target to request symbol lookups related to its
4371      (unrelated) current process.  */
4372   if (!target_has_execution)
4373     return;
4374
4375   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4376     return;
4377
4378   /* Make sure the remote is pointing at the right process.  Note
4379      there's no way to select "no process".  */
4380   set_general_process ();
4381
4382   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4383      because we need both at the same time.  */
4384   msg = (char *) xmalloc (get_remote_packet_size ());
4385   old_chain = make_cleanup (xfree, msg);
4386   reply = (char *) xmalloc (get_remote_packet_size ());
4387   make_cleanup (free_current_contents, &reply);
4388   reply_size = get_remote_packet_size ();
4389
4390   /* Invite target to request symbol lookups.  */
4391
4392   putpkt ("qSymbol::");
4393   getpkt (&reply, &reply_size, 0);
4394   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4395
4396   while (startswith (reply, "qSymbol:"))
4397     {
4398       struct bound_minimal_symbol sym;
4399
4400       tmp = &reply[8];
4401       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4402       msg[end] = '\0';
4403       sym = lookup_minimal_symbol (msg, NULL, NULL);
4404       if (sym.minsym == NULL)
4405         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4406       else
4407         {
4408           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4409           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4410
4411           /* If this is a function address, return the start of code
4412              instead of any data function descriptor.  */
4413           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4414                                                          sym_addr,
4415                                                          &current_target);
4416
4417           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4418                      phex_nz (sym_addr, addr_size), &reply[8]);
4419         }
4420   
4421       putpkt (msg);
4422       getpkt (&reply, &reply_size, 0);
4423     }
4424
4425   do_cleanups (old_chain);
4426 }
4427
4428 static struct serial *
4429 remote_serial_open (const char *name)
4430 {
4431   static int udp_warning = 0;
4432
4433   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4434      of in ser-tcp.c, because it is the remote protocol assuming that the
4435      serial connection is reliable and not the serial connection promising
4436      to be.  */
4437   if (!udp_warning && startswith (name, "udp:"))
4438     {
4439       warning (_("The remote protocol may be unreliable over UDP.\n"
4440                  "Some events may be lost, rendering further debugging "
4441                  "impossible."));
4442       udp_warning = 1;
4443     }
4444
4445   return serial_open (name);
4446 }
4447
4448 /* Inform the target of our permission settings.  The permission flags
4449    work without this, but if the target knows the settings, it can do
4450    a couple things.  First, it can add its own check, to catch cases
4451    that somehow manage to get by the permissions checks in target
4452    methods.  Second, if the target is wired to disallow particular
4453    settings (for instance, a system in the field that is not set up to
4454    be able to stop at a breakpoint), it can object to any unavailable
4455    permissions.  */
4456
4457 void
4458 remote_set_permissions (struct target_ops *self)
4459 {
4460   struct remote_state *rs = get_remote_state ();
4461
4462   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4463              "WriteReg:%x;WriteMem:%x;"
4464              "InsertBreak:%x;InsertTrace:%x;"
4465              "InsertFastTrace:%x;Stop:%x",
4466              may_write_registers, may_write_memory,
4467              may_insert_breakpoints, may_insert_tracepoints,
4468              may_insert_fast_tracepoints, may_stop);
4469   putpkt (rs->buf);
4470   getpkt (&rs->buf, &rs->buf_size, 0);
4471
4472   /* If the target didn't like the packet, warn the user.  Do not try
4473      to undo the user's settings, that would just be maddening.  */
4474   if (strcmp (rs->buf, "OK") != 0)
4475     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4476 }
4477
4478 /* This type describes each known response to the qSupported
4479    packet.  */
4480 struct protocol_feature
4481 {
4482   /* The name of this protocol feature.  */
4483   const char *name;
4484
4485   /* The default for this protocol feature.  */
4486   enum packet_support default_support;
4487
4488   /* The function to call when this feature is reported, or after
4489      qSupported processing if the feature is not supported.
4490      The first argument points to this structure.  The second
4491      argument indicates whether the packet requested support be
4492      enabled, disabled, or probed (or the default, if this function
4493      is being called at the end of processing and this feature was
4494      not reported).  The third argument may be NULL; if not NULL, it
4495      is a NUL-terminated string taken from the packet following
4496      this feature's name and an equals sign.  */
4497   void (*func) (const struct protocol_feature *, enum packet_support,
4498                 const char *);
4499
4500   /* The corresponding packet for this feature.  Only used if
4501      FUNC is remote_supported_packet.  */
4502   int packet;
4503 };
4504
4505 static void
4506 remote_supported_packet (const struct protocol_feature *feature,
4507                          enum packet_support support,
4508                          const char *argument)
4509 {
4510   if (argument)
4511     {
4512       warning (_("Remote qSupported response supplied an unexpected value for"
4513                  " \"%s\"."), feature->name);
4514       return;
4515     }
4516
4517   remote_protocol_packets[feature->packet].support = support;
4518 }
4519
4520 static void
4521 remote_packet_size (const struct protocol_feature *feature,
4522                     enum packet_support support, const char *value)
4523 {
4524   struct remote_state *rs = get_remote_state ();
4525
4526   int packet_size;
4527   char *value_end;
4528
4529   if (support != PACKET_ENABLE)
4530     return;
4531
4532   if (value == NULL || *value == '\0')
4533     {
4534       warning (_("Remote target reported \"%s\" without a size."),
4535                feature->name);
4536       return;
4537     }
4538
4539   errno = 0;
4540   packet_size = strtol (value, &value_end, 16);
4541   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4542     {
4543       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4544                feature->name, value);
4545       return;
4546     }
4547
4548   /* Record the new maximum packet size.  */
4549   rs->explicit_packet_size = packet_size;
4550 }
4551
4552 static const struct protocol_feature remote_protocol_features[] = {
4553   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4554   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4555     PACKET_qXfer_auxv },
4556   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4557     PACKET_qXfer_exec_file },
4558   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4559     PACKET_qXfer_features },
4560   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4561     PACKET_qXfer_libraries },
4562   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4563     PACKET_qXfer_libraries_svr4 },
4564   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4565     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4566   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4567     PACKET_qXfer_memory_map },
4568   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4569     PACKET_qXfer_spu_read },
4570   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4571     PACKET_qXfer_spu_write },
4572   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4573     PACKET_qXfer_osdata },
4574   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4575     PACKET_qXfer_threads },
4576   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4577     PACKET_qXfer_traceframe_info },
4578   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4579     PACKET_QPassSignals },
4580   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4581     PACKET_QCatchSyscalls },
4582   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4583     PACKET_QProgramSignals },
4584   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4585     PACKET_QStartNoAckMode },
4586   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4587     PACKET_multiprocess_feature },
4588   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4589   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4590     PACKET_qXfer_siginfo_read },
4591   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4592     PACKET_qXfer_siginfo_write },
4593   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4594     PACKET_ConditionalTracepoints },
4595   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4596     PACKET_ConditionalBreakpoints },
4597   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4598     PACKET_BreakpointCommands },
4599   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4600     PACKET_FastTracepoints },
4601   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4602     PACKET_StaticTracepoints },
4603   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4604    PACKET_InstallInTrace},
4605   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4606     PACKET_DisconnectedTracing_feature },
4607   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4608     PACKET_bc },
4609   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4610     PACKET_bs },
4611   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4612     PACKET_TracepointSource },
4613   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4614     PACKET_QAllow },
4615   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4616     PACKET_EnableDisableTracepoints_feature },
4617   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4618     PACKET_qXfer_fdpic },
4619   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4620     PACKET_qXfer_uib },
4621   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4622     PACKET_QDisableRandomization },
4623   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4624   { "QTBuffer:size", PACKET_DISABLE,
4625     remote_supported_packet, PACKET_QTBuffer_size},
4626   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4627   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4628   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4629   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4630   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4631     PACKET_qXfer_btrace },
4632   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4633     PACKET_qXfer_btrace_conf },
4634   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4635     PACKET_Qbtrace_conf_bts_size },
4636   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4637   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4638   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4639     PACKET_fork_event_feature },
4640   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4641     PACKET_vfork_event_feature },
4642   { "exec-events", PACKET_DISABLE, remote_supported_packet,
4643     PACKET_exec_event_feature },
4644   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4645     PACKET_Qbtrace_conf_pt_size },
4646   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4647   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4648   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4649 };
4650
4651 static char *remote_support_xml;
4652
4653 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4654
4655 void
4656 register_remote_support_xml (const char *xml)
4657 {
4658 #if defined(HAVE_LIBEXPAT)
4659   if (remote_support_xml == NULL)
4660     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4661   else
4662     {
4663       char *copy = xstrdup (remote_support_xml + 13);
4664       char *p = strtok (copy, ",");
4665
4666       do
4667         {
4668           if (strcmp (p, xml) == 0)
4669             {
4670               /* already there */
4671               xfree (copy);
4672               return;
4673             }
4674         }
4675       while ((p = strtok (NULL, ",")) != NULL);
4676       xfree (copy);
4677
4678       remote_support_xml = reconcat (remote_support_xml,
4679                                      remote_support_xml, ",", xml,
4680                                      (char *) NULL);
4681     }
4682 #endif
4683 }
4684
4685 static char *
4686 remote_query_supported_append (char *msg, const char *append)
4687 {
4688   if (msg)
4689     return reconcat (msg, msg, ";", append, (char *) NULL);
4690   else
4691     return xstrdup (append);
4692 }
4693
4694 static void
4695 remote_query_supported (void)
4696 {
4697   struct remote_state *rs = get_remote_state ();
4698   char *next;
4699   int i;
4700   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4701
4702   /* The packet support flags are handled differently for this packet
4703      than for most others.  We treat an error, a disabled packet, and
4704      an empty response identically: any features which must be reported
4705      to be used will be automatically disabled.  An empty buffer
4706      accomplishes this, since that is also the representation for a list
4707      containing no features.  */
4708
4709   rs->buf[0] = 0;
4710   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4711     {
4712       char *q = NULL;
4713       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4714
4715       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4716         q = remote_query_supported_append (q, "multiprocess+");
4717
4718       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4719         q = remote_query_supported_append (q, "swbreak+");
4720       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4721         q = remote_query_supported_append (q, "hwbreak+");
4722
4723       q = remote_query_supported_append (q, "qRelocInsn+");
4724
4725       if (packet_set_cmd_state (PACKET_fork_event_feature)
4726           != AUTO_BOOLEAN_FALSE)
4727         q = remote_query_supported_append (q, "fork-events+");
4728       if (packet_set_cmd_state (PACKET_vfork_event_feature)
4729           != AUTO_BOOLEAN_FALSE)
4730         q = remote_query_supported_append (q, "vfork-events+");
4731       if (packet_set_cmd_state (PACKET_exec_event_feature)
4732           != AUTO_BOOLEAN_FALSE)
4733         q = remote_query_supported_append (q, "exec-events+");
4734
4735       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4736         q = remote_query_supported_append (q, "vContSupported+");
4737
4738       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4739         q = remote_query_supported_append (q, "QThreadEvents+");
4740
4741       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4742         q = remote_query_supported_append (q, "no-resumed+");
4743
4744       /* Keep this one last to work around a gdbserver <= 7.10 bug in
4745          the qSupported:xmlRegisters=i386 handling.  */
4746       if (remote_support_xml != NULL)
4747         q = remote_query_supported_append (q, remote_support_xml);
4748
4749       q = reconcat (q, "qSupported:", q, (char *) NULL);
4750       putpkt (q);
4751
4752       do_cleanups (old_chain);
4753
4754       getpkt (&rs->buf, &rs->buf_size, 0);
4755
4756       /* If an error occured, warn, but do not return - just reset the
4757          buffer to empty and go on to disable features.  */
4758       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4759           == PACKET_ERROR)
4760         {
4761           warning (_("Remote failure reply: %s"), rs->buf);
4762           rs->buf[0] = 0;
4763         }
4764     }
4765
4766   memset (seen, 0, sizeof (seen));
4767
4768   next = rs->buf;
4769   while (*next)
4770     {
4771       enum packet_support is_supported;
4772       char *p, *end, *name_end, *value;
4773
4774       /* First separate out this item from the rest of the packet.  If
4775          there's another item after this, we overwrite the separator
4776          (terminated strings are much easier to work with).  */
4777       p = next;
4778       end = strchr (p, ';');
4779       if (end == NULL)
4780         {
4781           end = p + strlen (p);
4782           next = end;
4783         }
4784       else
4785         {
4786           *end = '\0';
4787           next = end + 1;
4788
4789           if (end == p)
4790             {
4791               warning (_("empty item in \"qSupported\" response"));
4792               continue;
4793             }
4794         }
4795
4796       name_end = strchr (p, '=');
4797       if (name_end)
4798         {
4799           /* This is a name=value entry.  */
4800           is_supported = PACKET_ENABLE;
4801           value = name_end + 1;
4802           *name_end = '\0';
4803         }
4804       else
4805         {
4806           value = NULL;
4807           switch (end[-1])
4808             {
4809             case '+':
4810               is_supported = PACKET_ENABLE;
4811               break;
4812
4813             case '-':
4814               is_supported = PACKET_DISABLE;
4815               break;
4816
4817             case '?':
4818               is_supported = PACKET_SUPPORT_UNKNOWN;
4819               break;
4820
4821             default:
4822               warning (_("unrecognized item \"%s\" "
4823                          "in \"qSupported\" response"), p);
4824               continue;
4825             }
4826           end[-1] = '\0';
4827         }
4828
4829       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4830         if (strcmp (remote_protocol_features[i].name, p) == 0)
4831           {
4832             const struct protocol_feature *feature;
4833
4834             seen[i] = 1;
4835             feature = &remote_protocol_features[i];
4836             feature->func (feature, is_supported, value);
4837             break;
4838           }
4839     }
4840
4841   /* If we increased the packet size, make sure to increase the global
4842      buffer size also.  We delay this until after parsing the entire
4843      qSupported packet, because this is the same buffer we were
4844      parsing.  */
4845   if (rs->buf_size < rs->explicit_packet_size)
4846     {
4847       rs->buf_size = rs->explicit_packet_size;
4848       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4849     }
4850
4851   /* Handle the defaults for unmentioned features.  */
4852   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4853     if (!seen[i])
4854       {
4855         const struct protocol_feature *feature;
4856
4857         feature = &remote_protocol_features[i];
4858         feature->func (feature, feature->default_support, NULL);
4859       }
4860 }
4861
4862 /* Serial QUIT handler for the remote serial descriptor.
4863
4864    Defers handling a Ctrl-C until we're done with the current
4865    command/response packet sequence, unless:
4866
4867    - We're setting up the connection.  Don't send a remote interrupt
4868      request, as we're not fully synced yet.  Quit immediately
4869      instead.
4870
4871    - The target has been resumed in the foreground
4872      (target_terminal_is_ours is false) with a synchronous resume
4873      packet, and we're blocked waiting for the stop reply, thus a
4874      Ctrl-C should be immediately sent to the target.
4875
4876    - We get a second Ctrl-C while still within the same serial read or
4877      write.  In that case the serial is seemingly wedged --- offer to
4878      quit/disconnect.
4879
4880    - We see a second Ctrl-C without target response, after having
4881      previously interrupted the target.  In that case the target/stub
4882      is probably wedged --- offer to quit/disconnect.
4883 */
4884
4885 static void
4886 remote_serial_quit_handler (void)
4887 {
4888   struct remote_state *rs = get_remote_state ();
4889
4890   if (check_quit_flag ())
4891     {
4892       /* If we're starting up, we're not fully synced yet.  Quit
4893          immediately.  */
4894       if (rs->starting_up)
4895         quit ();
4896       else if (rs->got_ctrlc_during_io)
4897         {
4898           if (query (_("The target is not responding to GDB commands.\n"
4899                        "Stop debugging it? ")))
4900             remote_unpush_and_throw ();
4901         }
4902       /* If ^C has already been sent once, offer to disconnect.  */
4903       else if (!target_terminal_is_ours () && rs->ctrlc_pending_p)
4904         interrupt_query ();
4905       /* All-stop protocol, and blocked waiting for stop reply.  Send
4906          an interrupt request.  */
4907       else if (!target_terminal_is_ours () && rs->waiting_for_stop_reply)
4908         target_interrupt (inferior_ptid);
4909       else
4910         rs->got_ctrlc_during_io = 1;
4911     }
4912 }
4913
4914 /* Remove any of the remote.c targets from target stack.  Upper targets depend
4915    on it so remove them first.  */
4916
4917 static void
4918 remote_unpush_target (void)
4919 {
4920   pop_all_targets_at_and_above (process_stratum);
4921 }
4922
4923 static void
4924 remote_unpush_and_throw (void)
4925 {
4926   remote_unpush_target ();
4927   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
4928 }
4929
4930 static void
4931 remote_open_1 (const char *name, int from_tty,
4932                struct target_ops *target, int extended_p)
4933 {
4934   struct remote_state *rs = get_remote_state ();
4935
4936   if (name == 0)
4937     error (_("To open a remote debug connection, you need to specify what\n"
4938            "serial device is attached to the remote system\n"
4939            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4940
4941   /* See FIXME above.  */
4942   if (!target_async_permitted)
4943     wait_forever_enabled_p = 1;
4944
4945   /* If we're connected to a running target, target_preopen will kill it.
4946      Ask this question first, before target_preopen has a chance to kill
4947      anything.  */
4948   if (rs->remote_desc != NULL && !have_inferiors ())
4949     {
4950       if (from_tty
4951           && !query (_("Already connected to a remote target.  Disconnect? ")))
4952         error (_("Still connected."));
4953     }
4954
4955   /* Here the possibly existing remote target gets unpushed.  */
4956   target_preopen (from_tty);
4957
4958   /* Make sure we send the passed signals list the next time we resume.  */
4959   xfree (rs->last_pass_packet);
4960   rs->last_pass_packet = NULL;
4961
4962   /* Make sure we send the program signals list the next time we
4963      resume.  */
4964   xfree (rs->last_program_signals_packet);
4965   rs->last_program_signals_packet = NULL;
4966
4967   remote_fileio_reset ();
4968   reopen_exec_file ();
4969   reread_symbols ();
4970
4971   rs->remote_desc = remote_serial_open (name);
4972   if (!rs->remote_desc)
4973     perror_with_name (name);
4974
4975   if (baud_rate != -1)
4976     {
4977       if (serial_setbaudrate (rs->remote_desc, baud_rate))
4978         {
4979           /* The requested speed could not be set.  Error out to
4980              top level after closing remote_desc.  Take care to
4981              set remote_desc to NULL to avoid closing remote_desc
4982              more than once.  */
4983           serial_close (rs->remote_desc);
4984           rs->remote_desc = NULL;
4985           perror_with_name (name);
4986         }
4987     }
4988
4989   serial_setparity (rs->remote_desc, serial_parity);
4990   serial_raw (rs->remote_desc);
4991
4992   /* If there is something sitting in the buffer we might take it as a
4993      response to a command, which would be bad.  */
4994   serial_flush_input (rs->remote_desc);
4995
4996   if (from_tty)
4997     {
4998       puts_filtered ("Remote debugging using ");
4999       puts_filtered (name);
5000       puts_filtered ("\n");
5001     }
5002   push_target (target);         /* Switch to using remote target now.  */
5003
5004   /* Register extra event sources in the event loop.  */
5005   remote_async_inferior_event_token
5006     = create_async_event_handler (remote_async_inferior_event_handler,
5007                                   NULL);
5008   rs->notif_state = remote_notif_state_allocate ();
5009
5010   /* Reset the target state; these things will be queried either by
5011      remote_query_supported or as they are needed.  */
5012   reset_all_packet_configs_support ();
5013   rs->cached_wait_status = 0;
5014   rs->explicit_packet_size = 0;
5015   rs->noack_mode = 0;
5016   rs->extended = extended_p;
5017   rs->waiting_for_stop_reply = 0;
5018   rs->ctrlc_pending_p = 0;
5019   rs->got_ctrlc_during_io = 0;
5020
5021   rs->general_thread = not_sent_ptid;
5022   rs->continue_thread = not_sent_ptid;
5023   rs->remote_traceframe_number = -1;
5024
5025   rs->last_resume_exec_dir = EXEC_FORWARD;
5026
5027   /* Probe for ability to use "ThreadInfo" query, as required.  */
5028   rs->use_threadinfo_query = 1;
5029   rs->use_threadextra_query = 1;
5030
5031   readahead_cache_invalidate ();
5032
5033   /* Start out by owning the terminal.  */
5034   remote_async_terminal_ours_p = 1;
5035
5036   if (target_async_permitted)
5037     {
5038       /* FIXME: cagney/1999-09-23: During the initial connection it is
5039          assumed that the target is already ready and able to respond to
5040          requests.  Unfortunately remote_start_remote() eventually calls
5041          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
5042          around this.  Eventually a mechanism that allows
5043          wait_for_inferior() to expect/get timeouts will be
5044          implemented.  */
5045       wait_forever_enabled_p = 0;
5046     }
5047
5048   /* First delete any symbols previously loaded from shared libraries.  */
5049   no_shared_libraries (NULL, 0);
5050
5051   /* Start afresh.  */
5052   init_thread_list ();
5053
5054   /* Start the remote connection.  If error() or QUIT, discard this
5055      target (we'd otherwise be in an inconsistent state) and then
5056      propogate the error on up the exception chain.  This ensures that
5057      the caller doesn't stumble along blindly assuming that the
5058      function succeeded.  The CLI doesn't have this problem but other
5059      UI's, such as MI do.
5060
5061      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5062      this function should return an error indication letting the
5063      caller restore the previous state.  Unfortunately the command
5064      ``target remote'' is directly wired to this function making that
5065      impossible.  On a positive note, the CLI side of this problem has
5066      been fixed - the function set_cmd_context() makes it possible for
5067      all the ``target ....'' commands to share a common callback
5068      function.  See cli-dump.c.  */
5069   {
5070
5071     TRY
5072       {
5073         remote_start_remote (from_tty, target, extended_p);
5074       }
5075     CATCH (ex, RETURN_MASK_ALL)
5076       {
5077         /* Pop the partially set up target - unless something else did
5078            already before throwing the exception.  */
5079         if (rs->remote_desc != NULL)
5080           remote_unpush_target ();
5081         if (target_async_permitted)
5082           wait_forever_enabled_p = 1;
5083         throw_exception (ex);
5084       }
5085     END_CATCH
5086   }
5087
5088   remote_btrace_reset ();
5089
5090   if (target_async_permitted)
5091     wait_forever_enabled_p = 1;
5092 }
5093
5094 /* Detach the specified process.  */
5095
5096 static void
5097 remote_detach_pid (int pid)
5098 {
5099   struct remote_state *rs = get_remote_state ();
5100
5101   if (remote_multi_process_p (rs))
5102     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5103   else
5104     strcpy (rs->buf, "D");
5105
5106   putpkt (rs->buf);
5107   getpkt (&rs->buf, &rs->buf_size, 0);
5108
5109   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5110     ;
5111   else if (rs->buf[0] == '\0')
5112     error (_("Remote doesn't know how to detach"));
5113   else
5114     error (_("Can't detach process."));
5115 }
5116
5117 /* This detaches a program to which we previously attached, using
5118    inferior_ptid to identify the process.  After this is done, GDB
5119    can be used to debug some other program.  We better not have left
5120    any breakpoints in the target program or it'll die when it hits
5121    one.  */
5122
5123 static void
5124 remote_detach_1 (const char *args, int from_tty)
5125 {
5126   int pid = ptid_get_pid (inferior_ptid);
5127   struct remote_state *rs = get_remote_state ();
5128   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5129   int is_fork_parent;
5130
5131   if (args)
5132     error (_("Argument given to \"detach\" when remotely debugging."));
5133
5134   if (!target_has_execution)
5135     error (_("No process to detach from."));
5136
5137   if (from_tty)
5138     {
5139       char *exec_file = get_exec_file (0);
5140       if (exec_file == NULL)
5141         exec_file = "";
5142       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
5143                          target_pid_to_str (pid_to_ptid (pid)));
5144       gdb_flush (gdb_stdout);
5145     }
5146
5147   /* Tell the remote target to detach.  */
5148   remote_detach_pid (pid);
5149
5150   /* Exit only if this is the only active inferior.  */
5151   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5152     puts_filtered (_("Ending remote debugging.\n"));
5153
5154   /* Check to see if we are detaching a fork parent.  Note that if we
5155      are detaching a fork child, tp == NULL.  */
5156   is_fork_parent = (tp != NULL
5157                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5158
5159   /* If doing detach-on-fork, we don't mourn, because that will delete
5160      breakpoints that should be available for the followed inferior.  */
5161   if (!is_fork_parent)
5162     target_mourn_inferior ();
5163   else
5164     {
5165       inferior_ptid = null_ptid;
5166       detach_inferior (pid);
5167     }
5168 }
5169
5170 static void
5171 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5172 {
5173   remote_detach_1 (args, from_tty);
5174 }
5175
5176 static void
5177 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5178 {
5179   remote_detach_1 (args, from_tty);
5180 }
5181
5182 /* Target follow-fork function for remote targets.  On entry, and
5183    at return, the current inferior is the fork parent.
5184
5185    Note that although this is currently only used for extended-remote,
5186    it is named remote_follow_fork in anticipation of using it for the
5187    remote target as well.  */
5188
5189 static int
5190 remote_follow_fork (struct target_ops *ops, int follow_child,
5191                     int detach_fork)
5192 {
5193   struct remote_state *rs = get_remote_state ();
5194   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5195
5196   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5197       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5198     {
5199       /* When following the parent and detaching the child, we detach
5200          the child here.  For the case of following the child and
5201          detaching the parent, the detach is done in the target-
5202          independent follow fork code in infrun.c.  We can't use
5203          target_detach when detaching an unfollowed child because
5204          the client side doesn't know anything about the child.  */
5205       if (detach_fork && !follow_child)
5206         {
5207           /* Detach the fork child.  */
5208           ptid_t child_ptid;
5209           pid_t child_pid;
5210
5211           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5212           child_pid = ptid_get_pid (child_ptid);
5213
5214           remote_detach_pid (child_pid);
5215           detach_inferior (child_pid);
5216         }
5217     }
5218   return 0;
5219 }
5220
5221 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5222    in the program space of the new inferior.  On entry and at return the
5223    current inferior is the exec'ing inferior.  INF is the new exec'd
5224    inferior, which may be the same as the exec'ing inferior unless
5225    follow-exec-mode is "new".  */
5226
5227 static void
5228 remote_follow_exec (struct target_ops *ops,
5229                     struct inferior *inf, char *execd_pathname)
5230 {
5231   /* We know that this is a target file name, so if it has the "target:"
5232      prefix we strip it off before saving it in the program space.  */
5233   if (is_target_filename (execd_pathname))
5234     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5235
5236   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5237 }
5238
5239 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5240
5241 static void
5242 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5243 {
5244   if (args)
5245     error (_("Argument given to \"disconnect\" when remotely debugging."));
5246
5247   /* Make sure we unpush even the extended remote targets.  Calling
5248      target_mourn_inferior won't unpush, and remote_mourn won't
5249      unpush if there is more than one inferior left.  */
5250   unpush_target (target);
5251   generic_mourn_inferior ();
5252
5253   if (from_tty)
5254     puts_filtered ("Ending remote debugging.\n");
5255 }
5256
5257 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5258    be chatty about it.  */
5259
5260 static void
5261 extended_remote_attach (struct target_ops *target, const char *args,
5262                         int from_tty)
5263 {
5264   struct remote_state *rs = get_remote_state ();
5265   int pid;
5266   char *wait_status = NULL;
5267
5268   pid = parse_pid_to_attach (args);
5269
5270   /* Remote PID can be freely equal to getpid, do not check it here the same
5271      way as in other targets.  */
5272
5273   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5274     error (_("This target does not support attaching to a process"));
5275
5276   if (from_tty)
5277     {
5278       char *exec_file = get_exec_file (0);
5279
5280       if (exec_file)
5281         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5282                            target_pid_to_str (pid_to_ptid (pid)));
5283       else
5284         printf_unfiltered (_("Attaching to %s\n"),
5285                            target_pid_to_str (pid_to_ptid (pid)));
5286
5287       gdb_flush (gdb_stdout);
5288     }
5289
5290   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5291   putpkt (rs->buf);
5292   getpkt (&rs->buf, &rs->buf_size, 0);
5293
5294   switch (packet_ok (rs->buf,
5295                      &remote_protocol_packets[PACKET_vAttach]))
5296     {
5297     case PACKET_OK:
5298       if (!target_is_non_stop_p ())
5299         {
5300           /* Save the reply for later.  */
5301           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5302           strcpy (wait_status, rs->buf);
5303         }
5304       else if (strcmp (rs->buf, "OK") != 0)
5305         error (_("Attaching to %s failed with: %s"),
5306                target_pid_to_str (pid_to_ptid (pid)),
5307                rs->buf);
5308       break;
5309     case PACKET_UNKNOWN:
5310       error (_("This target does not support attaching to a process"));
5311     default:
5312       error (_("Attaching to %s failed"),
5313              target_pid_to_str (pid_to_ptid (pid)));
5314     }
5315
5316   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5317
5318   inferior_ptid = pid_to_ptid (pid);
5319
5320   if (target_is_non_stop_p ())
5321     {
5322       struct thread_info *thread;
5323
5324       /* Get list of threads.  */
5325       remote_update_thread_list (target);
5326
5327       thread = first_thread_of_process (pid);
5328       if (thread)
5329         inferior_ptid = thread->ptid;
5330       else
5331         inferior_ptid = pid_to_ptid (pid);
5332
5333       /* Invalidate our notion of the remote current thread.  */
5334       record_currthread (rs, minus_one_ptid);
5335     }
5336   else
5337     {
5338       /* Now, if we have thread information, update inferior_ptid.  */
5339       inferior_ptid = remote_current_thread (inferior_ptid);
5340
5341       /* Add the main thread to the thread list.  */
5342       add_thread_silent (inferior_ptid);
5343     }
5344
5345   /* Next, if the target can specify a description, read it.  We do
5346      this before anything involving memory or registers.  */
5347   target_find_description ();
5348
5349   if (!target_is_non_stop_p ())
5350     {
5351       /* Use the previously fetched status.  */
5352       gdb_assert (wait_status != NULL);
5353
5354       if (target_can_async_p ())
5355         {
5356           struct notif_event *reply
5357             =  remote_notif_parse (&notif_client_stop, wait_status);
5358
5359           push_stop_reply ((struct stop_reply *) reply);
5360
5361           target_async (1);
5362         }
5363       else
5364         {
5365           gdb_assert (wait_status != NULL);
5366           strcpy (rs->buf, wait_status);
5367           rs->cached_wait_status = 1;
5368         }
5369     }
5370   else
5371     gdb_assert (wait_status == NULL);
5372 }
5373
5374 /* Implementation of the to_post_attach method.  */
5375
5376 static void
5377 extended_remote_post_attach (struct target_ops *ops, int pid)
5378 {
5379   /* Get text, data & bss offsets.  */
5380   get_offsets ();
5381
5382   /* In certain cases GDB might not have had the chance to start
5383      symbol lookup up until now.  This could happen if the debugged
5384      binary is not using shared libraries, the vsyscall page is not
5385      present (on Linux) and the binary itself hadn't changed since the
5386      debugging process was started.  */
5387   if (symfile_objfile != NULL)
5388     remote_check_symbols();
5389 }
5390
5391 \f
5392 /* Check for the availability of vCont.  This function should also check
5393    the response.  */
5394
5395 static void
5396 remote_vcont_probe (struct remote_state *rs)
5397 {
5398   char *buf;
5399
5400   strcpy (rs->buf, "vCont?");
5401   putpkt (rs->buf);
5402   getpkt (&rs->buf, &rs->buf_size, 0);
5403   buf = rs->buf;
5404
5405   /* Make sure that the features we assume are supported.  */
5406   if (startswith (buf, "vCont"))
5407     {
5408       char *p = &buf[5];
5409       int support_c, support_C;
5410
5411       rs->supports_vCont.s = 0;
5412       rs->supports_vCont.S = 0;
5413       support_c = 0;
5414       support_C = 0;
5415       rs->supports_vCont.t = 0;
5416       rs->supports_vCont.r = 0;
5417       while (p && *p == ';')
5418         {
5419           p++;
5420           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5421             rs->supports_vCont.s = 1;
5422           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5423             rs->supports_vCont.S = 1;
5424           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5425             support_c = 1;
5426           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5427             support_C = 1;
5428           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5429             rs->supports_vCont.t = 1;
5430           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5431             rs->supports_vCont.r = 1;
5432
5433           p = strchr (p, ';');
5434         }
5435
5436       /* If c, and C are not all supported, we can't use vCont.  Clearing
5437          BUF will make packet_ok disable the packet.  */
5438       if (!support_c || !support_C)
5439         buf[0] = 0;
5440     }
5441
5442   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5443 }
5444
5445 /* Helper function for building "vCont" resumptions.  Write a
5446    resumption to P.  ENDP points to one-passed-the-end of the buffer
5447    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5448    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5449    resumed thread should be single-stepped and/or signalled.  If PTID
5450    equals minus_one_ptid, then all threads are resumed; if PTID
5451    represents a process, then all threads of the process are resumed;
5452    the thread to be stepped and/or signalled is given in the global
5453    INFERIOR_PTID.  */
5454
5455 static char *
5456 append_resumption (char *p, char *endp,
5457                    ptid_t ptid, int step, enum gdb_signal siggnal)
5458 {
5459   struct remote_state *rs = get_remote_state ();
5460
5461   if (step && siggnal != GDB_SIGNAL_0)
5462     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5463   else if (step
5464            /* GDB is willing to range step.  */
5465            && use_range_stepping
5466            /* Target supports range stepping.  */
5467            && rs->supports_vCont.r
5468            /* We don't currently support range stepping multiple
5469               threads with a wildcard (though the protocol allows it,
5470               so stubs shouldn't make an active effort to forbid
5471               it).  */
5472            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5473     {
5474       struct thread_info *tp;
5475
5476       if (ptid_equal (ptid, minus_one_ptid))
5477         {
5478           /* If we don't know about the target thread's tid, then
5479              we're resuming magic_null_ptid (see caller).  */
5480           tp = find_thread_ptid (magic_null_ptid);
5481         }
5482       else
5483         tp = find_thread_ptid (ptid);
5484       gdb_assert (tp != NULL);
5485
5486       if (tp->control.may_range_step)
5487         {
5488           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5489
5490           p += xsnprintf (p, endp - p, ";r%s,%s",
5491                           phex_nz (tp->control.step_range_start,
5492                                    addr_size),
5493                           phex_nz (tp->control.step_range_end,
5494                                    addr_size));
5495         }
5496       else
5497         p += xsnprintf (p, endp - p, ";s");
5498     }
5499   else if (step)
5500     p += xsnprintf (p, endp - p, ";s");
5501   else if (siggnal != GDB_SIGNAL_0)
5502     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5503   else
5504     p += xsnprintf (p, endp - p, ";c");
5505
5506   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5507     {
5508       ptid_t nptid;
5509
5510       /* All (-1) threads of process.  */
5511       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5512
5513       p += xsnprintf (p, endp - p, ":");
5514       p = write_ptid (p, endp, nptid);
5515     }
5516   else if (!ptid_equal (ptid, minus_one_ptid))
5517     {
5518       p += xsnprintf (p, endp - p, ":");
5519       p = write_ptid (p, endp, ptid);
5520     }
5521
5522   return p;
5523 }
5524
5525 /* Clear the thread's private info on resume.  */
5526
5527 static void
5528 resume_clear_thread_private_info (struct thread_info *thread)
5529 {
5530   if (thread->priv != NULL)
5531     {
5532       thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5533       thread->priv->watch_data_address = 0;
5534     }
5535 }
5536
5537 /* Append a vCont continue-with-signal action for threads that have a
5538    non-zero stop signal.  */
5539
5540 static char *
5541 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5542 {
5543   struct thread_info *thread;
5544
5545   ALL_NON_EXITED_THREADS (thread)
5546     if (ptid_match (thread->ptid, ptid)
5547         && !ptid_equal (inferior_ptid, thread->ptid)
5548         && thread->suspend.stop_signal != GDB_SIGNAL_0)
5549       {
5550         p = append_resumption (p, endp, thread->ptid,
5551                                0, thread->suspend.stop_signal);
5552         thread->suspend.stop_signal = GDB_SIGNAL_0;
5553         resume_clear_thread_private_info (thread);
5554       }
5555
5556   return p;
5557 }
5558
5559 /* Resume the remote inferior by using a "vCont" packet.  The thread
5560    to be resumed is PTID; STEP and SIGGNAL indicate whether the
5561    resumed thread should be single-stepped and/or signalled.  If PTID
5562    equals minus_one_ptid, then all threads are resumed; the thread to
5563    be stepped and/or signalled is given in the global INFERIOR_PTID.
5564    This function returns non-zero iff it resumes the inferior.
5565
5566    This function issues a strict subset of all possible vCont commands at the
5567    moment.  */
5568
5569 static int
5570 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5571 {
5572   struct remote_state *rs = get_remote_state ();
5573   char *p;
5574   char *endp;
5575
5576   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5577     remote_vcont_probe (rs);
5578
5579   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5580     return 0;
5581
5582   p = rs->buf;
5583   endp = rs->buf + get_remote_packet_size ();
5584
5585   /* If we could generate a wider range of packets, we'd have to worry
5586      about overflowing BUF.  Should there be a generic
5587      "multi-part-packet" packet?  */
5588
5589   p += xsnprintf (p, endp - p, "vCont");
5590
5591   if (ptid_equal (ptid, magic_null_ptid))
5592     {
5593       /* MAGIC_NULL_PTID means that we don't have any active threads,
5594          so we don't have any TID numbers the inferior will
5595          understand.  Make sure to only send forms that do not specify
5596          a TID.  */
5597       append_resumption (p, endp, minus_one_ptid, step, siggnal);
5598     }
5599   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5600     {
5601       /* Resume all threads (of all processes, or of a single
5602          process), with preference for INFERIOR_PTID.  This assumes
5603          inferior_ptid belongs to the set of all threads we are about
5604          to resume.  */
5605       if (step || siggnal != GDB_SIGNAL_0)
5606         {
5607           /* Step inferior_ptid, with or without signal.  */
5608           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5609         }
5610
5611       /* Also pass down any pending signaled resumption for other
5612          threads not the current.  */
5613       p = append_pending_thread_resumptions (p, endp, ptid);
5614
5615       /* And continue others without a signal.  */
5616       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5617     }
5618   else
5619     {
5620       /* Scheduler locking; resume only PTID.  */
5621       append_resumption (p, endp, ptid, step, siggnal);
5622     }
5623
5624   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5625   putpkt (rs->buf);
5626
5627   if (target_is_non_stop_p ())
5628     {
5629       /* In non-stop, the stub replies to vCont with "OK".  The stop
5630          reply will be reported asynchronously by means of a `%Stop'
5631          notification.  */
5632       getpkt (&rs->buf, &rs->buf_size, 0);
5633       if (strcmp (rs->buf, "OK") != 0)
5634         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5635     }
5636
5637   return 1;
5638 }
5639
5640 /* Tell the remote machine to resume.  */
5641
5642 static void
5643 remote_resume (struct target_ops *ops,
5644                ptid_t ptid, int step, enum gdb_signal siggnal)
5645 {
5646   struct remote_state *rs = get_remote_state ();
5647   char *buf;
5648   struct thread_info *thread;
5649
5650   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5651      (explained in remote-notif.c:handle_notification) so
5652      remote_notif_process is not called.  We need find a place where
5653      it is safe to start a 'vNotif' sequence.  It is good to do it
5654      before resuming inferior, because inferior was stopped and no RSP
5655      traffic at that moment.  */
5656   if (!target_is_non_stop_p ())
5657     remote_notif_process (rs->notif_state, &notif_client_stop);
5658
5659   rs->last_sent_signal = siggnal;
5660   rs->last_sent_step = step;
5661
5662   rs->last_resume_exec_dir = execution_direction;
5663
5664   /* The vCont packet doesn't need to specify threads via Hc.  */
5665   /* No reverse support (yet) for vCont.  */
5666   if (execution_direction != EXEC_REVERSE)
5667     if (remote_vcont_resume (ptid, step, siggnal))
5668       goto done;
5669
5670   /* All other supported resume packets do use Hc, so set the continue
5671      thread.  */
5672   if (ptid_equal (ptid, minus_one_ptid))
5673     set_continue_thread (any_thread_ptid);
5674   else
5675     set_continue_thread (ptid);
5676
5677   ALL_NON_EXITED_THREADS (thread)
5678     resume_clear_thread_private_info (thread);
5679
5680   buf = rs->buf;
5681   if (execution_direction == EXEC_REVERSE)
5682     {
5683       /* We don't pass signals to the target in reverse exec mode.  */
5684       if (info_verbose && siggnal != GDB_SIGNAL_0)
5685         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5686                  siggnal);
5687
5688       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5689         error (_("Remote reverse-step not supported."));
5690       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5691         error (_("Remote reverse-continue not supported."));
5692
5693       strcpy (buf, step ? "bs" : "bc");
5694     }
5695   else if (siggnal != GDB_SIGNAL_0)
5696     {
5697       buf[0] = step ? 'S' : 'C';
5698       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5699       buf[2] = tohex (((int) siggnal) & 0xf);
5700       buf[3] = '\0';
5701     }
5702   else
5703     strcpy (buf, step ? "s" : "c");
5704
5705   putpkt (buf);
5706
5707  done:
5708   /* We are about to start executing the inferior, let's register it
5709      with the event loop.  NOTE: this is the one place where all the
5710      execution commands end up.  We could alternatively do this in each
5711      of the execution commands in infcmd.c.  */
5712   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5713      into infcmd.c in order to allow inferior function calls to work
5714      NOT asynchronously.  */
5715   if (target_can_async_p ())
5716     target_async (1);
5717
5718   /* We've just told the target to resume.  The remote server will
5719      wait for the inferior to stop, and then send a stop reply.  In
5720      the mean time, we can't start another command/query ourselves
5721      because the stub wouldn't be ready to process it.  This applies
5722      only to the base all-stop protocol, however.  In non-stop (which
5723      only supports vCont), the stub replies with an "OK", and is
5724      immediate able to process further serial input.  */
5725   if (!target_is_non_stop_p ())
5726     rs->waiting_for_stop_reply = 1;
5727 }
5728 \f
5729
5730 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
5731    thread, all threads of a remote process, or all threads of all
5732    processes.  */
5733
5734 static void
5735 remote_stop_ns (ptid_t ptid)
5736 {
5737   struct remote_state *rs = get_remote_state ();
5738   char *p = rs->buf;
5739   char *endp = rs->buf + get_remote_packet_size ();
5740
5741   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5742     remote_vcont_probe (rs);
5743
5744   if (!rs->supports_vCont.t)
5745     error (_("Remote server does not support stopping threads"));
5746
5747   if (ptid_equal (ptid, minus_one_ptid)
5748       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5749     p += xsnprintf (p, endp - p, "vCont;t");
5750   else
5751     {
5752       ptid_t nptid;
5753
5754       p += xsnprintf (p, endp - p, "vCont;t:");
5755
5756       if (ptid_is_pid (ptid))
5757           /* All (-1) threads of process.  */
5758         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5759       else
5760         {
5761           /* Small optimization: if we already have a stop reply for
5762              this thread, no use in telling the stub we want this
5763              stopped.  */
5764           if (peek_stop_reply (ptid))
5765             return;
5766
5767           nptid = ptid;
5768         }
5769
5770       write_ptid (p, endp, nptid);
5771     }
5772
5773   /* In non-stop, we get an immediate OK reply.  The stop reply will
5774      come in asynchronously by notification.  */
5775   putpkt (rs->buf);
5776   getpkt (&rs->buf, &rs->buf_size, 0);
5777   if (strcmp (rs->buf, "OK") != 0)
5778     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5779 }
5780
5781 /* All-stop version of target_interrupt.  Sends a break or a ^C to
5782    interrupt the remote target.  It is undefined which thread of which
5783    process reports the interrupt.  */
5784
5785 static void
5786 remote_interrupt_as (void)
5787 {
5788   struct remote_state *rs = get_remote_state ();
5789
5790   rs->ctrlc_pending_p = 1;
5791
5792   /* If the inferior is stopped already, but the core didn't know
5793      about it yet, just ignore the request.  The cached wait status
5794      will be collected in remote_wait.  */
5795   if (rs->cached_wait_status)
5796     return;
5797
5798   /* Send interrupt_sequence to remote target.  */
5799   send_interrupt_sequence ();
5800 }
5801
5802 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
5803    the remote target.  It is undefined which thread of which process
5804    reports the interrupt.  Throws an error if the packet is not
5805    supported by the server.  */
5806
5807 static void
5808 remote_interrupt_ns (void)
5809 {
5810   struct remote_state *rs = get_remote_state ();
5811   char *p = rs->buf;
5812   char *endp = rs->buf + get_remote_packet_size ();
5813
5814   xsnprintf (p, endp - p, "vCtrlC");
5815
5816   /* In non-stop, we get an immediate OK reply.  The stop reply will
5817      come in asynchronously by notification.  */
5818   putpkt (rs->buf);
5819   getpkt (&rs->buf, &rs->buf_size, 0);
5820
5821   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5822     {
5823     case PACKET_OK:
5824       break;
5825     case PACKET_UNKNOWN:
5826       error (_("No support for interrupting the remote target."));
5827     case PACKET_ERROR:
5828       error (_("Interrupting target failed: %s"), rs->buf);
5829     }
5830 }
5831
5832 /* Implement the to_stop function for the remote targets.  */
5833
5834 static void
5835 remote_stop (struct target_ops *self, ptid_t ptid)
5836 {
5837   if (remote_debug)
5838     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5839
5840   if (target_is_non_stop_p ())
5841     remote_stop_ns (ptid);
5842   else
5843     {
5844       /* We don't currently have a way to transparently pause the
5845          remote target in all-stop mode.  Interrupt it instead.  */
5846       remote_interrupt_as ();
5847     }
5848 }
5849
5850 /* Implement the to_interrupt function for the remote targets.  */
5851
5852 static void
5853 remote_interrupt (struct target_ops *self, ptid_t ptid)
5854 {
5855   struct remote_state *rs = get_remote_state ();
5856
5857   if (remote_debug)
5858     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5859
5860   if (target_is_non_stop_p ())
5861     remote_interrupt_ns ();
5862   else
5863     remote_interrupt_as ();
5864 }
5865
5866 /* Implement the to_pass_ctrlc function for the remote targets.  */
5867
5868 static void
5869 remote_pass_ctrlc (struct target_ops *self)
5870 {
5871   struct remote_state *rs = get_remote_state ();
5872
5873   if (remote_debug)
5874     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
5875
5876   /* If we're starting up, we're not fully synced yet.  Quit
5877      immediately.  */
5878   if (rs->starting_up)
5879     quit ();
5880   /* If ^C has already been sent once, offer to disconnect.  */
5881   else if (rs->ctrlc_pending_p)
5882     interrupt_query ();
5883   else
5884     target_interrupt (inferior_ptid);
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
5894   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5895     {
5896       if (query (_("The target is not responding to interrupt requests.\n"
5897                    "Stop debugging it? ")))
5898         {
5899           remote_unpush_target ();
5900           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5901         }
5902     }
5903   else
5904     {
5905       if (query (_("Interrupted while waiting for the program.\n"
5906                    "Give up waiting? ")))
5907         quit ();
5908     }
5909 }
5910
5911 /* Enable/disable target terminal ownership.  Most targets can use
5912    terminal groups to control terminal ownership.  Remote targets are
5913    different in that explicit transfer of ownership to/from GDB/target
5914    is required.  */
5915
5916 static void
5917 remote_terminal_inferior (struct target_ops *self)
5918 {
5919   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5920      idempotent.  The event-loop GDB talking to an asynchronous target
5921      with a synchronous command calls this function from both
5922      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
5923      transfer the terminal to the target when it shouldn't this guard
5924      can go away.  */
5925   if (!remote_async_terminal_ours_p)
5926     return;
5927   remote_async_terminal_ours_p = 0;
5928   /* NOTE: At this point we could also register our selves as the
5929      recipient of all input.  Any characters typed could then be
5930      passed on down to the target.  */
5931 }
5932
5933 static void
5934 remote_terminal_ours (struct target_ops *self)
5935 {
5936   /* See FIXME in remote_terminal_inferior.  */
5937   if (remote_async_terminal_ours_p)
5938     return;
5939   remote_async_terminal_ours_p = 1;
5940 }
5941
5942 static void
5943 remote_console_output (char *msg)
5944 {
5945   char *p;
5946
5947   for (p = msg; p[0] && p[1]; p += 2)
5948     {
5949       char tb[2];
5950       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5951
5952       tb[0] = c;
5953       tb[1] = 0;
5954       fputs_unfiltered (tb, gdb_stdtarg);
5955     }
5956   gdb_flush (gdb_stdtarg);
5957 }
5958
5959 typedef struct cached_reg
5960 {
5961   int num;
5962   gdb_byte data[MAX_REGISTER_SIZE];
5963 } cached_reg_t;
5964
5965 DEF_VEC_O(cached_reg_t);
5966
5967 typedef struct stop_reply
5968 {
5969   struct notif_event base;
5970
5971   /* The identifier of the thread about this event  */
5972   ptid_t ptid;
5973
5974   /* The remote state this event is associated with.  When the remote
5975      connection, represented by a remote_state object, is closed,
5976      all the associated stop_reply events should be released.  */
5977   struct remote_state *rs;
5978
5979   struct target_waitstatus ws;
5980
5981   /* Expedited registers.  This makes remote debugging a bit more
5982      efficient for those targets that provide critical registers as
5983      part of their normal status mechanism (as another roundtrip to
5984      fetch them is avoided).  */
5985   VEC(cached_reg_t) *regcache;
5986
5987   enum target_stop_reason stop_reason;
5988
5989   CORE_ADDR watch_data_address;
5990
5991   int core;
5992 } *stop_reply_p;
5993
5994 DECLARE_QUEUE_P (stop_reply_p);
5995 DEFINE_QUEUE_P (stop_reply_p);
5996 /* The list of already fetched and acknowledged stop events.  This
5997    queue is used for notification Stop, and other notifications
5998    don't need queue for their events, because the notification events
5999    of Stop can't be consumed immediately, so that events should be
6000    queued first, and be consumed by remote_wait_{ns,as} one per
6001    time.  Other notifications can consume their events immediately,
6002    so queue is not needed for them.  */
6003 static QUEUE (stop_reply_p) *stop_reply_queue;
6004
6005 static void
6006 stop_reply_xfree (struct stop_reply *r)
6007 {
6008   notif_event_xfree ((struct notif_event *) r);
6009 }
6010
6011 /* Return the length of the stop reply queue.  */
6012
6013 static int
6014 stop_reply_queue_length (void)
6015 {
6016   return QUEUE_length (stop_reply_p, stop_reply_queue);
6017 }
6018
6019 static void
6020 remote_notif_stop_parse (struct notif_client *self, char *buf,
6021                          struct notif_event *event)
6022 {
6023   remote_parse_stop_reply (buf, (struct stop_reply *) event);
6024 }
6025
6026 static void
6027 remote_notif_stop_ack (struct notif_client *self, char *buf,
6028                        struct notif_event *event)
6029 {
6030   struct stop_reply *stop_reply = (struct stop_reply *) event;
6031
6032   /* acknowledge */
6033   putpkt ((char *) self->ack_command);
6034
6035   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6036       /* We got an unknown stop reply.  */
6037       error (_("Unknown stop reply"));
6038
6039   push_stop_reply (stop_reply);
6040 }
6041
6042 static int
6043 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6044 {
6045   /* We can't get pending events in remote_notif_process for
6046      notification stop, and we have to do this in remote_wait_ns
6047      instead.  If we fetch all queued events from stub, remote stub
6048      may exit and we have no chance to process them back in
6049      remote_wait_ns.  */
6050   mark_async_event_handler (remote_async_inferior_event_token);
6051   return 0;
6052 }
6053
6054 static void
6055 stop_reply_dtr (struct notif_event *event)
6056 {
6057   struct stop_reply *r = (struct stop_reply *) event;
6058
6059   VEC_free (cached_reg_t, r->regcache);
6060 }
6061
6062 static struct notif_event *
6063 remote_notif_stop_alloc_reply (void)
6064 {
6065   /* We cast to a pointer to the "base class".  */
6066   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6067
6068   r->dtr = stop_reply_dtr;
6069
6070   return r;
6071 }
6072
6073 /* A client of notification Stop.  */
6074
6075 struct notif_client notif_client_stop =
6076 {
6077   "Stop",
6078   "vStopped",
6079   remote_notif_stop_parse,
6080   remote_notif_stop_ack,
6081   remote_notif_stop_can_get_pending_events,
6082   remote_notif_stop_alloc_reply,
6083   REMOTE_NOTIF_STOP,
6084 };
6085
6086 /* A parameter to pass data in and out.  */
6087
6088 struct queue_iter_param
6089 {
6090   void *input;
6091   struct stop_reply *output;
6092 };
6093
6094 /* Determine if THREAD is a pending fork parent thread.  ARG contains
6095    the pid of the process that owns the threads we want to check, or
6096    -1 if we want to check all threads.  */
6097
6098 static int
6099 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6100                         ptid_t thread_ptid)
6101 {
6102   if (ws->kind == TARGET_WAITKIND_FORKED
6103       || ws->kind == TARGET_WAITKIND_VFORKED)
6104     {
6105       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6106         return 1;
6107     }
6108
6109   return 0;
6110 }
6111
6112 /* Check whether EVENT is a fork event, and if it is, remove the
6113    fork child from the context list passed in DATA.  */
6114
6115 static int
6116 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6117                               QUEUE_ITER (stop_reply_p) *iter,
6118                               stop_reply_p event,
6119                               void *data)
6120 {
6121   struct queue_iter_param *param = (struct queue_iter_param *) data;
6122   struct threads_listing_context *context
6123     = (struct threads_listing_context *) param->input;
6124
6125   if (event->ws.kind == TARGET_WAITKIND_FORKED
6126       || event->ws.kind == TARGET_WAITKIND_VFORKED
6127       || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6128     threads_listing_context_remove (&event->ws, context);
6129
6130   return 1;
6131 }
6132
6133 /* If CONTEXT contains any fork child threads that have not been
6134    reported yet, remove them from the CONTEXT list.  If such a
6135    thread exists it is because we are stopped at a fork catchpoint
6136    and have not yet called follow_fork, which will set up the
6137    host-side data structures for the new process.  */
6138
6139 static void
6140 remove_new_fork_children (struct threads_listing_context *context)
6141 {
6142   struct thread_info * thread;
6143   int pid = -1;
6144   struct notif_client *notif = &notif_client_stop;
6145   struct queue_iter_param param;
6146
6147   /* For any threads stopped at a fork event, remove the corresponding
6148      fork child threads from the CONTEXT list.  */
6149   ALL_NON_EXITED_THREADS (thread)
6150     {
6151       struct target_waitstatus *ws;
6152
6153       if (thread->suspend.waitstatus_pending_p)
6154         ws = &thread->suspend.waitstatus;
6155       else
6156         ws = &thread->pending_follow;
6157
6158       if (is_pending_fork_parent (ws, pid, thread->ptid))
6159         {
6160           threads_listing_context_remove (ws, context);
6161         }
6162     }
6163
6164   /* Check for any pending fork events (not reported or processed yet)
6165      in process PID and remove those fork child threads from the
6166      CONTEXT list as well.  */
6167   remote_notif_get_pending_events (notif);
6168   param.input = context;
6169   param.output = NULL;
6170   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6171                  remove_child_of_pending_fork, &param);
6172 }
6173
6174 /* Remove stop replies in the queue if its pid is equal to the given
6175    inferior's pid.  */
6176
6177 static int
6178 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6179                                 QUEUE_ITER (stop_reply_p) *iter,
6180                                 stop_reply_p event,
6181                                 void *data)
6182 {
6183   struct queue_iter_param *param = (struct queue_iter_param *) data;
6184   struct inferior *inf = (struct inferior *) param->input;
6185
6186   if (ptid_get_pid (event->ptid) == inf->pid)
6187     {
6188       stop_reply_xfree (event);
6189       QUEUE_remove_elem (stop_reply_p, q, iter);
6190     }
6191
6192   return 1;
6193 }
6194
6195 /* Discard all pending stop replies of inferior INF.  */
6196
6197 static void
6198 discard_pending_stop_replies (struct inferior *inf)
6199 {
6200   struct queue_iter_param param;
6201   struct stop_reply *reply;
6202   struct remote_state *rs = get_remote_state ();
6203   struct remote_notif_state *rns = rs->notif_state;
6204
6205   /* This function can be notified when an inferior exists.  When the
6206      target is not remote, the notification state is NULL.  */
6207   if (rs->remote_desc == NULL)
6208     return;
6209
6210   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6211
6212   /* Discard the in-flight notification.  */
6213   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6214     {
6215       stop_reply_xfree (reply);
6216       rns->pending_event[notif_client_stop.id] = NULL;
6217     }
6218
6219   param.input = inf;
6220   param.output = NULL;
6221   /* Discard the stop replies we have already pulled with
6222      vStopped.  */
6223   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6224                  remove_stop_reply_for_inferior, &param);
6225 }
6226
6227 /* If its remote state is equal to the given remote state,
6228    remove EVENT from the stop reply queue.  */
6229
6230 static int
6231 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6232                                    QUEUE_ITER (stop_reply_p) *iter,
6233                                    stop_reply_p event,
6234                                    void *data)
6235 {
6236   struct queue_iter_param *param = (struct queue_iter_param *) data;
6237   struct remote_state *rs = (struct remote_state *) param->input;
6238
6239   if (event->rs == rs)
6240     {
6241       stop_reply_xfree (event);
6242       QUEUE_remove_elem (stop_reply_p, q, iter);
6243     }
6244
6245   return 1;
6246 }
6247
6248 /* Discard the stop replies for RS in stop_reply_queue.  */
6249
6250 static void
6251 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6252 {
6253   struct queue_iter_param param;
6254
6255   param.input = rs;
6256   param.output = NULL;
6257   /* Discard the stop replies we have already pulled with
6258      vStopped.  */
6259   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6260                  remove_stop_reply_of_remote_state, &param);
6261 }
6262
6263 /* A parameter to pass data in and out.  */
6264
6265 static int
6266 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6267                                    QUEUE_ITER (stop_reply_p) *iter,
6268                                    stop_reply_p event,
6269                                    void *data)
6270 {
6271   struct queue_iter_param *param = (struct queue_iter_param *) data;
6272   ptid_t *ptid = (ptid_t *) param->input;
6273
6274   if (ptid_match (event->ptid, *ptid))
6275     {
6276       param->output = event;
6277       QUEUE_remove_elem (stop_reply_p, q, iter);
6278       return 0;
6279     }
6280
6281   return 1;
6282 }
6283
6284 /* Remove the first reply in 'stop_reply_queue' which matches
6285    PTID.  */
6286
6287 static struct stop_reply *
6288 remote_notif_remove_queued_reply (ptid_t ptid)
6289 {
6290   struct queue_iter_param param;
6291
6292   param.input = &ptid;
6293   param.output = NULL;
6294
6295   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6296                  remote_notif_remove_once_on_match, &param);
6297   if (notif_debug)
6298     fprintf_unfiltered (gdb_stdlog,
6299                         "notif: discard queued event: 'Stop' in %s\n",
6300                         target_pid_to_str (ptid));
6301
6302   return param.output;
6303 }
6304
6305 /* Look for a queued stop reply belonging to PTID.  If one is found,
6306    remove it from the queue, and return it.  Returns NULL if none is
6307    found.  If there are still queued events left to process, tell the
6308    event loop to get back to target_wait soon.  */
6309
6310 static struct stop_reply *
6311 queued_stop_reply (ptid_t ptid)
6312 {
6313   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6314
6315   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6316     /* There's still at least an event left.  */
6317     mark_async_event_handler (remote_async_inferior_event_token);
6318
6319   return r;
6320 }
6321
6322 /* Push a fully parsed stop reply in the stop reply queue.  Since we
6323    know that we now have at least one queued event left to pass to the
6324    core side, tell the event loop to get back to target_wait soon.  */
6325
6326 static void
6327 push_stop_reply (struct stop_reply *new_event)
6328 {
6329   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6330
6331   if (notif_debug)
6332     fprintf_unfiltered (gdb_stdlog,
6333                         "notif: push 'Stop' %s to queue %d\n",
6334                         target_pid_to_str (new_event->ptid),
6335                         QUEUE_length (stop_reply_p,
6336                                       stop_reply_queue));
6337
6338   mark_async_event_handler (remote_async_inferior_event_token);
6339 }
6340
6341 static int
6342 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6343                               QUEUE_ITER (stop_reply_p) *iter,
6344                               struct stop_reply *event,
6345                               void *data)
6346 {
6347   ptid_t *ptid = (ptid_t *) data;
6348
6349   return !(ptid_equal (*ptid, event->ptid)
6350            && event->ws.kind == TARGET_WAITKIND_STOPPED);
6351 }
6352
6353 /* Returns true if we have a stop reply for PTID.  */
6354
6355 static int
6356 peek_stop_reply (ptid_t ptid)
6357 {
6358   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6359                          stop_reply_match_ptid_and_ws, &ptid);
6360 }
6361
6362 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
6363    starting with P and ending with PEND matches PREFIX.  */
6364
6365 static int
6366 strprefix (const char *p, const char *pend, const char *prefix)
6367 {
6368   for ( ; p < pend; p++, prefix++)
6369     if (*p != *prefix)
6370       return 0;
6371   return *prefix == '\0';
6372 }
6373
6374 /* Parse the stop reply in BUF.  Either the function succeeds, and the
6375    result is stored in EVENT, or throws an error.  */
6376
6377 static void
6378 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6379 {
6380   struct remote_arch_state *rsa = get_remote_arch_state ();
6381   ULONGEST addr;
6382   char *p;
6383   int skipregs = 0;
6384
6385   event->ptid = null_ptid;
6386   event->rs = get_remote_state ();
6387   event->ws.kind = TARGET_WAITKIND_IGNORE;
6388   event->ws.value.integer = 0;
6389   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6390   event->regcache = NULL;
6391   event->core = -1;
6392
6393   switch (buf[0])
6394     {
6395     case 'T':           /* Status with PC, SP, FP, ...  */
6396       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
6397       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
6398             ss = signal number
6399             n... = register number
6400             r... = register contents
6401       */
6402
6403       p = &buf[3];      /* after Txx */
6404       while (*p)
6405         {
6406           char *p1;
6407           int fieldsize;
6408
6409           p1 = strchr (p, ':');
6410           if (p1 == NULL)
6411             error (_("Malformed packet(a) (missing colon): %s\n\
6412 Packet: '%s'\n"),
6413                    p, buf);
6414           if (p == p1)
6415             error (_("Malformed packet(a) (missing register number): %s\n\
6416 Packet: '%s'\n"),
6417                    p, buf);
6418
6419           /* Some "registers" are actually extended stop information.
6420              Note if you're adding a new entry here: GDB 7.9 and
6421              earlier assume that all register "numbers" that start
6422              with an hex digit are real register numbers.  Make sure
6423              the server only sends such a packet if it knows the
6424              client understands it.  */
6425
6426           if (strprefix (p, p1, "thread"))
6427             event->ptid = read_ptid (++p1, &p);
6428           else if (strprefix (p, p1, "syscall_entry"))
6429             {
6430               ULONGEST sysno;
6431
6432               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6433               p = unpack_varlen_hex (++p1, &sysno);
6434               event->ws.value.syscall_number = (int) sysno;
6435             }
6436           else if (strprefix (p, p1, "syscall_return"))
6437             {
6438               ULONGEST sysno;
6439
6440               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6441               p = unpack_varlen_hex (++p1, &sysno);
6442               event->ws.value.syscall_number = (int) sysno;
6443             }
6444           else if (strprefix (p, p1, "watch")
6445                    || strprefix (p, p1, "rwatch")
6446                    || strprefix (p, p1, "awatch"))
6447             {
6448               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6449               p = unpack_varlen_hex (++p1, &addr);
6450               event->watch_data_address = (CORE_ADDR) addr;
6451             }
6452           else if (strprefix (p, p1, "swbreak"))
6453             {
6454               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6455
6456               /* Make sure the stub doesn't forget to indicate support
6457                  with qSupported.  */
6458               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6459                 error (_("Unexpected swbreak stop reason"));
6460
6461               /* The value part is documented as "must be empty",
6462                  though we ignore it, in case we ever decide to make
6463                  use of it in a backward compatible way.  */
6464               p = strchrnul (p1 + 1, ';');
6465             }
6466           else if (strprefix (p, p1, "hwbreak"))
6467             {
6468               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6469
6470               /* Make sure the stub doesn't forget to indicate support
6471                  with qSupported.  */
6472               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6473                 error (_("Unexpected hwbreak stop reason"));
6474
6475               /* See above.  */
6476               p = strchrnul (p1 + 1, ';');
6477             }
6478           else if (strprefix (p, p1, "library"))
6479             {
6480               event->ws.kind = TARGET_WAITKIND_LOADED;
6481               p = strchrnul (p1 + 1, ';');
6482             }
6483           else if (strprefix (p, p1, "replaylog"))
6484             {
6485               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6486               /* p1 will indicate "begin" or "end", but it makes
6487                  no difference for now, so ignore it.  */
6488               p = strchrnul (p1 + 1, ';');
6489             }
6490           else if (strprefix (p, p1, "core"))
6491             {
6492               ULONGEST c;
6493
6494               p = unpack_varlen_hex (++p1, &c);
6495               event->core = c;
6496             }
6497           else if (strprefix (p, p1, "fork"))
6498             {
6499               event->ws.value.related_pid = read_ptid (++p1, &p);
6500               event->ws.kind = TARGET_WAITKIND_FORKED;
6501             }
6502           else if (strprefix (p, p1, "vfork"))
6503             {
6504               event->ws.value.related_pid = read_ptid (++p1, &p);
6505               event->ws.kind = TARGET_WAITKIND_VFORKED;
6506             }
6507           else if (strprefix (p, p1, "vforkdone"))
6508             {
6509               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6510               p = strchrnul (p1 + 1, ';');
6511             }
6512           else if (strprefix (p, p1, "exec"))
6513             {
6514               ULONGEST ignored;
6515               char pathname[PATH_MAX];
6516               int pathlen;
6517
6518               /* Determine the length of the execd pathname.  */
6519               p = unpack_varlen_hex (++p1, &ignored);
6520               pathlen = (p - p1) / 2;
6521
6522               /* Save the pathname for event reporting and for
6523                  the next run command.  */
6524               hex2bin (p1, (gdb_byte *) pathname, pathlen);
6525               pathname[pathlen] = '\0';
6526
6527               /* This is freed during event handling.  */
6528               event->ws.value.execd_pathname = xstrdup (pathname);
6529               event->ws.kind = TARGET_WAITKIND_EXECD;
6530
6531               /* Skip the registers included in this packet, since
6532                  they may be for an architecture different from the
6533                  one used by the original program.  */
6534               skipregs = 1;
6535             }
6536           else if (strprefix (p, p1, "create"))
6537             {
6538               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6539               p = strchrnul (p1 + 1, ';');
6540             }
6541           else
6542             {
6543               ULONGEST pnum;
6544               char *p_temp;
6545
6546               if (skipregs)
6547                 {
6548                   p = strchrnul (p1 + 1, ';');
6549                   p++;
6550                   continue;
6551                 }
6552
6553               /* Maybe a real ``P'' register number.  */
6554               p_temp = unpack_varlen_hex (p, &pnum);
6555               /* If the first invalid character is the colon, we got a
6556                  register number.  Otherwise, it's an unknown stop
6557                  reason.  */
6558               if (p_temp == p1)
6559                 {
6560                   struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6561                   cached_reg_t cached_reg;
6562
6563                   if (reg == NULL)
6564                     error (_("Remote sent bad register number %s: %s\n\
6565 Packet: '%s'\n"),
6566                            hex_string (pnum), p, buf);
6567
6568                   cached_reg.num = reg->regnum;
6569
6570                   p = p1 + 1;
6571                   fieldsize = hex2bin (p, cached_reg.data,
6572                                        register_size (target_gdbarch (),
6573                                                       reg->regnum));
6574                   p += 2 * fieldsize;
6575                   if (fieldsize < register_size (target_gdbarch (),
6576                                                  reg->regnum))
6577                     warning (_("Remote reply is too short: %s"), buf);
6578
6579                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6580                 }
6581               else
6582                 {
6583                   /* Not a number.  Silently skip unknown optional
6584                      info.  */
6585                   p = strchrnul (p1 + 1, ';');
6586                 }
6587             }
6588
6589           if (*p != ';')
6590             error (_("Remote register badly formatted: %s\nhere: %s"),
6591                    buf, p);
6592           ++p;
6593         }
6594
6595       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6596         break;
6597
6598       /* fall through */
6599     case 'S':           /* Old style status, just signal only.  */
6600       {
6601         int sig;
6602
6603         event->ws.kind = TARGET_WAITKIND_STOPPED;
6604         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6605         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6606           event->ws.value.sig = (enum gdb_signal) sig;
6607         else
6608           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6609       }
6610       break;
6611     case 'w':           /* Thread exited.  */
6612       {
6613         char *p;
6614         ULONGEST value;
6615
6616         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6617         p = unpack_varlen_hex (&buf[1], &value);
6618         event->ws.value.integer = value;
6619         if (*p != ';')
6620           error (_("stop reply packet badly formatted: %s"), buf);
6621         event->ptid = read_ptid (++p, NULL);
6622         break;
6623       }
6624     case 'W':           /* Target exited.  */
6625     case 'X':
6626       {
6627         char *p;
6628         int pid;
6629         ULONGEST value;
6630
6631         /* GDB used to accept only 2 hex chars here.  Stubs should
6632            only send more if they detect GDB supports multi-process
6633            support.  */
6634         p = unpack_varlen_hex (&buf[1], &value);
6635
6636         if (buf[0] == 'W')
6637           {
6638             /* The remote process exited.  */
6639             event->ws.kind = TARGET_WAITKIND_EXITED;
6640             event->ws.value.integer = value;
6641           }
6642         else
6643           {
6644             /* The remote process exited with a signal.  */
6645             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6646             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6647               event->ws.value.sig = (enum gdb_signal) value;
6648             else
6649               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6650           }
6651
6652         /* If no process is specified, assume inferior_ptid.  */
6653         pid = ptid_get_pid (inferior_ptid);
6654         if (*p == '\0')
6655           ;
6656         else if (*p == ';')
6657           {
6658             p++;
6659
6660             if (*p == '\0')
6661               ;
6662             else if (startswith (p, "process:"))
6663               {
6664                 ULONGEST upid;
6665
6666                 p += sizeof ("process:") - 1;
6667                 unpack_varlen_hex (p, &upid);
6668                 pid = upid;
6669               }
6670             else
6671               error (_("unknown stop reply packet: %s"), buf);
6672           }
6673         else
6674           error (_("unknown stop reply packet: %s"), buf);
6675         event->ptid = pid_to_ptid (pid);
6676       }
6677       break;
6678     case 'N':
6679       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6680       event->ptid = minus_one_ptid;
6681       break;
6682     }
6683
6684   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6685     error (_("No process or thread specified in stop reply: %s"), buf);
6686 }
6687
6688 /* When the stub wants to tell GDB about a new notification reply, it
6689    sends a notification (%Stop, for example).  Those can come it at
6690    any time, hence, we have to make sure that any pending
6691    putpkt/getpkt sequence we're making is finished, before querying
6692    the stub for more events with the corresponding ack command
6693    (vStopped, for example).  E.g., if we started a vStopped sequence
6694    immediately upon receiving the notification, something like this
6695    could happen:
6696
6697     1.1) --> Hg 1
6698     1.2) <-- OK
6699     1.3) --> g
6700     1.4) <-- %Stop
6701     1.5) --> vStopped
6702     1.6) <-- (registers reply to step #1.3)
6703
6704    Obviously, the reply in step #1.6 would be unexpected to a vStopped
6705    query.
6706
6707    To solve this, whenever we parse a %Stop notification successfully,
6708    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6709    doing whatever we were doing:
6710
6711     2.1) --> Hg 1
6712     2.2) <-- OK
6713     2.3) --> g
6714     2.4) <-- %Stop
6715       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6716     2.5) <-- (registers reply to step #2.3)
6717
6718    Eventualy after step #2.5, we return to the event loop, which
6719    notices there's an event on the
6720    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6721    associated callback --- the function below.  At this point, we're
6722    always safe to start a vStopped sequence. :
6723
6724     2.6) --> vStopped
6725     2.7) <-- T05 thread:2
6726     2.8) --> vStopped
6727     2.9) --> OK
6728 */
6729
6730 void
6731 remote_notif_get_pending_events (struct notif_client *nc)
6732 {
6733   struct remote_state *rs = get_remote_state ();
6734
6735   if (rs->notif_state->pending_event[nc->id] != NULL)
6736     {
6737       if (notif_debug)
6738         fprintf_unfiltered (gdb_stdlog,
6739                             "notif: process: '%s' ack pending event\n",
6740                             nc->name);
6741
6742       /* acknowledge */
6743       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6744       rs->notif_state->pending_event[nc->id] = NULL;
6745
6746       while (1)
6747         {
6748           getpkt (&rs->buf, &rs->buf_size, 0);
6749           if (strcmp (rs->buf, "OK") == 0)
6750             break;
6751           else
6752             remote_notif_ack (nc, rs->buf);
6753         }
6754     }
6755   else
6756     {
6757       if (notif_debug)
6758         fprintf_unfiltered (gdb_stdlog,
6759                             "notif: process: '%s' no pending reply\n",
6760                             nc->name);
6761     }
6762 }
6763
6764 /* Called when it is decided that STOP_REPLY holds the info of the
6765    event that is to be returned to the core.  This function always
6766    destroys STOP_REPLY.  */
6767
6768 static ptid_t
6769 process_stop_reply (struct stop_reply *stop_reply,
6770                     struct target_waitstatus *status)
6771 {
6772   ptid_t ptid;
6773
6774   *status = stop_reply->ws;
6775   ptid = stop_reply->ptid;
6776
6777   /* If no thread/process was reported by the stub, assume the current
6778      inferior.  */
6779   if (ptid_equal (ptid, null_ptid))
6780     ptid = inferior_ptid;
6781
6782   if (status->kind != TARGET_WAITKIND_EXITED
6783       && status->kind != TARGET_WAITKIND_SIGNALLED
6784       && status->kind != TARGET_WAITKIND_NO_RESUMED)
6785     {
6786       struct private_thread_info *remote_thr;
6787
6788       /* Expedited registers.  */
6789       if (stop_reply->regcache)
6790         {
6791           struct regcache *regcache
6792             = get_thread_arch_regcache (ptid, target_gdbarch ());
6793           cached_reg_t *reg;
6794           int ix;
6795
6796           for (ix = 0;
6797                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6798                ix++)
6799             regcache_raw_supply (regcache, reg->num, reg->data);
6800           VEC_free (cached_reg_t, stop_reply->regcache);
6801         }
6802
6803       remote_notice_new_inferior (ptid, 0);
6804       remote_thr = demand_private_info (ptid);
6805       remote_thr->core = stop_reply->core;
6806       remote_thr->stop_reason = stop_reply->stop_reason;
6807       remote_thr->watch_data_address = stop_reply->watch_data_address;
6808     }
6809
6810   stop_reply_xfree (stop_reply);
6811   return ptid;
6812 }
6813
6814 /* The non-stop mode version of target_wait.  */
6815
6816 static ptid_t
6817 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6818 {
6819   struct remote_state *rs = get_remote_state ();
6820   struct stop_reply *stop_reply;
6821   int ret;
6822   int is_notif = 0;
6823
6824   /* If in non-stop mode, get out of getpkt even if a
6825      notification is received.  */
6826
6827   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6828                               0 /* forever */, &is_notif);
6829   while (1)
6830     {
6831       if (ret != -1 && !is_notif)
6832         switch (rs->buf[0])
6833           {
6834           case 'E':             /* Error of some sort.  */
6835             /* We're out of sync with the target now.  Did it continue
6836                or not?  We can't tell which thread it was in non-stop,
6837                so just ignore this.  */
6838             warning (_("Remote failure reply: %s"), rs->buf);
6839             break;
6840           case 'O':             /* Console output.  */
6841             remote_console_output (rs->buf + 1);
6842             break;
6843           default:
6844             warning (_("Invalid remote reply: %s"), rs->buf);
6845             break;
6846           }
6847
6848       /* Acknowledge a pending stop reply that may have arrived in the
6849          mean time.  */
6850       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6851         remote_notif_get_pending_events (&notif_client_stop);
6852
6853       /* If indeed we noticed a stop reply, we're done.  */
6854       stop_reply = queued_stop_reply (ptid);
6855       if (stop_reply != NULL)
6856         return process_stop_reply (stop_reply, status);
6857
6858       /* Still no event.  If we're just polling for an event, then
6859          return to the event loop.  */
6860       if (options & TARGET_WNOHANG)
6861         {
6862           status->kind = TARGET_WAITKIND_IGNORE;
6863           return minus_one_ptid;
6864         }
6865
6866       /* Otherwise do a blocking wait.  */
6867       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6868                                   1 /* forever */, &is_notif);
6869     }
6870 }
6871
6872 /* Wait until the remote machine stops, then return, storing status in
6873    STATUS just as `wait' would.  */
6874
6875 static ptid_t
6876 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6877 {
6878   struct remote_state *rs = get_remote_state ();
6879   ptid_t event_ptid = null_ptid;
6880   char *buf;
6881   struct stop_reply *stop_reply;
6882
6883  again:
6884
6885   status->kind = TARGET_WAITKIND_IGNORE;
6886   status->value.integer = 0;
6887
6888   stop_reply = queued_stop_reply (ptid);
6889   if (stop_reply != NULL)
6890     return process_stop_reply (stop_reply, status);
6891
6892   if (rs->cached_wait_status)
6893     /* Use the cached wait status, but only once.  */
6894     rs->cached_wait_status = 0;
6895   else
6896     {
6897       int ret;
6898       int is_notif;
6899       int forever = ((options & TARGET_WNOHANG) == 0
6900                      && wait_forever_enabled_p);
6901
6902       if (!rs->waiting_for_stop_reply)
6903         {
6904           status->kind = TARGET_WAITKIND_NO_RESUMED;
6905           return minus_one_ptid;
6906         }
6907
6908       /* FIXME: cagney/1999-09-27: If we're in async mode we should
6909          _never_ wait for ever -> test on target_is_async_p().
6910          However, before we do that we need to ensure that the caller
6911          knows how to take the target into/out of async mode.  */
6912       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6913                                   forever, &is_notif);
6914
6915       /* GDB gets a notification.  Return to core as this event is
6916          not interesting.  */
6917       if (ret != -1 && is_notif)
6918         return minus_one_ptid;
6919
6920       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6921         return minus_one_ptid;
6922     }
6923
6924   buf = rs->buf;
6925
6926   /* Assume that the target has acknowledged Ctrl-C unless we receive
6927      an 'F' or 'O' packet.  */
6928   if (buf[0] != 'F' && buf[0] != 'O')
6929     rs->ctrlc_pending_p = 0;
6930
6931   switch (buf[0])
6932     {
6933     case 'E':           /* Error of some sort.  */
6934       /* We're out of sync with the target now.  Did it continue or
6935          not?  Not is more likely, so report a stop.  */
6936       rs->waiting_for_stop_reply = 0;
6937
6938       warning (_("Remote failure reply: %s"), buf);
6939       status->kind = TARGET_WAITKIND_STOPPED;
6940       status->value.sig = GDB_SIGNAL_0;
6941       break;
6942     case 'F':           /* File-I/O request.  */
6943       /* GDB may access the inferior memory while handling the File-I/O
6944          request, but we don't want GDB accessing memory while waiting
6945          for a stop reply.  See the comments in putpkt_binary.  Set
6946          waiting_for_stop_reply to 0 temporarily.  */
6947       rs->waiting_for_stop_reply = 0;
6948       remote_fileio_request (buf, rs->ctrlc_pending_p);
6949       rs->ctrlc_pending_p = 0;
6950       /* GDB handled the File-I/O request, and the target is running
6951          again.  Keep waiting for events.  */
6952       rs->waiting_for_stop_reply = 1;
6953       break;
6954     case 'N': case 'T': case 'S': case 'X': case 'W':
6955       {
6956         struct stop_reply *stop_reply;
6957
6958         /* There is a stop reply to handle.  */
6959         rs->waiting_for_stop_reply = 0;
6960
6961         stop_reply
6962           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6963                                                       rs->buf);
6964
6965         event_ptid = process_stop_reply (stop_reply, status);
6966         break;
6967       }
6968     case 'O':           /* Console output.  */
6969       remote_console_output (buf + 1);
6970       break;
6971     case '\0':
6972       if (rs->last_sent_signal != GDB_SIGNAL_0)
6973         {
6974           /* Zero length reply means that we tried 'S' or 'C' and the
6975              remote system doesn't support it.  */
6976           target_terminal_ours_for_output ();
6977           printf_filtered
6978             ("Can't send signals to this remote system.  %s not sent.\n",
6979              gdb_signal_to_name (rs->last_sent_signal));
6980           rs->last_sent_signal = GDB_SIGNAL_0;
6981           target_terminal_inferior ();
6982
6983           strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6984           putpkt ((char *) buf);
6985           break;
6986         }
6987       /* else fallthrough */
6988     default:
6989       warning (_("Invalid remote reply: %s"), buf);
6990       break;
6991     }
6992
6993   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
6994     return minus_one_ptid;
6995   else if (status->kind == TARGET_WAITKIND_IGNORE)
6996     {
6997       /* Nothing interesting happened.  If we're doing a non-blocking
6998          poll, we're done.  Otherwise, go back to waiting.  */
6999       if (options & TARGET_WNOHANG)
7000         return minus_one_ptid;
7001       else
7002         goto again;
7003     }
7004   else if (status->kind != TARGET_WAITKIND_EXITED
7005            && status->kind != TARGET_WAITKIND_SIGNALLED)
7006     {
7007       if (!ptid_equal (event_ptid, null_ptid))
7008         record_currthread (rs, event_ptid);
7009       else
7010         event_ptid = inferior_ptid;
7011     }
7012   else
7013     /* A process exit.  Invalidate our notion of current thread.  */
7014     record_currthread (rs, minus_one_ptid);
7015
7016   return event_ptid;
7017 }
7018
7019 /* Wait until the remote machine stops, then return, storing status in
7020    STATUS just as `wait' would.  */
7021
7022 static ptid_t
7023 remote_wait (struct target_ops *ops,
7024              ptid_t ptid, struct target_waitstatus *status, int options)
7025 {
7026   ptid_t event_ptid;
7027
7028   if (target_is_non_stop_p ())
7029     event_ptid = remote_wait_ns (ptid, status, options);
7030   else
7031     event_ptid = remote_wait_as (ptid, status, options);
7032
7033   if (target_is_async_p ())
7034     {
7035       /* If there are are events left in the queue tell the event loop
7036          to return here.  */
7037       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7038         mark_async_event_handler (remote_async_inferior_event_token);
7039     }
7040
7041   return event_ptid;
7042 }
7043
7044 /* Fetch a single register using a 'p' packet.  */
7045
7046 static int
7047 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7048 {
7049   struct remote_state *rs = get_remote_state ();
7050   char *buf, *p;
7051   char regp[MAX_REGISTER_SIZE];
7052   int i;
7053
7054   if (packet_support (PACKET_p) == PACKET_DISABLE)
7055     return 0;
7056
7057   if (reg->pnum == -1)
7058     return 0;
7059
7060   p = rs->buf;
7061   *p++ = 'p';
7062   p += hexnumstr (p, reg->pnum);
7063   *p++ = '\0';
7064   putpkt (rs->buf);
7065   getpkt (&rs->buf, &rs->buf_size, 0);
7066
7067   buf = rs->buf;
7068
7069   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7070     {
7071     case PACKET_OK:
7072       break;
7073     case PACKET_UNKNOWN:
7074       return 0;
7075     case PACKET_ERROR:
7076       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7077              gdbarch_register_name (get_regcache_arch (regcache), 
7078                                     reg->regnum), 
7079              buf);
7080     }
7081
7082   /* If this register is unfetchable, tell the regcache.  */
7083   if (buf[0] == 'x')
7084     {
7085       regcache_raw_supply (regcache, reg->regnum, NULL);
7086       return 1;
7087     }
7088
7089   /* Otherwise, parse and supply the value.  */
7090   p = buf;
7091   i = 0;
7092   while (p[0] != 0)
7093     {
7094       if (p[1] == 0)
7095         error (_("fetch_register_using_p: early buf termination"));
7096
7097       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7098       p += 2;
7099     }
7100   regcache_raw_supply (regcache, reg->regnum, regp);
7101   return 1;
7102 }
7103
7104 /* Fetch the registers included in the target's 'g' packet.  */
7105
7106 static int
7107 send_g_packet (void)
7108 {
7109   struct remote_state *rs = get_remote_state ();
7110   int buf_len;
7111
7112   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7113   remote_send (&rs->buf, &rs->buf_size);
7114
7115   /* We can get out of synch in various cases.  If the first character
7116      in the buffer is not a hex character, assume that has happened
7117      and try to fetch another packet to read.  */
7118   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7119          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7120          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7121          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
7122     {
7123       if (remote_debug)
7124         fprintf_unfiltered (gdb_stdlog,
7125                             "Bad register packet; fetching a new packet\n");
7126       getpkt (&rs->buf, &rs->buf_size, 0);
7127     }
7128
7129   buf_len = strlen (rs->buf);
7130
7131   /* Sanity check the received packet.  */
7132   if (buf_len % 2 != 0)
7133     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7134
7135   return buf_len / 2;
7136 }
7137
7138 static void
7139 process_g_packet (struct regcache *regcache)
7140 {
7141   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7142   struct remote_state *rs = get_remote_state ();
7143   struct remote_arch_state *rsa = get_remote_arch_state ();
7144   int i, buf_len;
7145   char *p;
7146   char *regs;
7147
7148   buf_len = strlen (rs->buf);
7149
7150   /* Further sanity checks, with knowledge of the architecture.  */
7151   if (buf_len > 2 * rsa->sizeof_g_packet)
7152     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7153
7154   /* Save the size of the packet sent to us by the target.  It is used
7155      as a heuristic when determining the max size of packets that the
7156      target can safely receive.  */
7157   if (rsa->actual_register_packet_size == 0)
7158     rsa->actual_register_packet_size = buf_len;
7159
7160   /* If this is smaller than we guessed the 'g' packet would be,
7161      update our records.  A 'g' reply that doesn't include a register's
7162      value implies either that the register is not available, or that
7163      the 'p' packet must be used.  */
7164   if (buf_len < 2 * rsa->sizeof_g_packet)
7165     {
7166       rsa->sizeof_g_packet = buf_len / 2;
7167
7168       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7169         {
7170           if (rsa->regs[i].pnum == -1)
7171             continue;
7172
7173           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7174             rsa->regs[i].in_g_packet = 0;
7175           else
7176             rsa->regs[i].in_g_packet = 1;
7177         }
7178     }
7179
7180   regs = (char *) alloca (rsa->sizeof_g_packet);
7181
7182   /* Unimplemented registers read as all bits zero.  */
7183   memset (regs, 0, rsa->sizeof_g_packet);
7184
7185   /* Reply describes registers byte by byte, each byte encoded as two
7186      hex characters.  Suck them all up, then supply them to the
7187      register cacheing/storage mechanism.  */
7188
7189   p = rs->buf;
7190   for (i = 0; i < rsa->sizeof_g_packet; i++)
7191     {
7192       if (p[0] == 0 || p[1] == 0)
7193         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
7194         internal_error (__FILE__, __LINE__,
7195                         _("unexpected end of 'g' packet reply"));
7196
7197       if (p[0] == 'x' && p[1] == 'x')
7198         regs[i] = 0;            /* 'x' */
7199       else
7200         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7201       p += 2;
7202     }
7203
7204   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7205     {
7206       struct packet_reg *r = &rsa->regs[i];
7207
7208       if (r->in_g_packet)
7209         {
7210           if (r->offset * 2 >= strlen (rs->buf))
7211             /* This shouldn't happen - we adjusted in_g_packet above.  */
7212             internal_error (__FILE__, __LINE__,
7213                             _("unexpected end of 'g' packet reply"));
7214           else if (rs->buf[r->offset * 2] == 'x')
7215             {
7216               gdb_assert (r->offset * 2 < strlen (rs->buf));
7217               /* The register isn't available, mark it as such (at
7218                  the same time setting the value to zero).  */
7219               regcache_raw_supply (regcache, r->regnum, NULL);
7220             }
7221           else
7222             regcache_raw_supply (regcache, r->regnum,
7223                                  regs + r->offset);
7224         }
7225     }
7226 }
7227
7228 static void
7229 fetch_registers_using_g (struct regcache *regcache)
7230 {
7231   send_g_packet ();
7232   process_g_packet (regcache);
7233 }
7234
7235 /* Make the remote selected traceframe match GDB's selected
7236    traceframe.  */
7237
7238 static void
7239 set_remote_traceframe (void)
7240 {
7241   int newnum;
7242   struct remote_state *rs = get_remote_state ();
7243
7244   if (rs->remote_traceframe_number == get_traceframe_number ())
7245     return;
7246
7247   /* Avoid recursion, remote_trace_find calls us again.  */
7248   rs->remote_traceframe_number = get_traceframe_number ();
7249
7250   newnum = target_trace_find (tfind_number,
7251                               get_traceframe_number (), 0, 0, NULL);
7252
7253   /* Should not happen.  If it does, all bets are off.  */
7254   if (newnum != get_traceframe_number ())
7255     warning (_("could not set remote traceframe"));
7256 }
7257
7258 static void
7259 remote_fetch_registers (struct target_ops *ops,
7260                         struct regcache *regcache, int regnum)
7261 {
7262   struct remote_arch_state *rsa = get_remote_arch_state ();
7263   int i;
7264
7265   set_remote_traceframe ();
7266   set_general_thread (inferior_ptid);
7267
7268   if (regnum >= 0)
7269     {
7270       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7271
7272       gdb_assert (reg != NULL);
7273
7274       /* If this register might be in the 'g' packet, try that first -
7275          we are likely to read more than one register.  If this is the
7276          first 'g' packet, we might be overly optimistic about its
7277          contents, so fall back to 'p'.  */
7278       if (reg->in_g_packet)
7279         {
7280           fetch_registers_using_g (regcache);
7281           if (reg->in_g_packet)
7282             return;
7283         }
7284
7285       if (fetch_register_using_p (regcache, reg))
7286         return;
7287
7288       /* This register is not available.  */
7289       regcache_raw_supply (regcache, reg->regnum, NULL);
7290
7291       return;
7292     }
7293
7294   fetch_registers_using_g (regcache);
7295
7296   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7297     if (!rsa->regs[i].in_g_packet)
7298       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7299         {
7300           /* This register is not available.  */
7301           regcache_raw_supply (regcache, i, NULL);
7302         }
7303 }
7304
7305 /* Prepare to store registers.  Since we may send them all (using a
7306    'G' request), we have to read out the ones we don't want to change
7307    first.  */
7308
7309 static void
7310 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7311 {
7312   struct remote_arch_state *rsa = get_remote_arch_state ();
7313   int i;
7314   gdb_byte buf[MAX_REGISTER_SIZE];
7315
7316   /* Make sure the entire registers array is valid.  */
7317   switch (packet_support (PACKET_P))
7318     {
7319     case PACKET_DISABLE:
7320     case PACKET_SUPPORT_UNKNOWN:
7321       /* Make sure all the necessary registers are cached.  */
7322       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7323         if (rsa->regs[i].in_g_packet)
7324           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7325       break;
7326     case PACKET_ENABLE:
7327       break;
7328     }
7329 }
7330
7331 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
7332    packet was not recognized.  */
7333
7334 static int
7335 store_register_using_P (const struct regcache *regcache, 
7336                         struct packet_reg *reg)
7337 {
7338   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7339   struct remote_state *rs = get_remote_state ();
7340   /* Try storing a single register.  */
7341   char *buf = rs->buf;
7342   gdb_byte regp[MAX_REGISTER_SIZE];
7343   char *p;
7344
7345   if (packet_support (PACKET_P) == PACKET_DISABLE)
7346     return 0;
7347
7348   if (reg->pnum == -1)
7349     return 0;
7350
7351   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7352   p = buf + strlen (buf);
7353   regcache_raw_collect (regcache, reg->regnum, regp);
7354   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7355   putpkt (rs->buf);
7356   getpkt (&rs->buf, &rs->buf_size, 0);
7357
7358   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7359     {
7360     case PACKET_OK:
7361       return 1;
7362     case PACKET_ERROR:
7363       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7364              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7365     case PACKET_UNKNOWN:
7366       return 0;
7367     default:
7368       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7369     }
7370 }
7371
7372 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7373    contents of the register cache buffer.  FIXME: ignores errors.  */
7374
7375 static void
7376 store_registers_using_G (const struct regcache *regcache)
7377 {
7378   struct remote_state *rs = get_remote_state ();
7379   struct remote_arch_state *rsa = get_remote_arch_state ();
7380   gdb_byte *regs;
7381   char *p;
7382
7383   /* Extract all the registers in the regcache copying them into a
7384      local buffer.  */
7385   {
7386     int i;
7387
7388     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7389     memset (regs, 0, rsa->sizeof_g_packet);
7390     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7391       {
7392         struct packet_reg *r = &rsa->regs[i];
7393
7394         if (r->in_g_packet)
7395           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7396       }
7397   }
7398
7399   /* Command describes registers byte by byte,
7400      each byte encoded as two hex characters.  */
7401   p = rs->buf;
7402   *p++ = 'G';
7403   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7404      updated.  */
7405   bin2hex (regs, p, rsa->sizeof_g_packet);
7406   putpkt (rs->buf);
7407   getpkt (&rs->buf, &rs->buf_size, 0);
7408   if (packet_check_result (rs->buf) == PACKET_ERROR)
7409     error (_("Could not write registers; remote failure reply '%s'"), 
7410            rs->buf);
7411 }
7412
7413 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7414    of the register cache buffer.  FIXME: ignores errors.  */
7415
7416 static void
7417 remote_store_registers (struct target_ops *ops,
7418                         struct regcache *regcache, int regnum)
7419 {
7420   struct remote_arch_state *rsa = get_remote_arch_state ();
7421   int i;
7422
7423   set_remote_traceframe ();
7424   set_general_thread (inferior_ptid);
7425
7426   if (regnum >= 0)
7427     {
7428       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7429
7430       gdb_assert (reg != NULL);
7431
7432       /* Always prefer to store registers using the 'P' packet if
7433          possible; we often change only a small number of registers.
7434          Sometimes we change a larger number; we'd need help from a
7435          higher layer to know to use 'G'.  */
7436       if (store_register_using_P (regcache, reg))
7437         return;
7438
7439       /* For now, don't complain if we have no way to write the
7440          register.  GDB loses track of unavailable registers too
7441          easily.  Some day, this may be an error.  We don't have
7442          any way to read the register, either...  */
7443       if (!reg->in_g_packet)
7444         return;
7445
7446       store_registers_using_G (regcache);
7447       return;
7448     }
7449
7450   store_registers_using_G (regcache);
7451
7452   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7453     if (!rsa->regs[i].in_g_packet)
7454       if (!store_register_using_P (regcache, &rsa->regs[i]))
7455         /* See above for why we do not issue an error here.  */
7456         continue;
7457 }
7458 \f
7459
7460 /* Return the number of hex digits in num.  */
7461
7462 static int
7463 hexnumlen (ULONGEST num)
7464 {
7465   int i;
7466
7467   for (i = 0; num != 0; i++)
7468     num >>= 4;
7469
7470   return max (i, 1);
7471 }
7472
7473 /* Set BUF to the minimum number of hex digits representing NUM.  */
7474
7475 static int
7476 hexnumstr (char *buf, ULONGEST num)
7477 {
7478   int len = hexnumlen (num);
7479
7480   return hexnumnstr (buf, num, len);
7481 }
7482
7483
7484 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
7485
7486 static int
7487 hexnumnstr (char *buf, ULONGEST num, int width)
7488 {
7489   int i;
7490
7491   buf[width] = '\0';
7492
7493   for (i = width - 1; i >= 0; i--)
7494     {
7495       buf[i] = "0123456789abcdef"[(num & 0xf)];
7496       num >>= 4;
7497     }
7498
7499   return width;
7500 }
7501
7502 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
7503
7504 static CORE_ADDR
7505 remote_address_masked (CORE_ADDR addr)
7506 {
7507   unsigned int address_size = remote_address_size;
7508
7509   /* If "remoteaddresssize" was not set, default to target address size.  */
7510   if (!address_size)
7511     address_size = gdbarch_addr_bit (target_gdbarch ());
7512
7513   if (address_size > 0
7514       && address_size < (sizeof (ULONGEST) * 8))
7515     {
7516       /* Only create a mask when that mask can safely be constructed
7517          in a ULONGEST variable.  */
7518       ULONGEST mask = 1;
7519
7520       mask = (mask << address_size) - 1;
7521       addr &= mask;
7522     }
7523   return addr;
7524 }
7525
7526 /* Determine whether the remote target supports binary downloading.
7527    This is accomplished by sending a no-op memory write of zero length
7528    to the target at the specified address. It does not suffice to send
7529    the whole packet, since many stubs strip the eighth bit and
7530    subsequently compute a wrong checksum, which causes real havoc with
7531    remote_write_bytes.
7532
7533    NOTE: This can still lose if the serial line is not eight-bit
7534    clean.  In cases like this, the user should clear "remote
7535    X-packet".  */
7536
7537 static void
7538 check_binary_download (CORE_ADDR addr)
7539 {
7540   struct remote_state *rs = get_remote_state ();
7541
7542   switch (packet_support (PACKET_X))
7543     {
7544     case PACKET_DISABLE:
7545       break;
7546     case PACKET_ENABLE:
7547       break;
7548     case PACKET_SUPPORT_UNKNOWN:
7549       {
7550         char *p;
7551
7552         p = rs->buf;
7553         *p++ = 'X';
7554         p += hexnumstr (p, (ULONGEST) addr);
7555         *p++ = ',';
7556         p += hexnumstr (p, (ULONGEST) 0);
7557         *p++ = ':';
7558         *p = '\0';
7559
7560         putpkt_binary (rs->buf, (int) (p - rs->buf));
7561         getpkt (&rs->buf, &rs->buf_size, 0);
7562
7563         if (rs->buf[0] == '\0')
7564           {
7565             if (remote_debug)
7566               fprintf_unfiltered (gdb_stdlog,
7567                                   "binary downloading NOT "
7568                                   "supported by target\n");
7569             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7570           }
7571         else
7572           {
7573             if (remote_debug)
7574               fprintf_unfiltered (gdb_stdlog,
7575                                   "binary downloading supported by target\n");
7576             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7577           }
7578         break;
7579       }
7580     }
7581 }
7582
7583 /* Helper function to resize the payload in order to try to get a good
7584    alignment.  We try to write an amount of data such that the next write will
7585    start on an address aligned on REMOTE_ALIGN_WRITES.  */
7586
7587 static int
7588 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7589 {
7590   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7591 }
7592
7593 /* Write memory data directly to the remote machine.
7594    This does not inform the data cache; the data cache uses this.
7595    HEADER is the starting part of the packet.
7596    MEMADDR is the address in the remote memory space.
7597    MYADDR is the address of the buffer in our space.
7598    LEN_UNITS is the number of addressable units to write.
7599    UNIT_SIZE is the length in bytes of an addressable unit.
7600    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7601    should send data as binary ('X'), or hex-encoded ('M').
7602
7603    The function creates packet of the form
7604        <HEADER><ADDRESS>,<LENGTH>:<DATA>
7605
7606    where encoding of <DATA> is terminated by PACKET_FORMAT.
7607
7608    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7609    are omitted.
7610
7611    Return the transferred status, error or OK (an
7612    'enum target_xfer_status' value).  Save the number of addressable units
7613    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
7614
7615    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7616    exchange between gdb and the stub could look like (?? in place of the
7617    checksum):
7618
7619    -> $m1000,4#??
7620    <- aaaabbbbccccdddd
7621
7622    -> $M1000,3:eeeeffffeeee#??
7623    <- OK
7624
7625    -> $m1000,4#??
7626    <- eeeeffffeeeedddd  */
7627
7628 static enum target_xfer_status
7629 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7630                         const gdb_byte *myaddr, ULONGEST len_units,
7631                         int unit_size, ULONGEST *xfered_len_units,
7632                         char packet_format, int use_length)
7633 {
7634   struct remote_state *rs = get_remote_state ();
7635   char *p;
7636   char *plen = NULL;
7637   int plenlen = 0;
7638   int todo_units;
7639   int units_written;
7640   int payload_capacity_bytes;
7641   int payload_length_bytes;
7642
7643   if (packet_format != 'X' && packet_format != 'M')
7644     internal_error (__FILE__, __LINE__,
7645                     _("remote_write_bytes_aux: bad packet format"));
7646
7647   if (len_units == 0)
7648     return TARGET_XFER_EOF;
7649
7650   payload_capacity_bytes = get_memory_write_packet_size ();
7651
7652   /* The packet buffer will be large enough for the payload;
7653      get_memory_packet_size ensures this.  */
7654   rs->buf[0] = '\0';
7655
7656   /* Compute the size of the actual payload by subtracting out the
7657      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
7658
7659   payload_capacity_bytes -= strlen ("$,:#NN");
7660   if (!use_length)
7661     /* The comma won't be used.  */
7662     payload_capacity_bytes += 1;
7663   payload_capacity_bytes -= strlen (header);
7664   payload_capacity_bytes -= hexnumlen (memaddr);
7665
7666   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
7667
7668   strcat (rs->buf, header);
7669   p = rs->buf + strlen (header);
7670
7671   /* Compute a best guess of the number of bytes actually transfered.  */
7672   if (packet_format == 'X')
7673     {
7674       /* Best guess at number of bytes that will fit.  */
7675       todo_units = min (len_units, payload_capacity_bytes / unit_size);
7676       if (use_length)
7677         payload_capacity_bytes -= hexnumlen (todo_units);
7678       todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7679     }
7680   else
7681     {
7682       /* Number of bytes that will fit.  */
7683       todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7684       if (use_length)
7685         payload_capacity_bytes -= hexnumlen (todo_units);
7686       todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7687     }
7688
7689   if (todo_units <= 0)
7690     internal_error (__FILE__, __LINE__,
7691                     _("minimum packet size too small to write data"));
7692
7693   /* If we already need another packet, then try to align the end
7694      of this packet to a useful boundary.  */
7695   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7696     todo_units = align_for_efficient_write (todo_units, memaddr);
7697
7698   /* Append "<memaddr>".  */
7699   memaddr = remote_address_masked (memaddr);
7700   p += hexnumstr (p, (ULONGEST) memaddr);
7701
7702   if (use_length)
7703     {
7704       /* Append ",".  */
7705       *p++ = ',';
7706
7707       /* Append the length and retain its location and size.  It may need to be
7708          adjusted once the packet body has been created.  */
7709       plen = p;
7710       plenlen = hexnumstr (p, (ULONGEST) todo_units);
7711       p += plenlen;
7712     }
7713
7714   /* Append ":".  */
7715   *p++ = ':';
7716   *p = '\0';
7717
7718   /* Append the packet body.  */
7719   if (packet_format == 'X')
7720     {
7721       /* Binary mode.  Send target system values byte by byte, in
7722          increasing byte addresses.  Only escape certain critical
7723          characters.  */
7724       payload_length_bytes =
7725           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7726                                 &units_written, payload_capacity_bytes);
7727
7728       /* If not all TODO units fit, then we'll need another packet.  Make
7729          a second try to keep the end of the packet aligned.  Don't do
7730          this if the packet is tiny.  */
7731       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7732         {
7733           int new_todo_units;
7734
7735           new_todo_units = align_for_efficient_write (units_written, memaddr);
7736
7737           if (new_todo_units != units_written)
7738             payload_length_bytes =
7739                 remote_escape_output (myaddr, new_todo_units, unit_size,
7740                                       (gdb_byte *) p, &units_written,
7741                                       payload_capacity_bytes);
7742         }
7743
7744       p += payload_length_bytes;
7745       if (use_length && units_written < todo_units)
7746         {
7747           /* Escape chars have filled up the buffer prematurely,
7748              and we have actually sent fewer units than planned.
7749              Fix-up the length field of the packet.  Use the same
7750              number of characters as before.  */
7751           plen += hexnumnstr (plen, (ULONGEST) units_written,
7752                               plenlen);
7753           *plen = ':';  /* overwrite \0 from hexnumnstr() */
7754         }
7755     }
7756   else
7757     {
7758       /* Normal mode: Send target system values byte by byte, in
7759          increasing byte addresses.  Each byte is encoded as a two hex
7760          value.  */
7761       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7762       units_written = todo_units;
7763     }
7764
7765   putpkt_binary (rs->buf, (int) (p - rs->buf));
7766   getpkt (&rs->buf, &rs->buf_size, 0);
7767
7768   if (rs->buf[0] == 'E')
7769     return TARGET_XFER_E_IO;
7770
7771   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7772      send fewer units than we'd planned.  */
7773   *xfered_len_units = (ULONGEST) units_written;
7774   return TARGET_XFER_OK;
7775 }
7776
7777 /* Write memory data directly to the remote machine.
7778    This does not inform the data cache; the data cache uses this.
7779    MEMADDR is the address in the remote memory space.
7780    MYADDR is the address of the buffer in our space.
7781    LEN is the number of bytes.
7782
7783    Return the transferred status, error or OK (an
7784    'enum target_xfer_status' value).  Save the number of bytes
7785    transferred in *XFERED_LEN.  Only transfer a single packet.  */
7786
7787 static enum target_xfer_status
7788 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7789                     int unit_size, ULONGEST *xfered_len)
7790 {
7791   char *packet_format = 0;
7792
7793   /* Check whether the target supports binary download.  */
7794   check_binary_download (memaddr);
7795
7796   switch (packet_support (PACKET_X))
7797     {
7798     case PACKET_ENABLE:
7799       packet_format = "X";
7800       break;
7801     case PACKET_DISABLE:
7802       packet_format = "M";
7803       break;
7804     case PACKET_SUPPORT_UNKNOWN:
7805       internal_error (__FILE__, __LINE__,
7806                       _("remote_write_bytes: bad internal state"));
7807     default:
7808       internal_error (__FILE__, __LINE__, _("bad switch"));
7809     }
7810
7811   return remote_write_bytes_aux (packet_format,
7812                                  memaddr, myaddr, len, unit_size, xfered_len,
7813                                  packet_format[0], 1);
7814 }
7815
7816 /* Read memory data directly from the remote machine.
7817    This does not use the data cache; the data cache uses this.
7818    MEMADDR is the address in the remote memory space.
7819    MYADDR is the address of the buffer in our space.
7820    LEN_UNITS is the number of addressable memory units to read..
7821    UNIT_SIZE is the length in bytes of an addressable unit.
7822
7823    Return the transferred status, error or OK (an
7824    'enum target_xfer_status' value).  Save the number of bytes
7825    transferred in *XFERED_LEN_UNITS.
7826
7827    See the comment of remote_write_bytes_aux for an example of
7828    memory read/write exchange between gdb and the stub.  */
7829
7830 static enum target_xfer_status
7831 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7832                      int unit_size, ULONGEST *xfered_len_units)
7833 {
7834   struct remote_state *rs = get_remote_state ();
7835   int buf_size_bytes;           /* Max size of packet output buffer.  */
7836   char *p;
7837   int todo_units;
7838   int decoded_bytes;
7839
7840   buf_size_bytes = get_memory_read_packet_size ();
7841   /* The packet buffer will be large enough for the payload;
7842      get_memory_packet_size ensures this.  */
7843
7844   /* Number of units that will fit.  */
7845   todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7846
7847   /* Construct "m"<memaddr>","<len>".  */
7848   memaddr = remote_address_masked (memaddr);
7849   p = rs->buf;
7850   *p++ = 'm';
7851   p += hexnumstr (p, (ULONGEST) memaddr);
7852   *p++ = ',';
7853   p += hexnumstr (p, (ULONGEST) todo_units);
7854   *p = '\0';
7855   putpkt (rs->buf);
7856   getpkt (&rs->buf, &rs->buf_size, 0);
7857   if (rs->buf[0] == 'E'
7858       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7859       && rs->buf[3] == '\0')
7860     return TARGET_XFER_E_IO;
7861   /* Reply describes memory byte by byte, each byte encoded as two hex
7862      characters.  */
7863   p = rs->buf;
7864   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7865   /* Return what we have.  Let higher layers handle partial reads.  */
7866   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7867   return TARGET_XFER_OK;
7868 }
7869
7870 /* Using the set of read-only target sections of remote, read live
7871    read-only memory.
7872
7873    For interface/parameters/return description see target.h,
7874    to_xfer_partial.  */
7875
7876 static enum target_xfer_status
7877 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7878                                    ULONGEST memaddr, ULONGEST len,
7879                                    int unit_size, ULONGEST *xfered_len)
7880 {
7881   struct target_section *secp;
7882   struct target_section_table *table;
7883
7884   secp = target_section_by_addr (ops, memaddr);
7885   if (secp != NULL
7886       && (bfd_get_section_flags (secp->the_bfd_section->owner,
7887                                  secp->the_bfd_section)
7888           & SEC_READONLY))
7889     {
7890       struct target_section *p;
7891       ULONGEST memend = memaddr + len;
7892
7893       table = target_get_section_table (ops);
7894
7895       for (p = table->sections; p < table->sections_end; p++)
7896         {
7897           if (memaddr >= p->addr)
7898             {
7899               if (memend <= p->endaddr)
7900                 {
7901                   /* Entire transfer is within this section.  */
7902                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7903                                               xfered_len);
7904                 }
7905               else if (memaddr >= p->endaddr)
7906                 {
7907                   /* This section ends before the transfer starts.  */
7908                   continue;
7909                 }
7910               else
7911                 {
7912                   /* This section overlaps the transfer.  Just do half.  */
7913                   len = p->endaddr - memaddr;
7914                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7915                                               xfered_len);
7916                 }
7917             }
7918         }
7919     }
7920
7921   return TARGET_XFER_EOF;
7922 }
7923
7924 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7925    first if the requested memory is unavailable in traceframe.
7926    Otherwise, fall back to remote_read_bytes_1.  */
7927
7928 static enum target_xfer_status
7929 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7930                    gdb_byte *myaddr, ULONGEST len, int unit_size,
7931                    ULONGEST *xfered_len)
7932 {
7933   if (len == 0)
7934     return TARGET_XFER_EOF;
7935
7936   if (get_traceframe_number () != -1)
7937     {
7938       VEC(mem_range_s) *available;
7939
7940       /* If we fail to get the set of available memory, then the
7941          target does not support querying traceframe info, and so we
7942          attempt reading from the traceframe anyway (assuming the
7943          target implements the old QTro packet then).  */
7944       if (traceframe_available_memory (&available, memaddr, len))
7945         {
7946           struct cleanup *old_chain;
7947
7948           old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7949
7950           if (VEC_empty (mem_range_s, available)
7951               || VEC_index (mem_range_s, available, 0)->start != memaddr)
7952             {
7953               enum target_xfer_status res;
7954
7955               /* Don't read into the traceframe's available
7956                  memory.  */
7957               if (!VEC_empty (mem_range_s, available))
7958                 {
7959                   LONGEST oldlen = len;
7960
7961                   len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7962                   gdb_assert (len <= oldlen);
7963                 }
7964
7965               do_cleanups (old_chain);
7966
7967               /* This goes through the topmost target again.  */
7968               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7969                                                        len, unit_size, xfered_len);
7970               if (res == TARGET_XFER_OK)
7971                 return TARGET_XFER_OK;
7972               else
7973                 {
7974                   /* No use trying further, we know some memory starting
7975                      at MEMADDR isn't available.  */
7976                   *xfered_len = len;
7977                   return TARGET_XFER_UNAVAILABLE;
7978                 }
7979             }
7980
7981           /* Don't try to read more than how much is available, in
7982              case the target implements the deprecated QTro packet to
7983              cater for older GDBs (the target's knowledge of read-only
7984              sections may be outdated by now).  */
7985           len = VEC_index (mem_range_s, available, 0)->length;
7986
7987           do_cleanups (old_chain);
7988         }
7989     }
7990
7991   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7992 }
7993
7994 \f
7995
7996 /* Sends a packet with content determined by the printf format string
7997    FORMAT and the remaining arguments, then gets the reply.  Returns
7998    whether the packet was a success, a failure, or unknown.  */
7999
8000 static enum packet_result remote_send_printf (const char *format, ...)
8001   ATTRIBUTE_PRINTF (1, 2);
8002
8003 static enum packet_result
8004 remote_send_printf (const char *format, ...)
8005 {
8006   struct remote_state *rs = get_remote_state ();
8007   int max_size = get_remote_packet_size ();
8008   va_list ap;
8009
8010   va_start (ap, format);
8011
8012   rs->buf[0] = '\0';
8013   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8014     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8015
8016   if (putpkt (rs->buf) < 0)
8017     error (_("Communication problem with target."));
8018
8019   rs->buf[0] = '\0';
8020   getpkt (&rs->buf, &rs->buf_size, 0);
8021
8022   return packet_check_result (rs->buf);
8023 }
8024
8025 static void
8026 restore_remote_timeout (void *p)
8027 {
8028   int value = *(int *)p;
8029
8030   remote_timeout = value;
8031 }
8032
8033 /* Flash writing can take quite some time.  We'll set
8034    effectively infinite timeout for flash operations.
8035    In future, we'll need to decide on a better approach.  */
8036 static const int remote_flash_timeout = 1000;
8037
8038 static void
8039 remote_flash_erase (struct target_ops *ops,
8040                     ULONGEST address, LONGEST length)
8041 {
8042   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8043   int saved_remote_timeout = remote_timeout;
8044   enum packet_result ret;
8045   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8046                                           &saved_remote_timeout);
8047
8048   remote_timeout = remote_flash_timeout;
8049
8050   ret = remote_send_printf ("vFlashErase:%s,%s",
8051                             phex (address, addr_size),
8052                             phex (length, 4));
8053   switch (ret)
8054     {
8055     case PACKET_UNKNOWN:
8056       error (_("Remote target does not support flash erase"));
8057     case PACKET_ERROR:
8058       error (_("Error erasing flash with vFlashErase packet"));
8059     default:
8060       break;
8061     }
8062
8063   do_cleanups (back_to);
8064 }
8065
8066 static enum target_xfer_status
8067 remote_flash_write (struct target_ops *ops, ULONGEST address,
8068                     ULONGEST length, ULONGEST *xfered_len,
8069                     const gdb_byte *data)
8070 {
8071   int saved_remote_timeout = remote_timeout;
8072   enum target_xfer_status ret;
8073   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8074                                           &saved_remote_timeout);
8075
8076   remote_timeout = remote_flash_timeout;
8077   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8078                                 xfered_len,'X', 0);
8079   do_cleanups (back_to);
8080
8081   return ret;
8082 }
8083
8084 static void
8085 remote_flash_done (struct target_ops *ops)
8086 {
8087   int saved_remote_timeout = remote_timeout;
8088   int ret;
8089   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8090                                           &saved_remote_timeout);
8091
8092   remote_timeout = remote_flash_timeout;
8093   ret = remote_send_printf ("vFlashDone");
8094   do_cleanups (back_to);
8095
8096   switch (ret)
8097     {
8098     case PACKET_UNKNOWN:
8099       error (_("Remote target does not support vFlashDone"));
8100     case PACKET_ERROR:
8101       error (_("Error finishing flash operation"));
8102     default:
8103       break;
8104     }
8105 }
8106
8107 static void
8108 remote_files_info (struct target_ops *ignore)
8109 {
8110   puts_filtered ("Debugging a target over a serial line.\n");
8111 }
8112 \f
8113 /* Stuff for dealing with the packets which are part of this protocol.
8114    See comment at top of file for details.  */
8115
8116 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8117    error to higher layers.  Called when a serial error is detected.
8118    The exception message is STRING, followed by a colon and a blank,
8119    the system error message for errno at function entry and final dot
8120    for output compatibility with throw_perror_with_name.  */
8121
8122 static void
8123 unpush_and_perror (const char *string)
8124 {
8125   int saved_errno = errno;
8126
8127   remote_unpush_target ();
8128   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8129                safe_strerror (saved_errno));
8130 }
8131
8132 /* Read a single character from the remote end.  The current quit
8133    handler is overridden to avoid quitting in the middle of packet
8134    sequence, as that would break communication with the remote server.
8135    See remote_serial_quit_handler for more detail.  */
8136
8137 static int
8138 readchar (int timeout)
8139 {
8140   int ch;
8141   struct remote_state *rs = get_remote_state ();
8142   struct cleanup *old_chain;
8143
8144   old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8145
8146   rs->got_ctrlc_during_io = 0;
8147
8148   ch = serial_readchar (rs->remote_desc, timeout);
8149
8150   if (rs->got_ctrlc_during_io)
8151     set_quit_flag ();
8152
8153   do_cleanups (old_chain);
8154
8155   if (ch >= 0)
8156     return ch;
8157
8158   switch ((enum serial_rc) ch)
8159     {
8160     case SERIAL_EOF:
8161       remote_unpush_target ();
8162       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8163       /* no return */
8164     case SERIAL_ERROR:
8165       unpush_and_perror (_("Remote communication error.  "
8166                            "Target disconnected."));
8167       /* no return */
8168     case SERIAL_TIMEOUT:
8169       break;
8170     }
8171   return ch;
8172 }
8173
8174 /* Wrapper for serial_write that closes the target and throws if
8175    writing fails.  The current quit handler is overridden to avoid
8176    quitting in the middle of packet sequence, as that would break
8177    communication with the remote server.  See
8178    remote_serial_quit_handler for more detail.  */
8179
8180 static void
8181 remote_serial_write (const char *str, int len)
8182 {
8183   struct remote_state *rs = get_remote_state ();
8184   struct cleanup *old_chain;
8185
8186   old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8187
8188   rs->got_ctrlc_during_io = 0;
8189
8190   if (serial_write (rs->remote_desc, str, len))
8191     {
8192       unpush_and_perror (_("Remote communication error.  "
8193                            "Target disconnected."));
8194     }
8195
8196   if (rs->got_ctrlc_during_io)
8197     set_quit_flag ();
8198
8199   do_cleanups (old_chain);
8200 }
8201
8202 /* Send the command in *BUF to the remote machine, and read the reply
8203    into *BUF.  Report an error if we get an error reply.  Resize
8204    *BUF using xrealloc if necessary to hold the result, and update
8205    *SIZEOF_BUF.  */
8206
8207 static void
8208 remote_send (char **buf,
8209              long *sizeof_buf)
8210 {
8211   putpkt (*buf);
8212   getpkt (buf, sizeof_buf, 0);
8213
8214   if ((*buf)[0] == 'E')
8215     error (_("Remote failure reply: %s"), *buf);
8216 }
8217
8218 /* Return a pointer to an xmalloc'ed string representing an escaped
8219    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
8220    etc.  The caller is responsible for releasing the returned
8221    memory.  */
8222
8223 static char *
8224 escape_buffer (const char *buf, int n)
8225 {
8226   struct cleanup *old_chain;
8227   struct ui_file *stb;
8228   char *str;
8229
8230   stb = mem_fileopen ();
8231   old_chain = make_cleanup_ui_file_delete (stb);
8232
8233   fputstrn_unfiltered (buf, n, '\\', stb);
8234   str = ui_file_xstrdup (stb, NULL);
8235   do_cleanups (old_chain);
8236   return str;
8237 }
8238
8239 /* Display a null-terminated packet on stdout, for debugging, using C
8240    string notation.  */
8241
8242 static void
8243 print_packet (const char *buf)
8244 {
8245   puts_filtered ("\"");
8246   fputstr_filtered (buf, '"', gdb_stdout);
8247   puts_filtered ("\"");
8248 }
8249
8250 int
8251 putpkt (const char *buf)
8252 {
8253   return putpkt_binary (buf, strlen (buf));
8254 }
8255
8256 /* Send a packet to the remote machine, with error checking.  The data
8257    of the packet is in BUF.  The string in BUF can be at most
8258    get_remote_packet_size () - 5 to account for the $, # and checksum,
8259    and for a possible /0 if we are debugging (remote_debug) and want
8260    to print the sent packet as a string.  */
8261
8262 static int
8263 putpkt_binary (const char *buf, int cnt)
8264 {
8265   struct remote_state *rs = get_remote_state ();
8266   int i;
8267   unsigned char csum = 0;
8268   char *buf2 = (char *) xmalloc (cnt + 6);
8269   struct cleanup *old_chain = make_cleanup (xfree, buf2);
8270
8271   int ch;
8272   int tcount = 0;
8273   char *p;
8274
8275   /* Catch cases like trying to read memory or listing threads while
8276      we're waiting for a stop reply.  The remote server wouldn't be
8277      ready to handle this request, so we'd hang and timeout.  We don't
8278      have to worry about this in synchronous mode, because in that
8279      case it's not possible to issue a command while the target is
8280      running.  This is not a problem in non-stop mode, because in that
8281      case, the stub is always ready to process serial input.  */
8282   if (!target_is_non_stop_p ()
8283       && target_is_async_p ()
8284       && rs->waiting_for_stop_reply)
8285     {
8286       error (_("Cannot execute this command while the target is running.\n"
8287                "Use the \"interrupt\" command to stop the target\n"
8288                "and then try again."));
8289     }
8290
8291   /* We're sending out a new packet.  Make sure we don't look at a
8292      stale cached response.  */
8293   rs->cached_wait_status = 0;
8294
8295   /* Copy the packet into buffer BUF2, encapsulating it
8296      and giving it a checksum.  */
8297
8298   p = buf2;
8299   *p++ = '$';
8300
8301   for (i = 0; i < cnt; i++)
8302     {
8303       csum += buf[i];
8304       *p++ = buf[i];
8305     }
8306   *p++ = '#';
8307   *p++ = tohex ((csum >> 4) & 0xf);
8308   *p++ = tohex (csum & 0xf);
8309
8310   /* Send it over and over until we get a positive ack.  */
8311
8312   while (1)
8313     {
8314       int started_error_output = 0;
8315
8316       if (remote_debug)
8317         {
8318           struct cleanup *old_chain;
8319           char *str;
8320
8321           *p = '\0';
8322           str = escape_buffer (buf2, p - buf2);
8323           old_chain = make_cleanup (xfree, str);
8324           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8325           gdb_flush (gdb_stdlog);
8326           do_cleanups (old_chain);
8327         }
8328       remote_serial_write (buf2, p - buf2);
8329
8330       /* If this is a no acks version of the remote protocol, send the
8331          packet and move on.  */
8332       if (rs->noack_mode)
8333         break;
8334
8335       /* Read until either a timeout occurs (-2) or '+' is read.
8336          Handle any notification that arrives in the mean time.  */
8337       while (1)
8338         {
8339           ch = readchar (remote_timeout);
8340
8341           if (remote_debug)
8342             {
8343               switch (ch)
8344                 {
8345                 case '+':
8346                 case '-':
8347                 case SERIAL_TIMEOUT:
8348                 case '$':
8349                 case '%':
8350                   if (started_error_output)
8351                     {
8352                       putchar_unfiltered ('\n');
8353                       started_error_output = 0;
8354                     }
8355                 }
8356             }
8357
8358           switch (ch)
8359             {
8360             case '+':
8361               if (remote_debug)
8362                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8363               do_cleanups (old_chain);
8364               return 1;
8365             case '-':
8366               if (remote_debug)
8367                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8368               /* FALLTHROUGH */
8369             case SERIAL_TIMEOUT:
8370               tcount++;
8371               if (tcount > 3)
8372                 {
8373                   do_cleanups (old_chain);
8374                   return 0;
8375                 }
8376               break;            /* Retransmit buffer.  */
8377             case '$':
8378               {
8379                 if (remote_debug)
8380                   fprintf_unfiltered (gdb_stdlog,
8381                                       "Packet instead of Ack, ignoring it\n");
8382                 /* It's probably an old response sent because an ACK
8383                    was lost.  Gobble up the packet and ack it so it
8384                    doesn't get retransmitted when we resend this
8385                    packet.  */
8386                 skip_frame ();
8387                 remote_serial_write ("+", 1);
8388                 continue;       /* Now, go look for +.  */
8389               }
8390
8391             case '%':
8392               {
8393                 int val;
8394
8395                 /* If we got a notification, handle it, and go back to looking
8396                    for an ack.  */
8397                 /* We've found the start of a notification.  Now
8398                    collect the data.  */
8399                 val = read_frame (&rs->buf, &rs->buf_size);
8400                 if (val >= 0)
8401                   {
8402                     if (remote_debug)
8403                       {
8404                         struct cleanup *old_chain;
8405                         char *str;
8406
8407                         str = escape_buffer (rs->buf, val);
8408                         old_chain = make_cleanup (xfree, str);
8409                         fprintf_unfiltered (gdb_stdlog,
8410                                             "  Notification received: %s\n",
8411                                             str);
8412                         do_cleanups (old_chain);
8413                       }
8414                     handle_notification (rs->notif_state, rs->buf);
8415                     /* We're in sync now, rewait for the ack.  */
8416                     tcount = 0;
8417                   }
8418                 else
8419                   {
8420                     if (remote_debug)
8421                       {
8422                         if (!started_error_output)
8423                           {
8424                             started_error_output = 1;
8425                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8426                           }
8427                         fputc_unfiltered (ch & 0177, gdb_stdlog);
8428                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8429                       }
8430                   }
8431                 continue;
8432               }
8433               /* fall-through */
8434             default:
8435               if (remote_debug)
8436                 {
8437                   if (!started_error_output)
8438                     {
8439                       started_error_output = 1;
8440                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8441                     }
8442                   fputc_unfiltered (ch & 0177, gdb_stdlog);
8443                 }
8444               continue;
8445             }
8446           break;                /* Here to retransmit.  */
8447         }
8448
8449 #if 0
8450       /* This is wrong.  If doing a long backtrace, the user should be
8451          able to get out next time we call QUIT, without anything as
8452          violent as interrupt_query.  If we want to provide a way out of
8453          here without getting to the next QUIT, it should be based on
8454          hitting ^C twice as in remote_wait.  */
8455       if (quit_flag)
8456         {
8457           quit_flag = 0;
8458           interrupt_query ();
8459         }
8460 #endif
8461     }
8462
8463   do_cleanups (old_chain);
8464   return 0;
8465 }
8466
8467 /* Come here after finding the start of a frame when we expected an
8468    ack.  Do our best to discard the rest of this packet.  */
8469
8470 static void
8471 skip_frame (void)
8472 {
8473   int c;
8474
8475   while (1)
8476     {
8477       c = readchar (remote_timeout);
8478       switch (c)
8479         {
8480         case SERIAL_TIMEOUT:
8481           /* Nothing we can do.  */
8482           return;
8483         case '#':
8484           /* Discard the two bytes of checksum and stop.  */
8485           c = readchar (remote_timeout);
8486           if (c >= 0)
8487             c = readchar (remote_timeout);
8488
8489           return;
8490         case '*':               /* Run length encoding.  */
8491           /* Discard the repeat count.  */
8492           c = readchar (remote_timeout);
8493           if (c < 0)
8494             return;
8495           break;
8496         default:
8497           /* A regular character.  */
8498           break;
8499         }
8500     }
8501 }
8502
8503 /* Come here after finding the start of the frame.  Collect the rest
8504    into *BUF, verifying the checksum, length, and handling run-length
8505    compression.  NUL terminate the buffer.  If there is not enough room,
8506    expand *BUF using xrealloc.
8507
8508    Returns -1 on error, number of characters in buffer (ignoring the
8509    trailing NULL) on success. (could be extended to return one of the
8510    SERIAL status indications).  */
8511
8512 static long
8513 read_frame (char **buf_p,
8514             long *sizeof_buf)
8515 {
8516   unsigned char csum;
8517   long bc;
8518   int c;
8519   char *buf = *buf_p;
8520   struct remote_state *rs = get_remote_state ();
8521
8522   csum = 0;
8523   bc = 0;
8524
8525   while (1)
8526     {
8527       c = readchar (remote_timeout);
8528       switch (c)
8529         {
8530         case SERIAL_TIMEOUT:
8531           if (remote_debug)
8532             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8533           return -1;
8534         case '$':
8535           if (remote_debug)
8536             fputs_filtered ("Saw new packet start in middle of old one\n",
8537                             gdb_stdlog);
8538           return -1;            /* Start a new packet, count retries.  */
8539         case '#':
8540           {
8541             unsigned char pktcsum;
8542             int check_0 = 0;
8543             int check_1 = 0;
8544
8545             buf[bc] = '\0';
8546
8547             check_0 = readchar (remote_timeout);
8548             if (check_0 >= 0)
8549               check_1 = readchar (remote_timeout);
8550
8551             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8552               {
8553                 if (remote_debug)
8554                   fputs_filtered ("Timeout in checksum, retrying\n",
8555                                   gdb_stdlog);
8556                 return -1;
8557               }
8558             else if (check_0 < 0 || check_1 < 0)
8559               {
8560                 if (remote_debug)
8561                   fputs_filtered ("Communication error in checksum\n",
8562                                   gdb_stdlog);
8563                 return -1;
8564               }
8565
8566             /* Don't recompute the checksum; with no ack packets we
8567                don't have any way to indicate a packet retransmission
8568                is necessary.  */
8569             if (rs->noack_mode)
8570               return bc;
8571
8572             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8573             if (csum == pktcsum)
8574               return bc;
8575
8576             if (remote_debug)
8577               {
8578                 struct cleanup *old_chain;
8579                 char *str;
8580
8581                 str = escape_buffer (buf, bc);
8582                 old_chain = make_cleanup (xfree, str);
8583                 fprintf_unfiltered (gdb_stdlog,
8584                                     "Bad checksum, sentsum=0x%x, "
8585                                     "csum=0x%x, buf=%s\n",
8586                                     pktcsum, csum, str);
8587                 do_cleanups (old_chain);
8588               }
8589             /* Number of characters in buffer ignoring trailing
8590                NULL.  */
8591             return -1;
8592           }
8593         case '*':               /* Run length encoding.  */
8594           {
8595             int repeat;
8596
8597             csum += c;
8598             c = readchar (remote_timeout);
8599             csum += c;
8600             repeat = c - ' ' + 3;       /* Compute repeat count.  */
8601
8602             /* The character before ``*'' is repeated.  */
8603
8604             if (repeat > 0 && repeat <= 255 && bc > 0)
8605               {
8606                 if (bc + repeat - 1 >= *sizeof_buf - 1)
8607                   {
8608                     /* Make some more room in the buffer.  */
8609                     *sizeof_buf += repeat;
8610                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8611                     buf = *buf_p;
8612                   }
8613
8614                 memset (&buf[bc], buf[bc - 1], repeat);
8615                 bc += repeat;
8616                 continue;
8617               }
8618
8619             buf[bc] = '\0';
8620             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8621             return -1;
8622           }
8623         default:
8624           if (bc >= *sizeof_buf - 1)
8625             {
8626               /* Make some more room in the buffer.  */
8627               *sizeof_buf *= 2;
8628               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8629               buf = *buf_p;
8630             }
8631
8632           buf[bc++] = c;
8633           csum += c;
8634           continue;
8635         }
8636     }
8637 }
8638
8639 /* Read a packet from the remote machine, with error checking, and
8640    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8641    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8642    rather than timing out; this is used (in synchronous mode) to wait
8643    for a target that is is executing user code to stop.  */
8644 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8645    don't have to change all the calls to getpkt to deal with the
8646    return value, because at the moment I don't know what the right
8647    thing to do it for those.  */
8648 void
8649 getpkt (char **buf,
8650         long *sizeof_buf,
8651         int forever)
8652 {
8653   getpkt_sane (buf, sizeof_buf, forever);
8654 }
8655
8656
8657 /* Read a packet from the remote machine, with error checking, and
8658    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8659    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8660    rather than timing out; this is used (in synchronous mode) to wait
8661    for a target that is is executing user code to stop.  If FOREVER ==
8662    0, this function is allowed to time out gracefully and return an
8663    indication of this to the caller.  Otherwise return the number of
8664    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
8665    enough reason to return to the caller.  *IS_NOTIF is an output
8666    boolean that indicates whether *BUF holds a notification or not
8667    (a regular packet).  */
8668
8669 static int
8670 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8671                         int expecting_notif, int *is_notif)
8672 {
8673   struct remote_state *rs = get_remote_state ();
8674   int c;
8675   int tries;
8676   int timeout;
8677   int val = -1;
8678
8679   /* We're reading a new response.  Make sure we don't look at a
8680      previously cached response.  */
8681   rs->cached_wait_status = 0;
8682
8683   strcpy (*buf, "timeout");
8684
8685   if (forever)
8686     timeout = watchdog > 0 ? watchdog : -1;
8687   else if (expecting_notif)
8688     timeout = 0; /* There should already be a char in the buffer.  If
8689                     not, bail out.  */
8690   else
8691     timeout = remote_timeout;
8692
8693 #define MAX_TRIES 3
8694
8695   /* Process any number of notifications, and then return when
8696      we get a packet.  */
8697   for (;;)
8698     {
8699       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8700          times.  */
8701       for (tries = 1; tries <= MAX_TRIES; tries++)
8702         {
8703           /* This can loop forever if the remote side sends us
8704              characters continuously, but if it pauses, we'll get
8705              SERIAL_TIMEOUT from readchar because of timeout.  Then
8706              we'll count that as a retry.
8707
8708              Note that even when forever is set, we will only wait
8709              forever prior to the start of a packet.  After that, we
8710              expect characters to arrive at a brisk pace.  They should
8711              show up within remote_timeout intervals.  */
8712           do
8713             c = readchar (timeout);
8714           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8715
8716           if (c == SERIAL_TIMEOUT)
8717             {
8718               if (expecting_notif)
8719                 return -1; /* Don't complain, it's normal to not get
8720                               anything in this case.  */
8721
8722               if (forever)      /* Watchdog went off?  Kill the target.  */
8723                 {
8724                   remote_unpush_target ();
8725                   throw_error (TARGET_CLOSE_ERROR,
8726                                _("Watchdog timeout has expired.  "
8727                                  "Target detached."));
8728                 }
8729               if (remote_debug)
8730                 fputs_filtered ("Timed out.\n", gdb_stdlog);
8731             }
8732           else
8733             {
8734               /* We've found the start of a packet or notification.
8735                  Now collect the data.  */
8736               val = read_frame (buf, sizeof_buf);
8737               if (val >= 0)
8738                 break;
8739             }
8740
8741           remote_serial_write ("-", 1);
8742         }
8743
8744       if (tries > MAX_TRIES)
8745         {
8746           /* We have tried hard enough, and just can't receive the
8747              packet/notification.  Give up.  */
8748           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8749
8750           /* Skip the ack char if we're in no-ack mode.  */
8751           if (!rs->noack_mode)
8752             remote_serial_write ("+", 1);
8753           return -1;
8754         }
8755
8756       /* If we got an ordinary packet, return that to our caller.  */
8757       if (c == '$')
8758         {
8759           if (remote_debug)
8760             {
8761              struct cleanup *old_chain;
8762              char *str;
8763
8764              str = escape_buffer (*buf, val);
8765              old_chain = make_cleanup (xfree, str);
8766              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8767              do_cleanups (old_chain);
8768             }
8769
8770           /* Skip the ack char if we're in no-ack mode.  */
8771           if (!rs->noack_mode)
8772             remote_serial_write ("+", 1);
8773           if (is_notif != NULL)
8774             *is_notif = 0;
8775           return val;
8776         }
8777
8778        /* If we got a notification, handle it, and go back to looking
8779          for a packet.  */
8780       else
8781         {
8782           gdb_assert (c == '%');
8783
8784           if (remote_debug)
8785             {
8786               struct cleanup *old_chain;
8787               char *str;
8788
8789               str = escape_buffer (*buf, val);
8790               old_chain = make_cleanup (xfree, str);
8791               fprintf_unfiltered (gdb_stdlog,
8792                                   "  Notification received: %s\n",
8793                                   str);
8794               do_cleanups (old_chain);
8795             }
8796           if (is_notif != NULL)
8797             *is_notif = 1;
8798
8799           handle_notification (rs->notif_state, *buf);
8800
8801           /* Notifications require no acknowledgement.  */
8802
8803           if (expecting_notif)
8804             return val;
8805         }
8806     }
8807 }
8808
8809 static int
8810 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8811 {
8812   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8813 }
8814
8815 static int
8816 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8817                       int *is_notif)
8818 {
8819   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8820                                  is_notif);
8821 }
8822
8823 /* Check whether EVENT is a fork event for the process specified
8824    by the pid passed in DATA, and if it is, kill the fork child.  */
8825
8826 static int
8827 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8828                             QUEUE_ITER (stop_reply_p) *iter,
8829                             stop_reply_p event,
8830                             void *data)
8831 {
8832   struct queue_iter_param *param = (struct queue_iter_param *) data;
8833   int parent_pid = *(int *) param->input;
8834
8835   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8836     {
8837       struct remote_state *rs = get_remote_state ();
8838       int child_pid = ptid_get_pid (event->ws.value.related_pid);
8839       int res;
8840
8841       res = remote_vkill (child_pid, rs);
8842       if (res != 0)
8843         error (_("Can't kill fork child process %d"), child_pid);
8844     }
8845
8846   return 1;
8847 }
8848
8849 /* Kill any new fork children of process PID that haven't been
8850    processed by follow_fork.  */
8851
8852 static void
8853 kill_new_fork_children (int pid, struct remote_state *rs)
8854 {
8855   struct thread_info *thread;
8856   struct notif_client *notif = &notif_client_stop;
8857   struct queue_iter_param param;
8858
8859   /* Kill the fork child threads of any threads in process PID
8860      that are stopped at a fork event.  */
8861   ALL_NON_EXITED_THREADS (thread)
8862     {
8863       struct target_waitstatus *ws = &thread->pending_follow;
8864
8865       if (is_pending_fork_parent (ws, pid, thread->ptid))
8866         {
8867           struct remote_state *rs = get_remote_state ();
8868           int child_pid = ptid_get_pid (ws->value.related_pid);
8869           int res;
8870
8871           res = remote_vkill (child_pid, rs);
8872           if (res != 0)
8873             error (_("Can't kill fork child process %d"), child_pid);
8874         }
8875     }
8876
8877   /* Check for any pending fork events (not reported or processed yet)
8878      in process PID and kill those fork child threads as well.  */
8879   remote_notif_get_pending_events (notif);
8880   param.input = &pid;
8881   param.output = NULL;
8882   QUEUE_iterate (stop_reply_p, stop_reply_queue,
8883                  kill_child_of_pending_fork, &param);
8884 }
8885
8886 \f
8887 /* Target hook to kill the current inferior.  */
8888
8889 static void
8890 remote_kill (struct target_ops *ops)
8891 {
8892   int res = -1;
8893   int pid = ptid_get_pid (inferior_ptid);
8894   struct remote_state *rs = get_remote_state ();
8895
8896   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
8897     {
8898       /* If we're stopped while forking and we haven't followed yet,
8899          kill the child task.  We need to do this before killing the
8900          parent task because if this is a vfork then the parent will
8901          be sleeping.  */
8902       kill_new_fork_children (pid, rs);
8903
8904       res = remote_vkill (pid, rs);
8905       if (res == 0)
8906         {
8907           target_mourn_inferior ();
8908           return;
8909         }
8910     }
8911
8912   /* If we are in 'target remote' mode and we are killing the only
8913      inferior, then we will tell gdbserver to exit and unpush the
8914      target.  */
8915   if (res == -1 && !remote_multi_process_p (rs)
8916       && number_of_live_inferiors () == 1)
8917     {
8918       remote_kill_k ();
8919
8920       /* We've killed the remote end, we get to mourn it.  If we are
8921          not in extended mode, mourning the inferior also unpushes
8922          remote_ops from the target stack, which closes the remote
8923          connection.  */
8924       target_mourn_inferior ();
8925
8926       return;
8927     }
8928
8929   error (_("Can't kill process"));
8930 }
8931
8932 /* Send a kill request to the target using the 'vKill' packet.  */
8933
8934 static int
8935 remote_vkill (int pid, struct remote_state *rs)
8936 {
8937   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8938     return -1;
8939
8940   /* Tell the remote target to detach.  */
8941   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8942   putpkt (rs->buf);
8943   getpkt (&rs->buf, &rs->buf_size, 0);
8944
8945   switch (packet_ok (rs->buf,
8946                      &remote_protocol_packets[PACKET_vKill]))
8947     {
8948     case PACKET_OK:
8949       return 0;
8950     case PACKET_ERROR:
8951       return 1;
8952     case PACKET_UNKNOWN:
8953       return -1;
8954     default:
8955       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8956     }
8957 }
8958
8959 /* Send a kill request to the target using the 'k' packet.  */
8960
8961 static void
8962 remote_kill_k (void)
8963 {
8964   /* Catch errors so the user can quit from gdb even when we
8965      aren't on speaking terms with the remote system.  */
8966   TRY
8967     {
8968       putpkt ("k");
8969     }
8970   CATCH (ex, RETURN_MASK_ERROR)
8971     {
8972       if (ex.error == TARGET_CLOSE_ERROR)
8973         {
8974           /* If we got an (EOF) error that caused the target
8975              to go away, then we're done, that's what we wanted.
8976              "k" is susceptible to cause a premature EOF, given
8977              that the remote server isn't actually required to
8978              reply to "k", and it can happen that it doesn't
8979              even get to reply ACK to the "k".  */
8980           return;
8981         }
8982
8983       /* Otherwise, something went wrong.  We didn't actually kill
8984          the target.  Just propagate the exception, and let the
8985          user or higher layers decide what to do.  */
8986       throw_exception (ex);
8987     }
8988   END_CATCH
8989 }
8990
8991 static void
8992 remote_mourn (struct target_ops *target)
8993 {
8994   struct remote_state *rs = get_remote_state ();
8995
8996   /* In 'target remote' mode with one inferior, we close the connection.  */
8997   if (!rs->extended && number_of_live_inferiors () <= 1)
8998     {
8999       unpush_target (target);
9000
9001       /* remote_close takes care of doing most of the clean up.  */
9002       generic_mourn_inferior ();
9003       return;
9004     }
9005
9006   /* In case we got here due to an error, but we're going to stay
9007      connected.  */
9008   rs->waiting_for_stop_reply = 0;
9009
9010   /* If the current general thread belonged to the process we just
9011      detached from or has exited, the remote side current general
9012      thread becomes undefined.  Considering a case like this:
9013
9014      - We just got here due to a detach.
9015      - The process that we're detaching from happens to immediately
9016        report a global breakpoint being hit in non-stop mode, in the
9017        same thread we had selected before.
9018      - GDB attaches to this process again.
9019      - This event happens to be the next event we handle.
9020
9021      GDB would consider that the current general thread didn't need to
9022      be set on the stub side (with Hg), since for all it knew,
9023      GENERAL_THREAD hadn't changed.
9024
9025      Notice that although in all-stop mode, the remote server always
9026      sets the current thread to the thread reporting the stop event,
9027      that doesn't happen in non-stop mode; in non-stop, the stub *must
9028      not* change the current thread when reporting a breakpoint hit,
9029      due to the decoupling of event reporting and event handling.
9030
9031      To keep things simple, we always invalidate our notion of the
9032      current thread.  */
9033   record_currthread (rs, minus_one_ptid);
9034
9035   /* Call common code to mark the inferior as not running.  */
9036   generic_mourn_inferior ();
9037
9038   if (!have_inferiors ())
9039     {
9040       if (!remote_multi_process_p (rs))
9041         {
9042           /* Check whether the target is running now - some remote stubs
9043              automatically restart after kill.  */
9044           putpkt ("?");
9045           getpkt (&rs->buf, &rs->buf_size, 0);
9046
9047           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9048             {
9049               /* Assume that the target has been restarted.  Set
9050                  inferior_ptid so that bits of core GDB realizes
9051                  there's something here, e.g., so that the user can
9052                  say "kill" again.  */
9053               inferior_ptid = magic_null_ptid;
9054             }
9055         }
9056     }
9057 }
9058
9059 static int
9060 extended_remote_supports_disable_randomization (struct target_ops *self)
9061 {
9062   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9063 }
9064
9065 static void
9066 extended_remote_disable_randomization (int val)
9067 {
9068   struct remote_state *rs = get_remote_state ();
9069   char *reply;
9070
9071   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9072              val);
9073   putpkt (rs->buf);
9074   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9075   if (*reply == '\0')
9076     error (_("Target does not support QDisableRandomization."));
9077   if (strcmp (reply, "OK") != 0)
9078     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9079 }
9080
9081 static int
9082 extended_remote_run (char *args)
9083 {
9084   struct remote_state *rs = get_remote_state ();
9085   int len;
9086   const char *remote_exec_file = get_remote_exec_file ();
9087
9088   /* If the user has disabled vRun support, or we have detected that
9089      support is not available, do not try it.  */
9090   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9091     return -1;
9092
9093   strcpy (rs->buf, "vRun;");
9094   len = strlen (rs->buf);
9095
9096   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9097     error (_("Remote file name too long for run packet"));
9098   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9099                       strlen (remote_exec_file));
9100
9101   gdb_assert (args != NULL);
9102   if (*args)
9103     {
9104       struct cleanup *back_to;
9105       int i;
9106       char **argv;
9107
9108       argv = gdb_buildargv (args);
9109       back_to = make_cleanup_freeargv (argv);
9110       for (i = 0; argv[i] != NULL; i++)
9111         {
9112           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9113             error (_("Argument list too long for run packet"));
9114           rs->buf[len++] = ';';
9115           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9116                               strlen (argv[i]));
9117         }
9118       do_cleanups (back_to);
9119     }
9120
9121   rs->buf[len++] = '\0';
9122
9123   putpkt (rs->buf);
9124   getpkt (&rs->buf, &rs->buf_size, 0);
9125
9126   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9127     {
9128     case PACKET_OK:
9129       /* We have a wait response.  All is well.  */
9130       return 0;
9131     case PACKET_UNKNOWN:
9132       return -1;
9133     case PACKET_ERROR:
9134       if (remote_exec_file[0] == '\0')
9135         error (_("Running the default executable on the remote target failed; "
9136                  "try \"set remote exec-file\"?"));
9137       else
9138         error (_("Running \"%s\" on the remote target failed"),
9139                remote_exec_file);
9140     default:
9141       gdb_assert_not_reached (_("bad switch"));
9142     }
9143 }
9144
9145 /* In the extended protocol we want to be able to do things like
9146    "run" and have them basically work as expected.  So we need
9147    a special create_inferior function.  We support changing the
9148    executable file and the command line arguments, but not the
9149    environment.  */
9150
9151 static void
9152 extended_remote_create_inferior (struct target_ops *ops,
9153                                  char *exec_file, char *args,
9154                                  char **env, int from_tty)
9155 {
9156   int run_worked;
9157   char *stop_reply;
9158   struct remote_state *rs = get_remote_state ();
9159   const char *remote_exec_file = get_remote_exec_file ();
9160
9161   /* If running asynchronously, register the target file descriptor
9162      with the event loop.  */
9163   if (target_can_async_p ())
9164     target_async (1);
9165
9166   /* Disable address space randomization if requested (and supported).  */
9167   if (extended_remote_supports_disable_randomization (ops))
9168     extended_remote_disable_randomization (disable_randomization);
9169
9170   /* Now restart the remote server.  */
9171   run_worked = extended_remote_run (args) != -1;
9172   if (!run_worked)
9173     {
9174       /* vRun was not supported.  Fail if we need it to do what the
9175          user requested.  */
9176       if (remote_exec_file[0])
9177         error (_("Remote target does not support \"set remote exec-file\""));
9178       if (args[0])
9179         error (_("Remote target does not support \"set args\" or run <ARGS>"));
9180
9181       /* Fall back to "R".  */
9182       extended_remote_restart ();
9183     }
9184
9185   if (!have_inferiors ())
9186     {
9187       /* Clean up from the last time we ran, before we mark the target
9188          running again.  This will mark breakpoints uninserted, and
9189          get_offsets may insert breakpoints.  */
9190       init_thread_list ();
9191       init_wait_for_inferior ();
9192     }
9193
9194   /* vRun's success return is a stop reply.  */
9195   stop_reply = run_worked ? rs->buf : NULL;
9196   add_current_inferior_and_thread (stop_reply);
9197
9198   /* Get updated offsets, if the stub uses qOffsets.  */
9199   get_offsets ();
9200 }
9201 \f
9202
9203 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
9204    the list of conditions (in agent expression bytecode format), if any, the
9205    target needs to evaluate.  The output is placed into the packet buffer
9206    started from BUF and ended at BUF_END.  */
9207
9208 static int
9209 remote_add_target_side_condition (struct gdbarch *gdbarch,
9210                                   struct bp_target_info *bp_tgt, char *buf,
9211                                   char *buf_end)
9212 {
9213   struct agent_expr *aexpr = NULL;
9214   int i, ix;
9215
9216   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9217     return 0;
9218
9219   buf += strlen (buf);
9220   xsnprintf (buf, buf_end - buf, "%s", ";");
9221   buf++;
9222
9223   /* Send conditions to the target and free the vector.  */
9224   for (ix = 0;
9225        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9226        ix++)
9227     {
9228       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9229       buf += strlen (buf);
9230       for (i = 0; i < aexpr->len; ++i)
9231         buf = pack_hex_byte (buf, aexpr->buf[i]);
9232       *buf = '\0';
9233     }
9234   return 0;
9235 }
9236
9237 static void
9238 remote_add_target_side_commands (struct gdbarch *gdbarch,
9239                                  struct bp_target_info *bp_tgt, char *buf)
9240 {
9241   struct agent_expr *aexpr = NULL;
9242   int i, ix;
9243
9244   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9245     return;
9246
9247   buf += strlen (buf);
9248
9249   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9250   buf += strlen (buf);
9251
9252   /* Concatenate all the agent expressions that are commands into the
9253      cmds parameter.  */
9254   for (ix = 0;
9255        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9256        ix++)
9257     {
9258       sprintf (buf, "X%x,", aexpr->len);
9259       buf += strlen (buf);
9260       for (i = 0; i < aexpr->len; ++i)
9261         buf = pack_hex_byte (buf, aexpr->buf[i]);
9262       *buf = '\0';
9263     }
9264 }
9265
9266 /* Insert a breakpoint.  On targets that have software breakpoint
9267    support, we ask the remote target to do the work; on targets
9268    which don't, we insert a traditional memory breakpoint.  */
9269
9270 static int
9271 remote_insert_breakpoint (struct target_ops *ops,
9272                           struct gdbarch *gdbarch,
9273                           struct bp_target_info *bp_tgt)
9274 {
9275   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9276      If it succeeds, then set the support to PACKET_ENABLE.  If it
9277      fails, and the user has explicitly requested the Z support then
9278      report an error, otherwise, mark it disabled and go on.  */
9279
9280   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9281     {
9282       CORE_ADDR addr = bp_tgt->reqstd_address;
9283       struct remote_state *rs;
9284       char *p, *endbuf;
9285       int bpsize;
9286
9287       /* Make sure the remote is pointing at the right process, if
9288          necessary.  */
9289       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9290         set_general_process ();
9291
9292       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9293
9294       rs = get_remote_state ();
9295       p = rs->buf;
9296       endbuf = rs->buf + get_remote_packet_size ();
9297
9298       *(p++) = 'Z';
9299       *(p++) = '0';
9300       *(p++) = ',';
9301       addr = (ULONGEST) remote_address_masked (addr);
9302       p += hexnumstr (p, addr);
9303       xsnprintf (p, endbuf - p, ",%d", bpsize);
9304
9305       if (remote_supports_cond_breakpoints (ops))
9306         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9307
9308       if (remote_can_run_breakpoint_commands (ops))
9309         remote_add_target_side_commands (gdbarch, bp_tgt, p);
9310
9311       putpkt (rs->buf);
9312       getpkt (&rs->buf, &rs->buf_size, 0);
9313
9314       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9315         {
9316         case PACKET_ERROR:
9317           return -1;
9318         case PACKET_OK:
9319           bp_tgt->placed_address = addr;
9320           bp_tgt->placed_size = bpsize;
9321           return 0;
9322         case PACKET_UNKNOWN:
9323           break;
9324         }
9325     }
9326
9327   /* If this breakpoint has target-side commands but this stub doesn't
9328      support Z0 packets, throw error.  */
9329   if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9330     throw_error (NOT_SUPPORTED_ERROR, _("\
9331 Target doesn't support breakpoints that have target side commands."));
9332
9333   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9334 }
9335
9336 static int
9337 remote_remove_breakpoint (struct target_ops *ops,
9338                           struct gdbarch *gdbarch,
9339                           struct bp_target_info *bp_tgt)
9340 {
9341   CORE_ADDR addr = bp_tgt->placed_address;
9342   struct remote_state *rs = get_remote_state ();
9343
9344   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9345     {
9346       char *p = rs->buf;
9347       char *endbuf = rs->buf + get_remote_packet_size ();
9348
9349       /* Make sure the remote is pointing at the right process, if
9350          necessary.  */
9351       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9352         set_general_process ();
9353
9354       *(p++) = 'z';
9355       *(p++) = '0';
9356       *(p++) = ',';
9357
9358       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9359       p += hexnumstr (p, addr);
9360       xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9361
9362       putpkt (rs->buf);
9363       getpkt (&rs->buf, &rs->buf_size, 0);
9364
9365       return (rs->buf[0] == 'E');
9366     }
9367
9368   return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9369 }
9370
9371 static enum Z_packet_type
9372 watchpoint_to_Z_packet (int type)
9373 {
9374   switch (type)
9375     {
9376     case hw_write:
9377       return Z_PACKET_WRITE_WP;
9378       break;
9379     case hw_read:
9380       return Z_PACKET_READ_WP;
9381       break;
9382     case hw_access:
9383       return Z_PACKET_ACCESS_WP;
9384       break;
9385     default:
9386       internal_error (__FILE__, __LINE__,
9387                       _("hw_bp_to_z: bad watchpoint type %d"), type);
9388     }
9389 }
9390
9391 static int
9392 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9393                           enum target_hw_bp_type type, struct expression *cond)
9394 {
9395   struct remote_state *rs = get_remote_state ();
9396   char *endbuf = rs->buf + get_remote_packet_size ();
9397   char *p;
9398   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9399
9400   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9401     return 1;
9402
9403   /* Make sure the remote is pointing at the right process, if
9404      necessary.  */
9405   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9406     set_general_process ();
9407
9408   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9409   p = strchr (rs->buf, '\0');
9410   addr = remote_address_masked (addr);
9411   p += hexnumstr (p, (ULONGEST) addr);
9412   xsnprintf (p, endbuf - p, ",%x", len);
9413
9414   putpkt (rs->buf);
9415   getpkt (&rs->buf, &rs->buf_size, 0);
9416
9417   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9418     {
9419     case PACKET_ERROR:
9420       return -1;
9421     case PACKET_UNKNOWN:
9422       return 1;
9423     case PACKET_OK:
9424       return 0;
9425     }
9426   internal_error (__FILE__, __LINE__,
9427                   _("remote_insert_watchpoint: reached end of function"));
9428 }
9429
9430 static int
9431 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9432                                      CORE_ADDR start, int length)
9433 {
9434   CORE_ADDR diff = remote_address_masked (addr - start);
9435
9436   return diff < length;
9437 }
9438
9439
9440 static int
9441 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9442                           enum target_hw_bp_type type, struct expression *cond)
9443 {
9444   struct remote_state *rs = get_remote_state ();
9445   char *endbuf = rs->buf + get_remote_packet_size ();
9446   char *p;
9447   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9448
9449   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9450     return -1;
9451
9452   /* Make sure the remote is pointing at the right process, if
9453      necessary.  */
9454   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9455     set_general_process ();
9456
9457   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9458   p = strchr (rs->buf, '\0');
9459   addr = remote_address_masked (addr);
9460   p += hexnumstr (p, (ULONGEST) addr);
9461   xsnprintf (p, endbuf - p, ",%x", len);
9462   putpkt (rs->buf);
9463   getpkt (&rs->buf, &rs->buf_size, 0);
9464
9465   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9466     {
9467     case PACKET_ERROR:
9468     case PACKET_UNKNOWN:
9469       return -1;
9470     case PACKET_OK:
9471       return 0;
9472     }
9473   internal_error (__FILE__, __LINE__,
9474                   _("remote_remove_watchpoint: reached end of function"));
9475 }
9476
9477
9478 int remote_hw_watchpoint_limit = -1;
9479 int remote_hw_watchpoint_length_limit = -1;
9480 int remote_hw_breakpoint_limit = -1;
9481
9482 static int
9483 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9484                                     CORE_ADDR addr, int len)
9485 {
9486   if (remote_hw_watchpoint_length_limit == 0)
9487     return 0;
9488   else if (remote_hw_watchpoint_length_limit < 0)
9489     return 1;
9490   else if (len <= remote_hw_watchpoint_length_limit)
9491     return 1;
9492   else
9493     return 0;
9494 }
9495
9496 static int
9497 remote_check_watch_resources (struct target_ops *self,
9498                               enum bptype type, int cnt, int ot)
9499 {
9500   if (type == bp_hardware_breakpoint)
9501     {
9502       if (remote_hw_breakpoint_limit == 0)
9503         return 0;
9504       else if (remote_hw_breakpoint_limit < 0)
9505         return 1;
9506       else if (cnt <= remote_hw_breakpoint_limit)
9507         return 1;
9508     }
9509   else
9510     {
9511       if (remote_hw_watchpoint_limit == 0)
9512         return 0;
9513       else if (remote_hw_watchpoint_limit < 0)
9514         return 1;
9515       else if (ot)
9516         return -1;
9517       else if (cnt <= remote_hw_watchpoint_limit)
9518         return 1;
9519     }
9520   return -1;
9521 }
9522
9523 /* The to_stopped_by_sw_breakpoint method of target remote.  */
9524
9525 static int
9526 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9527 {
9528   struct thread_info *thread = inferior_thread ();
9529
9530   return (thread->priv != NULL
9531           && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9532 }
9533
9534 /* The to_supports_stopped_by_sw_breakpoint method of target
9535    remote.  */
9536
9537 static int
9538 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9539 {
9540   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9541 }
9542
9543 /* The to_stopped_by_hw_breakpoint method of target remote.  */
9544
9545 static int
9546 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9547 {
9548   struct thread_info *thread = inferior_thread ();
9549
9550   return (thread->priv != NULL
9551           && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9552 }
9553
9554 /* The to_supports_stopped_by_hw_breakpoint method of target
9555    remote.  */
9556
9557 static int
9558 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9559 {
9560   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9561 }
9562
9563 static int
9564 remote_stopped_by_watchpoint (struct target_ops *ops)
9565 {
9566   struct thread_info *thread = inferior_thread ();
9567
9568   return (thread->priv != NULL
9569           && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9570 }
9571
9572 static int
9573 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9574 {
9575   struct thread_info *thread = inferior_thread ();
9576
9577   if (thread->priv != NULL
9578       && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9579     {
9580       *addr_p = thread->priv->watch_data_address;
9581       return 1;
9582     }
9583
9584   return 0;
9585 }
9586
9587
9588 static int
9589 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9590                              struct bp_target_info *bp_tgt)
9591 {
9592   CORE_ADDR addr = bp_tgt->reqstd_address;
9593   struct remote_state *rs;
9594   char *p, *endbuf;
9595   char *message;
9596   int bpsize;
9597
9598   /* The length field should be set to the size of a breakpoint
9599      instruction, even though we aren't inserting one ourselves.  */
9600
9601   gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9602
9603   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9604     return -1;
9605
9606   /* Make sure the remote is pointing at the right process, if
9607      necessary.  */
9608   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9609     set_general_process ();
9610
9611   rs = get_remote_state ();
9612   p = rs->buf;
9613   endbuf = rs->buf + get_remote_packet_size ();
9614
9615   *(p++) = 'Z';
9616   *(p++) = '1';
9617   *(p++) = ',';
9618
9619   addr = remote_address_masked (addr);
9620   p += hexnumstr (p, (ULONGEST) addr);
9621   xsnprintf (p, endbuf - p, ",%x", bpsize);
9622
9623   if (remote_supports_cond_breakpoints (self))
9624     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9625
9626   if (remote_can_run_breakpoint_commands (self))
9627     remote_add_target_side_commands (gdbarch, bp_tgt, p);
9628
9629   putpkt (rs->buf);
9630   getpkt (&rs->buf, &rs->buf_size, 0);
9631
9632   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9633     {
9634     case PACKET_ERROR:
9635       if (rs->buf[1] == '.')
9636         {
9637           message = strchr (rs->buf + 2, '.');
9638           if (message)
9639             error (_("Remote failure reply: %s"), message + 1);
9640         }
9641       return -1;
9642     case PACKET_UNKNOWN:
9643       return -1;
9644     case PACKET_OK:
9645       bp_tgt->placed_address = addr;
9646       bp_tgt->placed_size = bpsize;
9647       return 0;
9648     }
9649   internal_error (__FILE__, __LINE__,
9650                   _("remote_insert_hw_breakpoint: reached end of function"));
9651 }
9652
9653
9654 static int
9655 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9656                              struct bp_target_info *bp_tgt)
9657 {
9658   CORE_ADDR addr;
9659   struct remote_state *rs = get_remote_state ();
9660   char *p = rs->buf;
9661   char *endbuf = rs->buf + get_remote_packet_size ();
9662
9663   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9664     return -1;
9665
9666   /* Make sure the remote is pointing at the right process, if
9667      necessary.  */
9668   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9669     set_general_process ();
9670
9671   *(p++) = 'z';
9672   *(p++) = '1';
9673   *(p++) = ',';
9674
9675   addr = remote_address_masked (bp_tgt->placed_address);
9676   p += hexnumstr (p, (ULONGEST) addr);
9677   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);
9678
9679   putpkt (rs->buf);
9680   getpkt (&rs->buf, &rs->buf_size, 0);
9681
9682   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9683     {
9684     case PACKET_ERROR:
9685     case PACKET_UNKNOWN:
9686       return -1;
9687     case PACKET_OK:
9688       return 0;
9689     }
9690   internal_error (__FILE__, __LINE__,
9691                   _("remote_remove_hw_breakpoint: reached end of function"));
9692 }
9693
9694 /* Verify memory using the "qCRC:" request.  */
9695
9696 static int
9697 remote_verify_memory (struct target_ops *ops,
9698                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9699 {
9700   struct remote_state *rs = get_remote_state ();
9701   unsigned long host_crc, target_crc;
9702   char *tmp;
9703
9704   /* It doesn't make sense to use qCRC if the remote target is
9705      connected but not running.  */
9706   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9707     {
9708       enum packet_result result;
9709
9710       /* Make sure the remote is pointing at the right process.  */
9711       set_general_process ();
9712
9713       /* FIXME: assumes lma can fit into long.  */
9714       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9715                  (long) lma, (long) size);
9716       putpkt (rs->buf);
9717
9718       /* Be clever; compute the host_crc before waiting for target
9719          reply.  */
9720       host_crc = xcrc32 (data, size, 0xffffffff);
9721
9722       getpkt (&rs->buf, &rs->buf_size, 0);
9723
9724       result = packet_ok (rs->buf,
9725                           &remote_protocol_packets[PACKET_qCRC]);
9726       if (result == PACKET_ERROR)
9727         return -1;
9728       else if (result == PACKET_OK)
9729         {
9730           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9731             target_crc = target_crc * 16 + fromhex (*tmp);
9732
9733           return (host_crc == target_crc);
9734         }
9735     }
9736
9737   return simple_verify_memory (ops, data, lma, size);
9738 }
9739
9740 /* compare-sections command
9741
9742    With no arguments, compares each loadable section in the exec bfd
9743    with the same memory range on the target, and reports mismatches.
9744    Useful for verifying the image on the target against the exec file.  */
9745
9746 static void
9747 compare_sections_command (char *args, int from_tty)
9748 {
9749   asection *s;
9750   struct cleanup *old_chain;
9751   gdb_byte *sectdata;
9752   const char *sectname;
9753   bfd_size_type size;
9754   bfd_vma lma;
9755   int matched = 0;
9756   int mismatched = 0;
9757   int res;
9758   int read_only = 0;
9759
9760   if (!exec_bfd)
9761     error (_("command cannot be used without an exec file"));
9762
9763   /* Make sure the remote is pointing at the right process.  */
9764   set_general_process ();
9765
9766   if (args != NULL && strcmp (args, "-r") == 0)
9767     {
9768       read_only = 1;
9769       args = NULL;
9770     }
9771
9772   for (s = exec_bfd->sections; s; s = s->next)
9773     {
9774       if (!(s->flags & SEC_LOAD))
9775         continue;               /* Skip non-loadable section.  */
9776
9777       if (read_only && (s->flags & SEC_READONLY) == 0)
9778         continue;               /* Skip writeable sections */
9779
9780       size = bfd_get_section_size (s);
9781       if (size == 0)
9782         continue;               /* Skip zero-length section.  */
9783
9784       sectname = bfd_get_section_name (exec_bfd, s);
9785       if (args && strcmp (args, sectname) != 0)
9786         continue;               /* Not the section selected by user.  */
9787
9788       matched = 1;              /* Do this section.  */
9789       lma = s->lma;
9790
9791       sectdata = (gdb_byte *) xmalloc (size);
9792       old_chain = make_cleanup (xfree, sectdata);
9793       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9794
9795       res = target_verify_memory (sectdata, lma, size);
9796
9797       if (res == -1)
9798         error (_("target memory fault, section %s, range %s -- %s"), sectname,
9799                paddress (target_gdbarch (), lma),
9800                paddress (target_gdbarch (), lma + size));
9801
9802       printf_filtered ("Section %s, range %s -- %s: ", sectname,
9803                        paddress (target_gdbarch (), lma),
9804                        paddress (target_gdbarch (), lma + size));
9805       if (res)
9806         printf_filtered ("matched.\n");
9807       else
9808         {
9809           printf_filtered ("MIS-MATCHED!\n");
9810           mismatched++;
9811         }
9812
9813       do_cleanups (old_chain);
9814     }
9815   if (mismatched > 0)
9816     warning (_("One or more sections of the target image does not match\n\
9817 the loaded file\n"));
9818   if (args && !matched)
9819     printf_filtered (_("No loaded section named '%s'.\n"), args);
9820 }
9821
9822 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9823    into remote target.  The number of bytes written to the remote
9824    target is returned, or -1 for error.  */
9825
9826 static enum target_xfer_status
9827 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9828                     const char *annex, const gdb_byte *writebuf, 
9829                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9830                     struct packet_config *packet)
9831 {
9832   int i, buf_len;
9833   ULONGEST n;
9834   struct remote_state *rs = get_remote_state ();
9835   int max_size = get_memory_write_packet_size (); 
9836
9837   if (packet->support == PACKET_DISABLE)
9838     return TARGET_XFER_E_IO;
9839
9840   /* Insert header.  */
9841   i = snprintf (rs->buf, max_size, 
9842                 "qXfer:%s:write:%s:%s:",
9843                 object_name, annex ? annex : "",
9844                 phex_nz (offset, sizeof offset));
9845   max_size -= (i + 1);
9846
9847   /* Escape as much data as fits into rs->buf.  */
9848   buf_len = remote_escape_output 
9849     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9850
9851   if (putpkt_binary (rs->buf, i + buf_len) < 0
9852       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9853       || packet_ok (rs->buf, packet) != PACKET_OK)
9854     return TARGET_XFER_E_IO;
9855
9856   unpack_varlen_hex (rs->buf, &n);
9857
9858   *xfered_len = n;
9859   return TARGET_XFER_OK;
9860 }
9861
9862 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9863    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9864    number of bytes read is returned, or 0 for EOF, or -1 for error.
9865    The number of bytes read may be less than LEN without indicating an
9866    EOF.  PACKET is checked and updated to indicate whether the remote
9867    target supports this object.  */
9868
9869 static enum target_xfer_status
9870 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9871                    const char *annex,
9872                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9873                    ULONGEST *xfered_len,
9874                    struct packet_config *packet)
9875 {
9876   struct remote_state *rs = get_remote_state ();
9877   LONGEST i, n, packet_len;
9878
9879   if (packet->support == PACKET_DISABLE)
9880     return TARGET_XFER_E_IO;
9881
9882   /* Check whether we've cached an end-of-object packet that matches
9883      this request.  */
9884   if (rs->finished_object)
9885     {
9886       if (strcmp (object_name, rs->finished_object) == 0
9887           && strcmp (annex ? annex : "", rs->finished_annex) == 0
9888           && offset == rs->finished_offset)
9889         return TARGET_XFER_EOF;
9890
9891
9892       /* Otherwise, we're now reading something different.  Discard
9893          the cache.  */
9894       xfree (rs->finished_object);
9895       xfree (rs->finished_annex);
9896       rs->finished_object = NULL;
9897       rs->finished_annex = NULL;
9898     }
9899
9900   /* Request only enough to fit in a single packet.  The actual data
9901      may not, since we don't know how much of it will need to be escaped;
9902      the target is free to respond with slightly less data.  We subtract
9903      five to account for the response type and the protocol frame.  */
9904   n = min (get_remote_packet_size () - 5, len);
9905   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9906             object_name, annex ? annex : "",
9907             phex_nz (offset, sizeof offset),
9908             phex_nz (n, sizeof n));
9909   i = putpkt (rs->buf);
9910   if (i < 0)
9911     return TARGET_XFER_E_IO;
9912
9913   rs->buf[0] = '\0';
9914   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9915   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9916     return TARGET_XFER_E_IO;
9917
9918   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9919     error (_("Unknown remote qXfer reply: %s"), rs->buf);
9920
9921   /* 'm' means there is (or at least might be) more data after this
9922      batch.  That does not make sense unless there's at least one byte
9923      of data in this reply.  */
9924   if (rs->buf[0] == 'm' && packet_len == 1)
9925     error (_("Remote qXfer reply contained no data."));
9926
9927   /* Got some data.  */
9928   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9929                              packet_len - 1, readbuf, n);
9930
9931   /* 'l' is an EOF marker, possibly including a final block of data,
9932      or possibly empty.  If we have the final block of a non-empty
9933      object, record this fact to bypass a subsequent partial read.  */
9934   if (rs->buf[0] == 'l' && offset + i > 0)
9935     {
9936       rs->finished_object = xstrdup (object_name);
9937       rs->finished_annex = xstrdup (annex ? annex : "");
9938       rs->finished_offset = offset + i;
9939     }
9940
9941   if (i == 0)
9942     return TARGET_XFER_EOF;
9943   else
9944     {
9945       *xfered_len = i;
9946       return TARGET_XFER_OK;
9947     }
9948 }
9949
9950 static enum target_xfer_status
9951 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9952                      const char *annex, gdb_byte *readbuf,
9953                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9954                      ULONGEST *xfered_len)
9955 {
9956   struct remote_state *rs;
9957   int i;
9958   char *p2;
9959   char query_type;
9960   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9961
9962   set_remote_traceframe ();
9963   set_general_thread (inferior_ptid);
9964
9965   rs = get_remote_state ();
9966
9967   /* Handle memory using the standard memory routines.  */
9968   if (object == TARGET_OBJECT_MEMORY)
9969     {
9970       /* If the remote target is connected but not running, we should
9971          pass this request down to a lower stratum (e.g. the executable
9972          file).  */
9973       if (!target_has_execution)
9974         return TARGET_XFER_EOF;
9975
9976       if (writebuf != NULL)
9977         return remote_write_bytes (offset, writebuf, len, unit_size,
9978                                    xfered_len);
9979       else
9980         return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9981                                   xfered_len);
9982     }
9983
9984   /* Handle SPU memory using qxfer packets.  */
9985   if (object == TARGET_OBJECT_SPU)
9986     {
9987       if (readbuf)
9988         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9989                                   xfered_len, &remote_protocol_packets
9990                                   [PACKET_qXfer_spu_read]);
9991       else
9992         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9993                                    xfered_len, &remote_protocol_packets
9994                                    [PACKET_qXfer_spu_write]);
9995     }
9996
9997   /* Handle extra signal info using qxfer packets.  */
9998   if (object == TARGET_OBJECT_SIGNAL_INFO)
9999     {
10000       if (readbuf)
10001         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10002                                   xfered_len, &remote_protocol_packets
10003                                   [PACKET_qXfer_siginfo_read]);
10004       else
10005         return remote_write_qxfer (ops, "siginfo", annex,
10006                                    writebuf, offset, len, xfered_len,
10007                                    &remote_protocol_packets
10008                                    [PACKET_qXfer_siginfo_write]);
10009     }
10010
10011   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10012     {
10013       if (readbuf)
10014         return remote_read_qxfer (ops, "statictrace", annex,
10015                                   readbuf, offset, len, xfered_len,
10016                                   &remote_protocol_packets
10017                                   [PACKET_qXfer_statictrace_read]);
10018       else
10019         return TARGET_XFER_E_IO;
10020     }
10021
10022   /* Only handle flash writes.  */
10023   if (writebuf != NULL)
10024     {
10025       switch (object)
10026         {
10027         case TARGET_OBJECT_FLASH:
10028           return remote_flash_write (ops, offset, len, xfered_len,
10029                                      writebuf);
10030
10031         default:
10032           return TARGET_XFER_E_IO;
10033         }
10034     }
10035
10036   /* Map pre-existing objects onto letters.  DO NOT do this for new
10037      objects!!!  Instead specify new query packets.  */
10038   switch (object)
10039     {
10040     case TARGET_OBJECT_AVR:
10041       query_type = 'R';
10042       break;
10043
10044     case TARGET_OBJECT_AUXV:
10045       gdb_assert (annex == NULL);
10046       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10047                                 xfered_len,
10048                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10049
10050     case TARGET_OBJECT_AVAILABLE_FEATURES:
10051       return remote_read_qxfer
10052         (ops, "features", annex, readbuf, offset, len, xfered_len,
10053          &remote_protocol_packets[PACKET_qXfer_features]);
10054
10055     case TARGET_OBJECT_LIBRARIES:
10056       return remote_read_qxfer
10057         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10058          &remote_protocol_packets[PACKET_qXfer_libraries]);
10059
10060     case TARGET_OBJECT_LIBRARIES_SVR4:
10061       return remote_read_qxfer
10062         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10063          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10064
10065     case TARGET_OBJECT_MEMORY_MAP:
10066       gdb_assert (annex == NULL);
10067       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10068                                  xfered_len,
10069                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10070
10071     case TARGET_OBJECT_OSDATA:
10072       /* Should only get here if we're connected.  */
10073       gdb_assert (rs->remote_desc);
10074       return remote_read_qxfer
10075         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10076         &remote_protocol_packets[PACKET_qXfer_osdata]);
10077
10078     case TARGET_OBJECT_THREADS:
10079       gdb_assert (annex == NULL);
10080       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10081                                 xfered_len,
10082                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10083
10084     case TARGET_OBJECT_TRACEFRAME_INFO:
10085       gdb_assert (annex == NULL);
10086       return remote_read_qxfer
10087         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10088          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10089
10090     case TARGET_OBJECT_FDPIC:
10091       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10092                                 xfered_len,
10093                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10094
10095     case TARGET_OBJECT_OPENVMS_UIB:
10096       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10097                                 xfered_len,
10098                                 &remote_protocol_packets[PACKET_qXfer_uib]);
10099
10100     case TARGET_OBJECT_BTRACE:
10101       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10102                                 xfered_len,
10103         &remote_protocol_packets[PACKET_qXfer_btrace]);
10104
10105     case TARGET_OBJECT_BTRACE_CONF:
10106       return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10107                                 len, xfered_len,
10108         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10109
10110     case TARGET_OBJECT_EXEC_FILE:
10111       return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10112                                 len, xfered_len,
10113         &remote_protocol_packets[PACKET_qXfer_exec_file]);
10114
10115     default:
10116       return TARGET_XFER_E_IO;
10117     }
10118
10119   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
10120      large enough let the caller deal with it.  */
10121   if (len < get_remote_packet_size ())
10122     return TARGET_XFER_E_IO;
10123   len = get_remote_packet_size ();
10124
10125   /* Except for querying the minimum buffer size, target must be open.  */
10126   if (!rs->remote_desc)
10127     error (_("remote query is only available after target open"));
10128
10129   gdb_assert (annex != NULL);
10130   gdb_assert (readbuf != NULL);
10131
10132   p2 = rs->buf;
10133   *p2++ = 'q';
10134   *p2++ = query_type;
10135
10136   /* We used one buffer char for the remote protocol q command and
10137      another for the query type.  As the remote protocol encapsulation
10138      uses 4 chars plus one extra in case we are debugging
10139      (remote_debug), we have PBUFZIZ - 7 left to pack the query
10140      string.  */
10141   i = 0;
10142   while (annex[i] && (i < (get_remote_packet_size () - 8)))
10143     {
10144       /* Bad caller may have sent forbidden characters.  */
10145       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10146       *p2++ = annex[i];
10147       i++;
10148     }
10149   *p2 = '\0';
10150   gdb_assert (annex[i] == '\0');
10151
10152   i = putpkt (rs->buf);
10153   if (i < 0)
10154     return TARGET_XFER_E_IO;
10155
10156   getpkt (&rs->buf, &rs->buf_size, 0);
10157   strcpy ((char *) readbuf, rs->buf);
10158
10159   *xfered_len = strlen ((char *) readbuf);
10160   return TARGET_XFER_OK;
10161 }
10162
10163 static int
10164 remote_search_memory (struct target_ops* ops,
10165                       CORE_ADDR start_addr, ULONGEST search_space_len,
10166                       const gdb_byte *pattern, ULONGEST pattern_len,
10167                       CORE_ADDR *found_addrp)
10168 {
10169   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10170   struct remote_state *rs = get_remote_state ();
10171   int max_size = get_memory_write_packet_size ();
10172   struct packet_config *packet =
10173     &remote_protocol_packets[PACKET_qSearch_memory];
10174   /* Number of packet bytes used to encode the pattern;
10175      this could be more than PATTERN_LEN due to escape characters.  */
10176   int escaped_pattern_len;
10177   /* Amount of pattern that was encodable in the packet.  */
10178   int used_pattern_len;
10179   int i;
10180   int found;
10181   ULONGEST found_addr;
10182
10183   /* Don't go to the target if we don't have to.
10184      This is done before checking packet->support to avoid the possibility that
10185      a success for this edge case means the facility works in general.  */
10186   if (pattern_len > search_space_len)
10187     return 0;
10188   if (pattern_len == 0)
10189     {
10190       *found_addrp = start_addr;
10191       return 1;
10192     }
10193
10194   /* If we already know the packet isn't supported, fall back to the simple
10195      way of searching memory.  */
10196
10197   if (packet_config_support (packet) == PACKET_DISABLE)
10198     {
10199       /* Target doesn't provided special support, fall back and use the
10200          standard support (copy memory and do the search here).  */
10201       return simple_search_memory (ops, start_addr, search_space_len,
10202                                    pattern, pattern_len, found_addrp);
10203     }
10204
10205   /* Make sure the remote is pointing at the right process.  */
10206   set_general_process ();
10207
10208   /* Insert header.  */
10209   i = snprintf (rs->buf, max_size, 
10210                 "qSearch:memory:%s;%s;",
10211                 phex_nz (start_addr, addr_size),
10212                 phex_nz (search_space_len, sizeof (search_space_len)));
10213   max_size -= (i + 1);
10214
10215   /* Escape as much data as fits into rs->buf.  */
10216   escaped_pattern_len =
10217     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10218                           &used_pattern_len, max_size);
10219
10220   /* Bail if the pattern is too large.  */
10221   if (used_pattern_len != pattern_len)
10222     error (_("Pattern is too large to transmit to remote target."));
10223
10224   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10225       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10226       || packet_ok (rs->buf, packet) != PACKET_OK)
10227     {
10228       /* The request may not have worked because the command is not
10229          supported.  If so, fall back to the simple way.  */
10230       if (packet->support == PACKET_DISABLE)
10231         {
10232           return simple_search_memory (ops, start_addr, search_space_len,
10233                                        pattern, pattern_len, found_addrp);
10234         }
10235       return -1;
10236     }
10237
10238   if (rs->buf[0] == '0')
10239     found = 0;
10240   else if (rs->buf[0] == '1')
10241     {
10242       found = 1;
10243       if (rs->buf[1] != ',')
10244         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10245       unpack_varlen_hex (rs->buf + 2, &found_addr);
10246       *found_addrp = found_addr;
10247     }
10248   else
10249     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10250
10251   return found;
10252 }
10253
10254 static void
10255 remote_rcmd (struct target_ops *self, const char *command,
10256              struct ui_file *outbuf)
10257 {
10258   struct remote_state *rs = get_remote_state ();
10259   char *p = rs->buf;
10260
10261   if (!rs->remote_desc)
10262     error (_("remote rcmd is only available after target open"));
10263
10264   /* Send a NULL command across as an empty command.  */
10265   if (command == NULL)
10266     command = "";
10267
10268   /* The query prefix.  */
10269   strcpy (rs->buf, "qRcmd,");
10270   p = strchr (rs->buf, '\0');
10271
10272   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10273       > get_remote_packet_size ())
10274     error (_("\"monitor\" command ``%s'' is too long."), command);
10275
10276   /* Encode the actual command.  */
10277   bin2hex ((const gdb_byte *) command, p, strlen (command));
10278
10279   if (putpkt (rs->buf) < 0)
10280     error (_("Communication problem with target."));
10281
10282   /* get/display the response */
10283   while (1)
10284     {
10285       char *buf;
10286
10287       /* XXX - see also remote_get_noisy_reply().  */
10288       QUIT;                     /* Allow user to bail out with ^C.  */
10289       rs->buf[0] = '\0';
10290       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10291         { 
10292           /* Timeout.  Continue to (try to) read responses.
10293              This is better than stopping with an error, assuming the stub
10294              is still executing the (long) monitor command.
10295              If needed, the user can interrupt gdb using C-c, obtaining
10296              an effect similar to stop on timeout.  */
10297           continue;
10298         }
10299       buf = rs->buf;
10300       if (buf[0] == '\0')
10301         error (_("Target does not support this command."));
10302       if (buf[0] == 'O' && buf[1] != 'K')
10303         {
10304           remote_console_output (buf + 1); /* 'O' message from stub.  */
10305           continue;
10306         }
10307       if (strcmp (buf, "OK") == 0)
10308         break;
10309       if (strlen (buf) == 3 && buf[0] == 'E'
10310           && isdigit (buf[1]) && isdigit (buf[2]))
10311         {
10312           error (_("Protocol error with Rcmd"));
10313         }
10314       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10315         {
10316           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10317
10318           fputc_unfiltered (c, outbuf);
10319         }
10320       break;
10321     }
10322 }
10323
10324 static VEC(mem_region_s) *
10325 remote_memory_map (struct target_ops *ops)
10326 {
10327   VEC(mem_region_s) *result = NULL;
10328   char *text = target_read_stralloc (&current_target,
10329                                      TARGET_OBJECT_MEMORY_MAP, NULL);
10330
10331   if (text)
10332     {
10333       struct cleanup *back_to = make_cleanup (xfree, text);
10334
10335       result = parse_memory_map (text);
10336       do_cleanups (back_to);
10337     }
10338
10339   return result;
10340 }
10341
10342 static void
10343 packet_command (char *args, int from_tty)
10344 {
10345   struct remote_state *rs = get_remote_state ();
10346
10347   if (!rs->remote_desc)
10348     error (_("command can only be used with remote target"));
10349
10350   if (!args)
10351     error (_("remote-packet command requires packet text as argument"));
10352
10353   puts_filtered ("sending: ");
10354   print_packet (args);
10355   puts_filtered ("\n");
10356   putpkt (args);
10357
10358   getpkt (&rs->buf, &rs->buf_size, 0);
10359   puts_filtered ("received: ");
10360   print_packet (rs->buf);
10361   puts_filtered ("\n");
10362 }
10363
10364 #if 0
10365 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10366
10367 static void display_thread_info (struct gdb_ext_thread_info *info);
10368
10369 static void threadset_test_cmd (char *cmd, int tty);
10370
10371 static void threadalive_test (char *cmd, int tty);
10372
10373 static void threadlist_test_cmd (char *cmd, int tty);
10374
10375 int get_and_display_threadinfo (threadref *ref);
10376
10377 static void threadinfo_test_cmd (char *cmd, int tty);
10378
10379 static int thread_display_step (threadref *ref, void *context);
10380
10381 static void threadlist_update_test_cmd (char *cmd, int tty);
10382
10383 static void init_remote_threadtests (void);
10384
10385 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
10386
10387 static void
10388 threadset_test_cmd (char *cmd, int tty)
10389 {
10390   int sample_thread = SAMPLE_THREAD;
10391
10392   printf_filtered (_("Remote threadset test\n"));
10393   set_general_thread (sample_thread);
10394 }
10395
10396
10397 static void
10398 threadalive_test (char *cmd, int tty)
10399 {
10400   int sample_thread = SAMPLE_THREAD;
10401   int pid = ptid_get_pid (inferior_ptid);
10402   ptid_t ptid = ptid_build (pid, sample_thread, 0);
10403
10404   if (remote_thread_alive (ptid))
10405     printf_filtered ("PASS: Thread alive test\n");
10406   else
10407     printf_filtered ("FAIL: Thread alive test\n");
10408 }
10409
10410 void output_threadid (char *title, threadref *ref);
10411
10412 void
10413 output_threadid (char *title, threadref *ref)
10414 {
10415   char hexid[20];
10416
10417   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
10418   hexid[16] = 0;
10419   printf_filtered ("%s  %s\n", title, (&hexid[0]));
10420 }
10421
10422 static void
10423 threadlist_test_cmd (char *cmd, int tty)
10424 {
10425   int startflag = 1;
10426   threadref nextthread;
10427   int done, result_count;
10428   threadref threadlist[3];
10429
10430   printf_filtered ("Remote Threadlist test\n");
10431   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10432                               &result_count, &threadlist[0]))
10433     printf_filtered ("FAIL: threadlist test\n");
10434   else
10435     {
10436       threadref *scan = threadlist;
10437       threadref *limit = scan + result_count;
10438
10439       while (scan < limit)
10440         output_threadid (" thread ", scan++);
10441     }
10442 }
10443
10444 void
10445 display_thread_info (struct gdb_ext_thread_info *info)
10446 {
10447   output_threadid ("Threadid: ", &info->threadid);
10448   printf_filtered ("Name: %s\n ", info->shortname);
10449   printf_filtered ("State: %s\n", info->display);
10450   printf_filtered ("other: %s\n\n", info->more_display);
10451 }
10452
10453 int
10454 get_and_display_threadinfo (threadref *ref)
10455 {
10456   int result;
10457   int set;
10458   struct gdb_ext_thread_info threadinfo;
10459
10460   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10461     | TAG_MOREDISPLAY | TAG_DISPLAY;
10462   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10463     display_thread_info (&threadinfo);
10464   return result;
10465 }
10466
10467 static void
10468 threadinfo_test_cmd (char *cmd, int tty)
10469 {
10470   int athread = SAMPLE_THREAD;
10471   threadref thread;
10472   int set;
10473
10474   int_to_threadref (&thread, athread);
10475   printf_filtered ("Remote Threadinfo test\n");
10476   if (!get_and_display_threadinfo (&thread))
10477     printf_filtered ("FAIL cannot get thread info\n");
10478 }
10479
10480 static int
10481 thread_display_step (threadref *ref, void *context)
10482 {
10483   /* output_threadid(" threadstep ",ref); *//* simple test */
10484   return get_and_display_threadinfo (ref);
10485 }
10486
10487 static void
10488 threadlist_update_test_cmd (char *cmd, int tty)
10489 {
10490   printf_filtered ("Remote Threadlist update test\n");
10491   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10492 }
10493
10494 static void
10495 init_remote_threadtests (void)
10496 {
10497   add_com ("tlist", class_obscure, threadlist_test_cmd,
10498            _("Fetch and print the remote list of "
10499              "thread identifiers, one pkt only"));
10500   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10501            _("Fetch and display info about one thread"));
10502   add_com ("tset", class_obscure, threadset_test_cmd,
10503            _("Test setting to a different thread"));
10504   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10505            _("Iterate through updating all remote thread info"));
10506   add_com ("talive", class_obscure, threadalive_test,
10507            _(" Remote thread alive test "));
10508 }
10509
10510 #endif /* 0 */
10511
10512 /* Convert a thread ID to a string.  Returns the string in a static
10513    buffer.  */
10514
10515 static char *
10516 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10517 {
10518   static char buf[64];
10519   struct remote_state *rs = get_remote_state ();
10520
10521   if (ptid_equal (ptid, null_ptid))
10522     return normal_pid_to_str (ptid);
10523   else if (ptid_is_pid (ptid))
10524     {
10525       /* Printing an inferior target id.  */
10526
10527       /* When multi-process extensions are off, there's no way in the
10528          remote protocol to know the remote process id, if there's any
10529          at all.  There's one exception --- when we're connected with
10530          target extended-remote, and we manually attached to a process
10531          with "attach PID".  We don't record anywhere a flag that
10532          allows us to distinguish that case from the case of
10533          connecting with extended-remote and the stub already being
10534          attached to a process, and reporting yes to qAttached, hence
10535          no smart special casing here.  */
10536       if (!remote_multi_process_p (rs))
10537         {
10538           xsnprintf (buf, sizeof buf, "Remote target");
10539           return buf;
10540         }
10541
10542       return normal_pid_to_str (ptid);
10543     }
10544   else
10545     {
10546       if (ptid_equal (magic_null_ptid, ptid))
10547         xsnprintf (buf, sizeof buf, "Thread <main>");
10548       else if (remote_multi_process_p (rs))
10549         if (ptid_get_lwp (ptid) == 0)
10550           return normal_pid_to_str (ptid);
10551         else
10552           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10553                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
10554       else
10555         xsnprintf (buf, sizeof buf, "Thread %ld",
10556                    ptid_get_lwp (ptid));
10557       return buf;
10558     }
10559 }
10560
10561 /* Get the address of the thread local variable in OBJFILE which is
10562    stored at OFFSET within the thread local storage for thread PTID.  */
10563
10564 static CORE_ADDR
10565 remote_get_thread_local_address (struct target_ops *ops,
10566                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10567 {
10568   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10569     {
10570       struct remote_state *rs = get_remote_state ();
10571       char *p = rs->buf;
10572       char *endp = rs->buf + get_remote_packet_size ();
10573       enum packet_result result;
10574
10575       strcpy (p, "qGetTLSAddr:");
10576       p += strlen (p);
10577       p = write_ptid (p, endp, ptid);
10578       *p++ = ',';
10579       p += hexnumstr (p, offset);
10580       *p++ = ',';
10581       p += hexnumstr (p, lm);
10582       *p++ = '\0';
10583
10584       putpkt (rs->buf);
10585       getpkt (&rs->buf, &rs->buf_size, 0);
10586       result = packet_ok (rs->buf,
10587                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
10588       if (result == PACKET_OK)
10589         {
10590           ULONGEST result;
10591
10592           unpack_varlen_hex (rs->buf, &result);
10593           return result;
10594         }
10595       else if (result == PACKET_UNKNOWN)
10596         throw_error (TLS_GENERIC_ERROR,
10597                      _("Remote target doesn't support qGetTLSAddr packet"));
10598       else
10599         throw_error (TLS_GENERIC_ERROR,
10600                      _("Remote target failed to process qGetTLSAddr request"));
10601     }
10602   else
10603     throw_error (TLS_GENERIC_ERROR,
10604                  _("TLS not supported or disabled on this target"));
10605   /* Not reached.  */
10606   return 0;
10607 }
10608
10609 /* Provide thread local base, i.e. Thread Information Block address.
10610    Returns 1 if ptid is found and thread_local_base is non zero.  */
10611
10612 static int
10613 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10614 {
10615   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10616     {
10617       struct remote_state *rs = get_remote_state ();
10618       char *p = rs->buf;
10619       char *endp = rs->buf + get_remote_packet_size ();
10620       enum packet_result result;
10621
10622       strcpy (p, "qGetTIBAddr:");
10623       p += strlen (p);
10624       p = write_ptid (p, endp, ptid);
10625       *p++ = '\0';
10626
10627       putpkt (rs->buf);
10628       getpkt (&rs->buf, &rs->buf_size, 0);
10629       result = packet_ok (rs->buf,
10630                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
10631       if (result == PACKET_OK)
10632         {
10633           ULONGEST result;
10634
10635           unpack_varlen_hex (rs->buf, &result);
10636           if (addr)
10637             *addr = (CORE_ADDR) result;
10638           return 1;
10639         }
10640       else if (result == PACKET_UNKNOWN)
10641         error (_("Remote target doesn't support qGetTIBAddr packet"));
10642       else
10643         error (_("Remote target failed to process qGetTIBAddr request"));
10644     }
10645   else
10646     error (_("qGetTIBAddr not supported or disabled on this target"));
10647   /* Not reached.  */
10648   return 0;
10649 }
10650
10651 /* Support for inferring a target description based on the current
10652    architecture and the size of a 'g' packet.  While the 'g' packet
10653    can have any size (since optional registers can be left off the
10654    end), some sizes are easily recognizable given knowledge of the
10655    approximate architecture.  */
10656
10657 struct remote_g_packet_guess
10658 {
10659   int bytes;
10660   const struct target_desc *tdesc;
10661 };
10662 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10663 DEF_VEC_O(remote_g_packet_guess_s);
10664
10665 struct remote_g_packet_data
10666 {
10667   VEC(remote_g_packet_guess_s) *guesses;
10668 };
10669
10670 static struct gdbarch_data *remote_g_packet_data_handle;
10671
10672 static void *
10673 remote_g_packet_data_init (struct obstack *obstack)
10674 {
10675   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10676 }
10677
10678 void
10679 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10680                                 const struct target_desc *tdesc)
10681 {
10682   struct remote_g_packet_data *data
10683     = ((struct remote_g_packet_data *)
10684        gdbarch_data (gdbarch, remote_g_packet_data_handle));
10685   struct remote_g_packet_guess new_guess, *guess;
10686   int ix;
10687
10688   gdb_assert (tdesc != NULL);
10689
10690   for (ix = 0;
10691        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10692        ix++)
10693     if (guess->bytes == bytes)
10694       internal_error (__FILE__, __LINE__,
10695                       _("Duplicate g packet description added for size %d"),
10696                       bytes);
10697
10698   new_guess.bytes = bytes;
10699   new_guess.tdesc = tdesc;
10700   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10701 }
10702
10703 /* Return 1 if remote_read_description would do anything on this target
10704    and architecture, 0 otherwise.  */
10705
10706 static int
10707 remote_read_description_p (struct target_ops *target)
10708 {
10709   struct remote_g_packet_data *data
10710     = ((struct remote_g_packet_data *)
10711        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10712
10713   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10714     return 1;
10715
10716   return 0;
10717 }
10718
10719 static const struct target_desc *
10720 remote_read_description (struct target_ops *target)
10721 {
10722   struct remote_g_packet_data *data
10723     = ((struct remote_g_packet_data *)
10724        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10725
10726   /* Do not try this during initial connection, when we do not know
10727      whether there is a running but stopped thread.  */
10728   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10729     return target->beneath->to_read_description (target->beneath);
10730
10731   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10732     {
10733       struct remote_g_packet_guess *guess;
10734       int ix;
10735       int bytes = send_g_packet ();
10736
10737       for (ix = 0;
10738            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10739            ix++)
10740         if (guess->bytes == bytes)
10741           return guess->tdesc;
10742
10743       /* We discard the g packet.  A minor optimization would be to
10744          hold on to it, and fill the register cache once we have selected
10745          an architecture, but it's too tricky to do safely.  */
10746     }
10747
10748   return target->beneath->to_read_description (target->beneath);
10749 }
10750
10751 /* Remote file transfer support.  This is host-initiated I/O, not
10752    target-initiated; for target-initiated, see remote-fileio.c.  */
10753
10754 /* If *LEFT is at least the length of STRING, copy STRING to
10755    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10756    decrease *LEFT.  Otherwise raise an error.  */
10757
10758 static void
10759 remote_buffer_add_string (char **buffer, int *left, char *string)
10760 {
10761   int len = strlen (string);
10762
10763   if (len > *left)
10764     error (_("Packet too long for target."));
10765
10766   memcpy (*buffer, string, len);
10767   *buffer += len;
10768   *left -= len;
10769
10770   /* NUL-terminate the buffer as a convenience, if there is
10771      room.  */
10772   if (*left)
10773     **buffer = '\0';
10774 }
10775
10776 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10777    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10778    decrease *LEFT.  Otherwise raise an error.  */
10779
10780 static void
10781 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10782                          int len)
10783 {
10784   if (2 * len > *left)
10785     error (_("Packet too long for target."));
10786
10787   bin2hex (bytes, *buffer, len);
10788   *buffer += 2 * len;
10789   *left -= 2 * len;
10790
10791   /* NUL-terminate the buffer as a convenience, if there is
10792      room.  */
10793   if (*left)
10794     **buffer = '\0';
10795 }
10796
10797 /* If *LEFT is large enough, convert VALUE to hex and add it to
10798    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10799    decrease *LEFT.  Otherwise raise an error.  */
10800
10801 static void
10802 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10803 {
10804   int len = hexnumlen (value);
10805
10806   if (len > *left)
10807     error (_("Packet too long for target."));
10808
10809   hexnumstr (*buffer, value);
10810   *buffer += len;
10811   *left -= len;
10812
10813   /* NUL-terminate the buffer as a convenience, if there is
10814      room.  */
10815   if (*left)
10816     **buffer = '\0';
10817 }
10818
10819 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
10820    value, *REMOTE_ERRNO to the remote error number or zero if none
10821    was included, and *ATTACHMENT to point to the start of the annex
10822    if any.  The length of the packet isn't needed here; there may
10823    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10824
10825    Return 0 if the packet could be parsed, -1 if it could not.  If
10826    -1 is returned, the other variables may not be initialized.  */
10827
10828 static int
10829 remote_hostio_parse_result (char *buffer, int *retcode,
10830                             int *remote_errno, char **attachment)
10831 {
10832   char *p, *p2;
10833
10834   *remote_errno = 0;
10835   *attachment = NULL;
10836
10837   if (buffer[0] != 'F')
10838     return -1;
10839
10840   errno = 0;
10841   *retcode = strtol (&buffer[1], &p, 16);
10842   if (errno != 0 || p == &buffer[1])
10843     return -1;
10844
10845   /* Check for ",errno".  */
10846   if (*p == ',')
10847     {
10848       errno = 0;
10849       *remote_errno = strtol (p + 1, &p2, 16);
10850       if (errno != 0 || p + 1 == p2)
10851         return -1;
10852       p = p2;
10853     }
10854
10855   /* Check for ";attachment".  If there is no attachment, the
10856      packet should end here.  */
10857   if (*p == ';')
10858     {
10859       *attachment = p + 1;
10860       return 0;
10861     }
10862   else if (*p == '\0')
10863     return 0;
10864   else
10865     return -1;
10866 }
10867
10868 /* Send a prepared I/O packet to the target and read its response.
10869    The prepared packet is in the global RS->BUF before this function
10870    is called, and the answer is there when we return.
10871
10872    COMMAND_BYTES is the length of the request to send, which may include
10873    binary data.  WHICH_PACKET is the packet configuration to check
10874    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
10875    is set to the error number and -1 is returned.  Otherwise the value
10876    returned by the function is returned.
10877
10878    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10879    attachment is expected; an error will be reported if there's a
10880    mismatch.  If one is found, *ATTACHMENT will be set to point into
10881    the packet buffer and *ATTACHMENT_LEN will be set to the
10882    attachment's length.  */
10883
10884 static int
10885 remote_hostio_send_command (int command_bytes, int which_packet,
10886                             int *remote_errno, char **attachment,
10887                             int *attachment_len)
10888 {
10889   struct remote_state *rs = get_remote_state ();
10890   int ret, bytes_read;
10891   char *attachment_tmp;
10892
10893   if (!rs->remote_desc
10894       || packet_support (which_packet) == PACKET_DISABLE)
10895     {
10896       *remote_errno = FILEIO_ENOSYS;
10897       return -1;
10898     }
10899
10900   putpkt_binary (rs->buf, command_bytes);
10901   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10902
10903   /* If it timed out, something is wrong.  Don't try to parse the
10904      buffer.  */
10905   if (bytes_read < 0)
10906     {
10907       *remote_errno = FILEIO_EINVAL;
10908       return -1;
10909     }
10910
10911   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10912     {
10913     case PACKET_ERROR:
10914       *remote_errno = FILEIO_EINVAL;
10915       return -1;
10916     case PACKET_UNKNOWN:
10917       *remote_errno = FILEIO_ENOSYS;
10918       return -1;
10919     case PACKET_OK:
10920       break;
10921     }
10922
10923   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10924                                   &attachment_tmp))
10925     {
10926       *remote_errno = FILEIO_EINVAL;
10927       return -1;
10928     }
10929
10930   /* Make sure we saw an attachment if and only if we expected one.  */
10931   if ((attachment_tmp == NULL && attachment != NULL)
10932       || (attachment_tmp != NULL && attachment == NULL))
10933     {
10934       *remote_errno = FILEIO_EINVAL;
10935       return -1;
10936     }
10937
10938   /* If an attachment was found, it must point into the packet buffer;
10939      work out how many bytes there were.  */
10940   if (attachment_tmp != NULL)
10941     {
10942       *attachment = attachment_tmp;
10943       *attachment_len = bytes_read - (*attachment - rs->buf);
10944     }
10945
10946   return ret;
10947 }
10948
10949 /* Invalidate the readahead cache.  */
10950
10951 static void
10952 readahead_cache_invalidate (void)
10953 {
10954   struct remote_state *rs = get_remote_state ();
10955
10956   rs->readahead_cache.fd = -1;
10957 }
10958
10959 /* Invalidate the readahead cache if it is holding data for FD.  */
10960
10961 static void
10962 readahead_cache_invalidate_fd (int fd)
10963 {
10964   struct remote_state *rs = get_remote_state ();
10965
10966   if (rs->readahead_cache.fd == fd)
10967     rs->readahead_cache.fd = -1;
10968 }
10969
10970 /* Set the filesystem remote_hostio functions that take FILENAME
10971    arguments will use.  Return 0 on success, or -1 if an error
10972    occurs (and set *REMOTE_ERRNO).  */
10973
10974 static int
10975 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10976 {
10977   struct remote_state *rs = get_remote_state ();
10978   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10979   char *p = rs->buf;
10980   int left = get_remote_packet_size () - 1;
10981   char arg[9];
10982   int ret;
10983
10984   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10985     return 0;
10986
10987   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10988     return 0;
10989
10990   remote_buffer_add_string (&p, &left, "vFile:setfs:");
10991
10992   xsnprintf (arg, sizeof (arg), "%x", required_pid);
10993   remote_buffer_add_string (&p, &left, arg);
10994
10995   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10996                                     remote_errno, NULL, NULL);
10997
10998   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10999     return 0;
11000
11001   if (ret == 0)
11002     rs->fs_pid = required_pid;
11003
11004   return ret;
11005 }
11006
11007 /* Implementation of to_fileio_open.  */
11008
11009 static int
11010 remote_hostio_open (struct target_ops *self,
11011                     struct inferior *inf, const char *filename,
11012                     int flags, int mode, int warn_if_slow,
11013                     int *remote_errno)
11014 {
11015   struct remote_state *rs = get_remote_state ();
11016   char *p = rs->buf;
11017   int left = get_remote_packet_size () - 1;
11018
11019   if (warn_if_slow)
11020     {
11021       static int warning_issued = 0;
11022
11023       printf_unfiltered (_("Reading %s from remote target...\n"),
11024                          filename);
11025
11026       if (!warning_issued)
11027         {
11028           warning (_("File transfers from remote targets can be slow."
11029                      " Use \"set sysroot\" to access files locally"
11030                      " instead."));
11031           warning_issued = 1;
11032         }
11033     }
11034
11035   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11036     return -1;
11037
11038   remote_buffer_add_string (&p, &left, "vFile:open:");
11039
11040   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11041                            strlen (filename));
11042   remote_buffer_add_string (&p, &left, ",");
11043
11044   remote_buffer_add_int (&p, &left, flags);
11045   remote_buffer_add_string (&p, &left, ",");
11046
11047   remote_buffer_add_int (&p, &left, mode);
11048
11049   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11050                                      remote_errno, NULL, NULL);
11051 }
11052
11053 /* Implementation of to_fileio_pwrite.  */
11054
11055 static int
11056 remote_hostio_pwrite (struct target_ops *self,
11057                       int fd, const gdb_byte *write_buf, int len,
11058                       ULONGEST offset, int *remote_errno)
11059 {
11060   struct remote_state *rs = get_remote_state ();
11061   char *p = rs->buf;
11062   int left = get_remote_packet_size ();
11063   int out_len;
11064
11065   readahead_cache_invalidate_fd (fd);
11066
11067   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11068
11069   remote_buffer_add_int (&p, &left, fd);
11070   remote_buffer_add_string (&p, &left, ",");
11071
11072   remote_buffer_add_int (&p, &left, offset);
11073   remote_buffer_add_string (&p, &left, ",");
11074
11075   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11076                              get_remote_packet_size () - (p - rs->buf));
11077
11078   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11079                                      remote_errno, NULL, NULL);
11080 }
11081
11082 /* Helper for the implementation of to_fileio_pread.  Read the file
11083    from the remote side with vFile:pread.  */
11084
11085 static int
11086 remote_hostio_pread_vFile (struct target_ops *self,
11087                            int fd, gdb_byte *read_buf, int len,
11088                            ULONGEST offset, int *remote_errno)
11089 {
11090   struct remote_state *rs = get_remote_state ();
11091   char *p = rs->buf;
11092   char *attachment;
11093   int left = get_remote_packet_size ();
11094   int ret, attachment_len;
11095   int read_len;
11096
11097   remote_buffer_add_string (&p, &left, "vFile:pread:");
11098
11099   remote_buffer_add_int (&p, &left, fd);
11100   remote_buffer_add_string (&p, &left, ",");
11101
11102   remote_buffer_add_int (&p, &left, len);
11103   remote_buffer_add_string (&p, &left, ",");
11104
11105   remote_buffer_add_int (&p, &left, offset);
11106
11107   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11108                                     remote_errno, &attachment,
11109                                     &attachment_len);
11110
11111   if (ret < 0)
11112     return ret;
11113
11114   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11115                                     read_buf, len);
11116   if (read_len != ret)
11117     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11118
11119   return ret;
11120 }
11121
11122 /* Serve pread from the readahead cache.  Returns number of bytes
11123    read, or 0 if the request can't be served from the cache.  */
11124
11125 static int
11126 remote_hostio_pread_from_cache (struct remote_state *rs,
11127                                 int fd, gdb_byte *read_buf, size_t len,
11128                                 ULONGEST offset)
11129 {
11130   struct readahead_cache *cache = &rs->readahead_cache;
11131
11132   if (cache->fd == fd
11133       && cache->offset <= offset
11134       && offset < cache->offset + cache->bufsize)
11135     {
11136       ULONGEST max = cache->offset + cache->bufsize;
11137
11138       if (offset + len > max)
11139         len = max - offset;
11140
11141       memcpy (read_buf, cache->buf + offset - cache->offset, len);
11142       return len;
11143     }
11144
11145   return 0;
11146 }
11147
11148 /* Implementation of to_fileio_pread.  */
11149
11150 static int
11151 remote_hostio_pread (struct target_ops *self,
11152                      int fd, gdb_byte *read_buf, int len,
11153                      ULONGEST offset, int *remote_errno)
11154 {
11155   int ret;
11156   struct remote_state *rs = get_remote_state ();
11157   struct readahead_cache *cache = &rs->readahead_cache;
11158
11159   ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11160   if (ret > 0)
11161     {
11162       cache->hit_count++;
11163
11164       if (remote_debug)
11165         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11166                             pulongest (cache->hit_count));
11167       return ret;
11168     }
11169
11170   cache->miss_count++;
11171   if (remote_debug)
11172     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11173                         pulongest (cache->miss_count));
11174
11175   cache->fd = fd;
11176   cache->offset = offset;
11177   cache->bufsize = get_remote_packet_size ();
11178   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11179
11180   ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11181                                    cache->offset, remote_errno);
11182   if (ret <= 0)
11183     {
11184       readahead_cache_invalidate_fd (fd);
11185       return ret;
11186     }
11187
11188   cache->bufsize = ret;
11189   return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11190 }
11191
11192 /* Implementation of to_fileio_close.  */
11193
11194 static int
11195 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11196 {
11197   struct remote_state *rs = get_remote_state ();
11198   char *p = rs->buf;
11199   int left = get_remote_packet_size () - 1;
11200
11201   readahead_cache_invalidate_fd (fd);
11202
11203   remote_buffer_add_string (&p, &left, "vFile:close:");
11204
11205   remote_buffer_add_int (&p, &left, fd);
11206
11207   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11208                                      remote_errno, NULL, NULL);
11209 }
11210
11211 /* Implementation of to_fileio_unlink.  */
11212
11213 static int
11214 remote_hostio_unlink (struct target_ops *self,
11215                       struct inferior *inf, const char *filename,
11216                       int *remote_errno)
11217 {
11218   struct remote_state *rs = get_remote_state ();
11219   char *p = rs->buf;
11220   int left = get_remote_packet_size () - 1;
11221
11222   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11223     return -1;
11224
11225   remote_buffer_add_string (&p, &left, "vFile:unlink:");
11226
11227   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11228                            strlen (filename));
11229
11230   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11231                                      remote_errno, NULL, NULL);
11232 }
11233
11234 /* Implementation of to_fileio_readlink.  */
11235
11236 static char *
11237 remote_hostio_readlink (struct target_ops *self,
11238                         struct inferior *inf, const char *filename,
11239                         int *remote_errno)
11240 {
11241   struct remote_state *rs = get_remote_state ();
11242   char *p = rs->buf;
11243   char *attachment;
11244   int left = get_remote_packet_size ();
11245   int len, attachment_len;
11246   int read_len;
11247   char *ret;
11248
11249   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11250     return NULL;
11251
11252   remote_buffer_add_string (&p, &left, "vFile:readlink:");
11253
11254   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11255                            strlen (filename));
11256
11257   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11258                                     remote_errno, &attachment,
11259                                     &attachment_len);
11260
11261   if (len < 0)
11262     return NULL;
11263
11264   ret = (char *) xmalloc (len + 1);
11265
11266   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11267                                     (gdb_byte *) ret, len);
11268   if (read_len != len)
11269     error (_("Readlink returned %d, but %d bytes."), len, read_len);
11270
11271   ret[len] = '\0';
11272   return ret;
11273 }
11274
11275 /* Implementation of to_fileio_fstat.  */
11276
11277 static int
11278 remote_hostio_fstat (struct target_ops *self,
11279                      int fd, struct stat *st,
11280                      int *remote_errno)
11281 {
11282   struct remote_state *rs = get_remote_state ();
11283   char *p = rs->buf;
11284   int left = get_remote_packet_size ();
11285   int attachment_len, ret;
11286   char *attachment;
11287   struct fio_stat fst;
11288   int read_len;
11289
11290   remote_buffer_add_string (&p, &left, "vFile:fstat:");
11291
11292   remote_buffer_add_int (&p, &left, fd);
11293
11294   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11295                                     remote_errno, &attachment,
11296                                     &attachment_len);
11297   if (ret < 0)
11298     {
11299       if (*remote_errno != FILEIO_ENOSYS)
11300         return ret;
11301
11302       /* Strictly we should return -1, ENOSYS here, but when
11303          "set sysroot remote:" was implemented in August 2008
11304          BFD's need for a stat function was sidestepped with
11305          this hack.  This was not remedied until March 2015
11306          so we retain the previous behavior to avoid breaking
11307          compatibility.
11308
11309          Note that the memset is a March 2015 addition; older
11310          GDBs set st_size *and nothing else* so the structure
11311          would have garbage in all other fields.  This might
11312          break something but retaining the previous behavior
11313          here would be just too wrong.  */
11314
11315       memset (st, 0, sizeof (struct stat));
11316       st->st_size = INT_MAX;
11317       return 0;
11318     }
11319
11320   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11321                                     (gdb_byte *) &fst, sizeof (fst));
11322
11323   if (read_len != ret)
11324     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11325
11326   if (read_len != sizeof (fst))
11327     error (_("vFile:fstat returned %d bytes, but expecting %d."),
11328            read_len, (int) sizeof (fst));
11329
11330   remote_fileio_to_host_stat (&fst, st);
11331
11332   return 0;
11333 }
11334
11335 /* Implementation of to_filesystem_is_local.  */
11336
11337 static int
11338 remote_filesystem_is_local (struct target_ops *self)
11339 {
11340   /* Valgrind GDB presents itself as a remote target but works
11341      on the local filesystem: it does not implement remote get
11342      and users are not expected to set a sysroot.  To handle
11343      this case we treat the remote filesystem as local if the
11344      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11345      does not support vFile:open.  */
11346   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11347     {
11348       enum packet_support ps = packet_support (PACKET_vFile_open);
11349
11350       if (ps == PACKET_SUPPORT_UNKNOWN)
11351         {
11352           int fd, remote_errno;
11353
11354           /* Try opening a file to probe support.  The supplied
11355              filename is irrelevant, we only care about whether
11356              the stub recognizes the packet or not.  */
11357           fd = remote_hostio_open (self, NULL, "just probing",
11358                                    FILEIO_O_RDONLY, 0700, 0,
11359                                    &remote_errno);
11360
11361           if (fd >= 0)
11362             remote_hostio_close (self, fd, &remote_errno);
11363
11364           ps = packet_support (PACKET_vFile_open);
11365         }
11366
11367       if (ps == PACKET_DISABLE)
11368         {
11369           static int warning_issued = 0;
11370
11371           if (!warning_issued)
11372             {
11373               warning (_("remote target does not support file"
11374                          " transfer, attempting to access files"
11375                          " from local filesystem."));
11376               warning_issued = 1;
11377             }
11378
11379           return 1;
11380         }
11381     }
11382
11383   return 0;
11384 }
11385
11386 static int
11387 remote_fileio_errno_to_host (int errnum)
11388 {
11389   switch (errnum)
11390     {
11391       case FILEIO_EPERM:
11392         return EPERM;
11393       case FILEIO_ENOENT:
11394         return ENOENT;
11395       case FILEIO_EINTR:
11396         return EINTR;
11397       case FILEIO_EIO:
11398         return EIO;
11399       case FILEIO_EBADF:
11400         return EBADF;
11401       case FILEIO_EACCES:
11402         return EACCES;
11403       case FILEIO_EFAULT:
11404         return EFAULT;
11405       case FILEIO_EBUSY:
11406         return EBUSY;
11407       case FILEIO_EEXIST:
11408         return EEXIST;
11409       case FILEIO_ENODEV:
11410         return ENODEV;
11411       case FILEIO_ENOTDIR:
11412         return ENOTDIR;
11413       case FILEIO_EISDIR:
11414         return EISDIR;
11415       case FILEIO_EINVAL:
11416         return EINVAL;
11417       case FILEIO_ENFILE:
11418         return ENFILE;
11419       case FILEIO_EMFILE:
11420         return EMFILE;
11421       case FILEIO_EFBIG:
11422         return EFBIG;
11423       case FILEIO_ENOSPC:
11424         return ENOSPC;
11425       case FILEIO_ESPIPE:
11426         return ESPIPE;
11427       case FILEIO_EROFS:
11428         return EROFS;
11429       case FILEIO_ENOSYS:
11430         return ENOSYS;
11431       case FILEIO_ENAMETOOLONG:
11432         return ENAMETOOLONG;
11433     }
11434   return -1;
11435 }
11436
11437 static char *
11438 remote_hostio_error (int errnum)
11439 {
11440   int host_error = remote_fileio_errno_to_host (errnum);
11441
11442   if (host_error == -1)
11443     error (_("Unknown remote I/O error %d"), errnum);
11444   else
11445     error (_("Remote I/O error: %s"), safe_strerror (host_error));
11446 }
11447
11448 static void
11449 remote_hostio_close_cleanup (void *opaque)
11450 {
11451   int fd = *(int *) opaque;
11452   int remote_errno;
11453
11454   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11455 }
11456
11457 void
11458 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11459 {
11460   struct cleanup *back_to, *close_cleanup;
11461   int retcode, fd, remote_errno, bytes, io_size;
11462   FILE *file;
11463   gdb_byte *buffer;
11464   int bytes_in_buffer;
11465   int saw_eof;
11466   ULONGEST offset;
11467   struct remote_state *rs = get_remote_state ();
11468
11469   if (!rs->remote_desc)
11470     error (_("command can only be used with remote target"));
11471
11472   file = gdb_fopen_cloexec (local_file, "rb");
11473   if (file == NULL)
11474     perror_with_name (local_file);
11475   back_to = make_cleanup_fclose (file);
11476
11477   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11478                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11479                                          | FILEIO_O_TRUNC),
11480                            0700, 0, &remote_errno);
11481   if (fd == -1)
11482     remote_hostio_error (remote_errno);
11483
11484   /* Send up to this many bytes at once.  They won't all fit in the
11485      remote packet limit, so we'll transfer slightly fewer.  */
11486   io_size = get_remote_packet_size ();
11487   buffer = (gdb_byte *) xmalloc (io_size);
11488   make_cleanup (xfree, buffer);
11489
11490   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11491
11492   bytes_in_buffer = 0;
11493   saw_eof = 0;
11494   offset = 0;
11495   while (bytes_in_buffer || !saw_eof)
11496     {
11497       if (!saw_eof)
11498         {
11499           bytes = fread (buffer + bytes_in_buffer, 1,
11500                          io_size - bytes_in_buffer,
11501                          file);
11502           if (bytes == 0)
11503             {
11504               if (ferror (file))
11505                 error (_("Error reading %s."), local_file);
11506               else
11507                 {
11508                   /* EOF.  Unless there is something still in the
11509                      buffer from the last iteration, we are done.  */
11510                   saw_eof = 1;
11511                   if (bytes_in_buffer == 0)
11512                     break;
11513                 }
11514             }
11515         }
11516       else
11517         bytes = 0;
11518
11519       bytes += bytes_in_buffer;
11520       bytes_in_buffer = 0;
11521
11522       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11523                                       fd, buffer, bytes,
11524                                       offset, &remote_errno);
11525
11526       if (retcode < 0)
11527         remote_hostio_error (remote_errno);
11528       else if (retcode == 0)
11529         error (_("Remote write of %d bytes returned 0!"), bytes);
11530       else if (retcode < bytes)
11531         {
11532           /* Short write.  Save the rest of the read data for the next
11533              write.  */
11534           bytes_in_buffer = bytes - retcode;
11535           memmove (buffer, buffer + retcode, bytes_in_buffer);
11536         }
11537
11538       offset += retcode;
11539     }
11540
11541   discard_cleanups (close_cleanup);
11542   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11543     remote_hostio_error (remote_errno);
11544
11545   if (from_tty)
11546     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11547   do_cleanups (back_to);
11548 }
11549
11550 void
11551 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11552 {
11553   struct cleanup *back_to, *close_cleanup;
11554   int fd, remote_errno, bytes, io_size;
11555   FILE *file;
11556   gdb_byte *buffer;
11557   ULONGEST offset;
11558   struct remote_state *rs = get_remote_state ();
11559
11560   if (!rs->remote_desc)
11561     error (_("command can only be used with remote target"));
11562
11563   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11564                            remote_file, FILEIO_O_RDONLY, 0, 0,
11565                            &remote_errno);
11566   if (fd == -1)
11567     remote_hostio_error (remote_errno);
11568
11569   file = gdb_fopen_cloexec (local_file, "wb");
11570   if (file == NULL)
11571     perror_with_name (local_file);
11572   back_to = make_cleanup_fclose (file);
11573
11574   /* Send up to this many bytes at once.  They won't all fit in the
11575      remote packet limit, so we'll transfer slightly fewer.  */
11576   io_size = get_remote_packet_size ();
11577   buffer = (gdb_byte *) xmalloc (io_size);
11578   make_cleanup (xfree, buffer);
11579
11580   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11581
11582   offset = 0;
11583   while (1)
11584     {
11585       bytes = remote_hostio_pread (find_target_at (process_stratum),
11586                                    fd, buffer, io_size, offset, &remote_errno);
11587       if (bytes == 0)
11588         /* Success, but no bytes, means end-of-file.  */
11589         break;
11590       if (bytes == -1)
11591         remote_hostio_error (remote_errno);
11592
11593       offset += bytes;
11594
11595       bytes = fwrite (buffer, 1, bytes, file);
11596       if (bytes == 0)
11597         perror_with_name (local_file);
11598     }
11599
11600   discard_cleanups (close_cleanup);
11601   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11602     remote_hostio_error (remote_errno);
11603
11604   if (from_tty)
11605     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11606   do_cleanups (back_to);
11607 }
11608
11609 void
11610 remote_file_delete (const char *remote_file, int from_tty)
11611 {
11612   int retcode, remote_errno;
11613   struct remote_state *rs = get_remote_state ();
11614
11615   if (!rs->remote_desc)
11616     error (_("command can only be used with remote target"));
11617
11618   retcode = remote_hostio_unlink (find_target_at (process_stratum),
11619                                   NULL, remote_file, &remote_errno);
11620   if (retcode == -1)
11621     remote_hostio_error (remote_errno);
11622
11623   if (from_tty)
11624     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11625 }
11626
11627 static void
11628 remote_put_command (char *args, int from_tty)
11629 {
11630   struct cleanup *back_to;
11631   char **argv;
11632
11633   if (args == NULL)
11634     error_no_arg (_("file to put"));
11635
11636   argv = gdb_buildargv (args);
11637   back_to = make_cleanup_freeargv (argv);
11638   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11639     error (_("Invalid parameters to remote put"));
11640
11641   remote_file_put (argv[0], argv[1], from_tty);
11642
11643   do_cleanups (back_to);
11644 }
11645
11646 static void
11647 remote_get_command (char *args, int from_tty)
11648 {
11649   struct cleanup *back_to;
11650   char **argv;
11651
11652   if (args == NULL)
11653     error_no_arg (_("file to get"));
11654
11655   argv = gdb_buildargv (args);
11656   back_to = make_cleanup_freeargv (argv);
11657   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11658     error (_("Invalid parameters to remote get"));
11659
11660   remote_file_get (argv[0], argv[1], from_tty);
11661
11662   do_cleanups (back_to);
11663 }
11664
11665 static void
11666 remote_delete_command (char *args, int from_tty)
11667 {
11668   struct cleanup *back_to;
11669   char **argv;
11670
11671   if (args == NULL)
11672     error_no_arg (_("file to delete"));
11673
11674   argv = gdb_buildargv (args);
11675   back_to = make_cleanup_freeargv (argv);
11676   if (argv[0] == NULL || argv[1] != NULL)
11677     error (_("Invalid parameters to remote delete"));
11678
11679   remote_file_delete (argv[0], from_tty);
11680
11681   do_cleanups (back_to);
11682 }
11683
11684 static void
11685 remote_command (char *args, int from_tty)
11686 {
11687   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11688 }
11689
11690 static int
11691 remote_can_execute_reverse (struct target_ops *self)
11692 {
11693   if (packet_support (PACKET_bs) == PACKET_ENABLE
11694       || packet_support (PACKET_bc) == PACKET_ENABLE)
11695     return 1;
11696   else
11697     return 0;
11698 }
11699
11700 static int
11701 remote_supports_non_stop (struct target_ops *self)
11702 {
11703   return 1;
11704 }
11705
11706 static int
11707 remote_supports_disable_randomization (struct target_ops *self)
11708 {
11709   /* Only supported in extended mode.  */
11710   return 0;
11711 }
11712
11713 static int
11714 remote_supports_multi_process (struct target_ops *self)
11715 {
11716   struct remote_state *rs = get_remote_state ();
11717
11718   return remote_multi_process_p (rs);
11719 }
11720
11721 static int
11722 remote_supports_cond_tracepoints (void)
11723 {
11724   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11725 }
11726
11727 static int
11728 remote_supports_cond_breakpoints (struct target_ops *self)
11729 {
11730   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11731 }
11732
11733 static int
11734 remote_supports_fast_tracepoints (void)
11735 {
11736   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11737 }
11738
11739 static int
11740 remote_supports_static_tracepoints (void)
11741 {
11742   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11743 }
11744
11745 static int
11746 remote_supports_install_in_trace (void)
11747 {
11748   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11749 }
11750
11751 static int
11752 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11753 {
11754   return (packet_support (PACKET_EnableDisableTracepoints_feature)
11755           == PACKET_ENABLE);
11756 }
11757
11758 static int
11759 remote_supports_string_tracing (struct target_ops *self)
11760 {
11761   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11762 }
11763
11764 static int
11765 remote_can_run_breakpoint_commands (struct target_ops *self)
11766 {
11767   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11768 }
11769
11770 static void
11771 remote_trace_init (struct target_ops *self)
11772 {
11773   putpkt ("QTinit");
11774   remote_get_noisy_reply (&target_buf, &target_buf_size);
11775   if (strcmp (target_buf, "OK") != 0)
11776     error (_("Target does not support this command."));
11777 }
11778
11779 static void free_actions_list (char **actions_list);
11780 static void free_actions_list_cleanup_wrapper (void *);
11781 static void
11782 free_actions_list_cleanup_wrapper (void *al)
11783 {
11784   free_actions_list ((char **) al);
11785 }
11786
11787 static void
11788 free_actions_list (char **actions_list)
11789 {
11790   int ndx;
11791
11792   if (actions_list == 0)
11793     return;
11794
11795   for (ndx = 0; actions_list[ndx]; ndx++)
11796     xfree (actions_list[ndx]);
11797
11798   xfree (actions_list);
11799 }
11800
11801 /* Recursive routine to walk through command list including loops, and
11802    download packets for each command.  */
11803
11804 static void
11805 remote_download_command_source (int num, ULONGEST addr,
11806                                 struct command_line *cmds)
11807 {
11808   struct remote_state *rs = get_remote_state ();
11809   struct command_line *cmd;
11810
11811   for (cmd = cmds; cmd; cmd = cmd->next)
11812     {
11813       QUIT;     /* Allow user to bail out with ^C.  */
11814       strcpy (rs->buf, "QTDPsrc:");
11815       encode_source_string (num, addr, "cmd", cmd->line,
11816                             rs->buf + strlen (rs->buf),
11817                             rs->buf_size - strlen (rs->buf));
11818       putpkt (rs->buf);
11819       remote_get_noisy_reply (&target_buf, &target_buf_size);
11820       if (strcmp (target_buf, "OK"))
11821         warning (_("Target does not support source download."));
11822
11823       if (cmd->control_type == while_control
11824           || cmd->control_type == while_stepping_control)
11825         {
11826           remote_download_command_source (num, addr, *cmd->body_list);
11827
11828           QUIT; /* Allow user to bail out with ^C.  */
11829           strcpy (rs->buf, "QTDPsrc:");
11830           encode_source_string (num, addr, "cmd", "end",
11831                                 rs->buf + strlen (rs->buf),
11832                                 rs->buf_size - strlen (rs->buf));
11833           putpkt (rs->buf);
11834           remote_get_noisy_reply (&target_buf, &target_buf_size);
11835           if (strcmp (target_buf, "OK"))
11836             warning (_("Target does not support source download."));
11837         }
11838     }
11839 }
11840
11841 static void
11842 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11843 {
11844 #define BUF_SIZE 2048
11845
11846   CORE_ADDR tpaddr;
11847   char addrbuf[40];
11848   char buf[BUF_SIZE];
11849   char **tdp_actions;
11850   char **stepping_actions;
11851   int ndx;
11852   struct cleanup *old_chain = NULL;
11853   struct agent_expr *aexpr;
11854   struct cleanup *aexpr_chain = NULL;
11855   char *pkt;
11856   struct breakpoint *b = loc->owner;
11857   struct tracepoint *t = (struct tracepoint *) b;
11858
11859   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11860   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11861                             tdp_actions);
11862   (void) make_cleanup (free_actions_list_cleanup_wrapper,
11863                        stepping_actions);
11864
11865   tpaddr = loc->address;
11866   sprintf_vma (addrbuf, tpaddr);
11867   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11868              addrbuf, /* address */
11869              (b->enable_state == bp_enabled ? 'E' : 'D'),
11870              t->step_count, t->pass_count);
11871   /* Fast tracepoints are mostly handled by the target, but we can
11872      tell the target how big of an instruction block should be moved
11873      around.  */
11874   if (b->type == bp_fast_tracepoint)
11875     {
11876       /* Only test for support at download time; we may not know
11877          target capabilities at definition time.  */
11878       if (remote_supports_fast_tracepoints ())
11879         {
11880           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11881                                                 NULL))
11882             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11883                        gdb_insn_length (loc->gdbarch, tpaddr));
11884           else
11885             /* If it passed validation at definition but fails now,
11886                something is very wrong.  */
11887             internal_error (__FILE__, __LINE__,
11888                             _("Fast tracepoint not "
11889                               "valid during download"));
11890         }
11891       else
11892         /* Fast tracepoints are functionally identical to regular
11893            tracepoints, so don't take lack of support as a reason to
11894            give up on the trace run.  */
11895         warning (_("Target does not support fast tracepoints, "
11896                    "downloading %d as regular tracepoint"), b->number);
11897     }
11898   else if (b->type == bp_static_tracepoint)
11899     {
11900       /* Only test for support at download time; we may not know
11901          target capabilities at definition time.  */
11902       if (remote_supports_static_tracepoints ())
11903         {
11904           struct static_tracepoint_marker marker;
11905
11906           if (target_static_tracepoint_marker_at (tpaddr, &marker))
11907             strcat (buf, ":S");
11908           else
11909             error (_("Static tracepoint not valid during download"));
11910         }
11911       else
11912         /* Fast tracepoints are functionally identical to regular
11913            tracepoints, so don't take lack of support as a reason
11914            to give up on the trace run.  */
11915         error (_("Target does not support static tracepoints"));
11916     }
11917   /* If the tracepoint has a conditional, make it into an agent
11918      expression and append to the definition.  */
11919   if (loc->cond)
11920     {
11921       /* Only test support at download time, we may not know target
11922          capabilities at definition time.  */
11923       if (remote_supports_cond_tracepoints ())
11924         {
11925           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11926           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11927           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11928                      aexpr->len);
11929           pkt = buf + strlen (buf);
11930           for (ndx = 0; ndx < aexpr->len; ++ndx)
11931             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11932           *pkt = '\0';
11933           do_cleanups (aexpr_chain);
11934         }
11935       else
11936         warning (_("Target does not support conditional tracepoints, "
11937                    "ignoring tp %d cond"), b->number);
11938     }
11939
11940   if (b->commands || *default_collect)
11941     strcat (buf, "-");
11942   putpkt (buf);
11943   remote_get_noisy_reply (&target_buf, &target_buf_size);
11944   if (strcmp (target_buf, "OK"))
11945     error (_("Target does not support tracepoints."));
11946
11947   /* do_single_steps (t); */
11948   if (tdp_actions)
11949     {
11950       for (ndx = 0; tdp_actions[ndx]; ndx++)
11951         {
11952           QUIT; /* Allow user to bail out with ^C.  */
11953           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11954                      b->number, addrbuf, /* address */
11955                      tdp_actions[ndx],
11956                      ((tdp_actions[ndx + 1] || stepping_actions)
11957                       ? '-' : 0));
11958           putpkt (buf);
11959           remote_get_noisy_reply (&target_buf,
11960                                   &target_buf_size);
11961           if (strcmp (target_buf, "OK"))
11962             error (_("Error on target while setting tracepoints."));
11963         }
11964     }
11965   if (stepping_actions)
11966     {
11967       for (ndx = 0; stepping_actions[ndx]; ndx++)
11968         {
11969           QUIT; /* Allow user to bail out with ^C.  */
11970           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11971                      b->number, addrbuf, /* address */
11972                      ((ndx == 0) ? "S" : ""),
11973                      stepping_actions[ndx],
11974                      (stepping_actions[ndx + 1] ? "-" : ""));
11975           putpkt (buf);
11976           remote_get_noisy_reply (&target_buf,
11977                                   &target_buf_size);
11978           if (strcmp (target_buf, "OK"))
11979             error (_("Error on target while setting tracepoints."));
11980         }
11981     }
11982
11983   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11984     {
11985       if (b->location != NULL)
11986         {
11987           strcpy (buf, "QTDPsrc:");
11988           encode_source_string (b->number, loc->address, "at",
11989                                 event_location_to_string (b->location),
11990                                 buf + strlen (buf), 2048 - strlen (buf));
11991           putpkt (buf);
11992           remote_get_noisy_reply (&target_buf, &target_buf_size);
11993           if (strcmp (target_buf, "OK"))
11994             warning (_("Target does not support source download."));
11995         }
11996       if (b->cond_string)
11997         {
11998           strcpy (buf, "QTDPsrc:");
11999           encode_source_string (b->number, loc->address,
12000                                 "cond", b->cond_string, buf + strlen (buf),
12001                                 2048 - strlen (buf));
12002           putpkt (buf);
12003           remote_get_noisy_reply (&target_buf, &target_buf_size);
12004           if (strcmp (target_buf, "OK"))
12005             warning (_("Target does not support source download."));
12006         }
12007       remote_download_command_source (b->number, loc->address,
12008                                       breakpoint_commands (b));
12009     }
12010
12011   do_cleanups (old_chain);
12012 }
12013
12014 static int
12015 remote_can_download_tracepoint (struct target_ops *self)
12016 {
12017   struct remote_state *rs = get_remote_state ();
12018   struct trace_status *ts;
12019   int status;
12020
12021   /* Don't try to install tracepoints until we've relocated our
12022      symbols, and fetched and merged the target's tracepoint list with
12023      ours.  */
12024   if (rs->starting_up)
12025     return 0;
12026
12027   ts = current_trace_status ();
12028   status = remote_get_trace_status (self, ts);
12029
12030   if (status == -1 || !ts->running_known || !ts->running)
12031     return 0;
12032
12033   /* If we are in a tracing experiment, but remote stub doesn't support
12034      installing tracepoint in trace, we have to return.  */
12035   if (!remote_supports_install_in_trace ())
12036     return 0;
12037
12038   return 1;
12039 }
12040
12041
12042 static void
12043 remote_download_trace_state_variable (struct target_ops *self,
12044                                       struct trace_state_variable *tsv)
12045 {
12046   struct remote_state *rs = get_remote_state ();
12047   char *p;
12048
12049   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12050              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12051              tsv->builtin);
12052   p = rs->buf + strlen (rs->buf);
12053   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12054     error (_("Trace state variable name too long for tsv definition packet"));
12055   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12056   *p++ = '\0';
12057   putpkt (rs->buf);
12058   remote_get_noisy_reply (&target_buf, &target_buf_size);
12059   if (*target_buf == '\0')
12060     error (_("Target does not support this command."));
12061   if (strcmp (target_buf, "OK") != 0)
12062     error (_("Error on target while downloading trace state variable."));
12063 }
12064
12065 static void
12066 remote_enable_tracepoint (struct target_ops *self,
12067                           struct bp_location *location)
12068 {
12069   struct remote_state *rs = get_remote_state ();
12070   char addr_buf[40];
12071
12072   sprintf_vma (addr_buf, location->address);
12073   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12074              location->owner->number, addr_buf);
12075   putpkt (rs->buf);
12076   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12077   if (*rs->buf == '\0')
12078     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12079   if (strcmp (rs->buf, "OK") != 0)
12080     error (_("Error on target while enabling tracepoint."));
12081 }
12082
12083 static void
12084 remote_disable_tracepoint (struct target_ops *self,
12085                            struct bp_location *location)
12086 {
12087   struct remote_state *rs = get_remote_state ();
12088   char addr_buf[40];
12089
12090   sprintf_vma (addr_buf, location->address);
12091   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12092              location->owner->number, addr_buf);
12093   putpkt (rs->buf);
12094   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12095   if (*rs->buf == '\0')
12096     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12097   if (strcmp (rs->buf, "OK") != 0)
12098     error (_("Error on target while disabling tracepoint."));
12099 }
12100
12101 static void
12102 remote_trace_set_readonly_regions (struct target_ops *self)
12103 {
12104   asection *s;
12105   bfd *abfd = NULL;
12106   bfd_size_type size;
12107   bfd_vma vma;
12108   int anysecs = 0;
12109   int offset = 0;
12110
12111   if (!exec_bfd)
12112     return;                     /* No information to give.  */
12113
12114   strcpy (target_buf, "QTro");
12115   offset = strlen (target_buf);
12116   for (s = exec_bfd->sections; s; s = s->next)
12117     {
12118       char tmp1[40], tmp2[40];
12119       int sec_length;
12120
12121       if ((s->flags & SEC_LOAD) == 0 ||
12122       /*  (s->flags & SEC_CODE) == 0 || */
12123           (s->flags & SEC_READONLY) == 0)
12124         continue;
12125
12126       anysecs = 1;
12127       vma = bfd_get_section_vma (abfd, s);
12128       size = bfd_get_section_size (s);
12129       sprintf_vma (tmp1, vma);
12130       sprintf_vma (tmp2, vma + size);
12131       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12132       if (offset + sec_length + 1 > target_buf_size)
12133         {
12134           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12135             warning (_("\
12136 Too many sections for read-only sections definition packet."));
12137           break;
12138         }
12139       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12140                  tmp1, tmp2);
12141       offset += sec_length;
12142     }
12143   if (anysecs)
12144     {
12145       putpkt (target_buf);
12146       getpkt (&target_buf, &target_buf_size, 0);
12147     }
12148 }
12149
12150 static void
12151 remote_trace_start (struct target_ops *self)
12152 {
12153   putpkt ("QTStart");
12154   remote_get_noisy_reply (&target_buf, &target_buf_size);
12155   if (*target_buf == '\0')
12156     error (_("Target does not support this command."));
12157   if (strcmp (target_buf, "OK") != 0)
12158     error (_("Bogus reply from target: %s"), target_buf);
12159 }
12160
12161 static int
12162 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12163 {
12164   /* Initialize it just to avoid a GCC false warning.  */
12165   char *p = NULL;
12166   /* FIXME we need to get register block size some other way.  */
12167   extern int trace_regblock_size;
12168   enum packet_result result;
12169
12170   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12171     return -1;
12172
12173   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12174
12175   putpkt ("qTStatus");
12176
12177   TRY
12178     {
12179       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12180     }
12181   CATCH (ex, RETURN_MASK_ERROR)
12182     {
12183       if (ex.error != TARGET_CLOSE_ERROR)
12184         {
12185           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12186           return -1;
12187         }
12188       throw_exception (ex);
12189     }
12190   END_CATCH
12191
12192   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12193
12194   /* If the remote target doesn't do tracing, flag it.  */
12195   if (result == PACKET_UNKNOWN)
12196     return -1;
12197
12198   /* We're working with a live target.  */
12199   ts->filename = NULL;
12200
12201   if (*p++ != 'T')
12202     error (_("Bogus trace status reply from target: %s"), target_buf);
12203
12204   /* Function 'parse_trace_status' sets default value of each field of
12205      'ts' at first, so we don't have to do it here.  */
12206   parse_trace_status (p, ts);
12207
12208   return ts->running;
12209 }
12210
12211 static void
12212 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12213                               struct uploaded_tp *utp)
12214 {
12215   struct remote_state *rs = get_remote_state ();
12216   char *reply;
12217   struct bp_location *loc;
12218   struct tracepoint *tp = (struct tracepoint *) bp;
12219   size_t size = get_remote_packet_size ();
12220
12221   if (tp)
12222     {
12223       tp->base.hit_count = 0;
12224       tp->traceframe_usage = 0;
12225       for (loc = tp->base.loc; loc; loc = loc->next)
12226         {
12227           /* If the tracepoint was never downloaded, don't go asking for
12228              any status.  */
12229           if (tp->number_on_target == 0)
12230             continue;
12231           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12232                      phex_nz (loc->address, 0));
12233           putpkt (rs->buf);
12234           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12235           if (reply && *reply)
12236             {
12237               if (*reply == 'V')
12238                 parse_tracepoint_status (reply + 1, bp, utp);
12239             }
12240         }
12241     }
12242   else if (utp)
12243     {
12244       utp->hit_count = 0;
12245       utp->traceframe_usage = 0;
12246       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12247                  phex_nz (utp->addr, 0));
12248       putpkt (rs->buf);
12249       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12250       if (reply && *reply)
12251         {
12252           if (*reply == 'V')
12253             parse_tracepoint_status (reply + 1, bp, utp);
12254         }
12255     }
12256 }
12257
12258 static void
12259 remote_trace_stop (struct target_ops *self)
12260 {
12261   putpkt ("QTStop");
12262   remote_get_noisy_reply (&target_buf, &target_buf_size);
12263   if (*target_buf == '\0')
12264     error (_("Target does not support this command."));
12265   if (strcmp (target_buf, "OK") != 0)
12266     error (_("Bogus reply from target: %s"), target_buf);
12267 }
12268
12269 static int
12270 remote_trace_find (struct target_ops *self,
12271                    enum trace_find_type type, int num,
12272                    CORE_ADDR addr1, CORE_ADDR addr2,
12273                    int *tpp)
12274 {
12275   struct remote_state *rs = get_remote_state ();
12276   char *endbuf = rs->buf + get_remote_packet_size ();
12277   char *p, *reply;
12278   int target_frameno = -1, target_tracept = -1;
12279
12280   /* Lookups other than by absolute frame number depend on the current
12281      trace selected, so make sure it is correct on the remote end
12282      first.  */
12283   if (type != tfind_number)
12284     set_remote_traceframe ();
12285
12286   p = rs->buf;
12287   strcpy (p, "QTFrame:");
12288   p = strchr (p, '\0');
12289   switch (type)
12290     {
12291     case tfind_number:
12292       xsnprintf (p, endbuf - p, "%x", num);
12293       break;
12294     case tfind_pc:
12295       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12296       break;
12297     case tfind_tp:
12298       xsnprintf (p, endbuf - p, "tdp:%x", num);
12299       break;
12300     case tfind_range:
12301       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12302                  phex_nz (addr2, 0));
12303       break;
12304     case tfind_outside:
12305       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12306                  phex_nz (addr2, 0));
12307       break;
12308     default:
12309       error (_("Unknown trace find type %d"), type);
12310     }
12311
12312   putpkt (rs->buf);
12313   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12314   if (*reply == '\0')
12315     error (_("Target does not support this command."));
12316
12317   while (reply && *reply)
12318     switch (*reply)
12319       {
12320       case 'F':
12321         p = ++reply;
12322         target_frameno = (int) strtol (p, &reply, 16);
12323         if (reply == p)
12324           error (_("Unable to parse trace frame number"));
12325         /* Don't update our remote traceframe number cache on failure
12326            to select a remote traceframe.  */
12327         if (target_frameno == -1)
12328           return -1;
12329         break;
12330       case 'T':
12331         p = ++reply;
12332         target_tracept = (int) strtol (p, &reply, 16);
12333         if (reply == p)
12334           error (_("Unable to parse tracepoint number"));
12335         break;
12336       case 'O':         /* "OK"? */
12337         if (reply[1] == 'K' && reply[2] == '\0')
12338           reply += 2;
12339         else
12340           error (_("Bogus reply from target: %s"), reply);
12341         break;
12342       default:
12343         error (_("Bogus reply from target: %s"), reply);
12344       }
12345   if (tpp)
12346     *tpp = target_tracept;
12347
12348   rs->remote_traceframe_number = target_frameno;
12349   return target_frameno;
12350 }
12351
12352 static int
12353 remote_get_trace_state_variable_value (struct target_ops *self,
12354                                        int tsvnum, LONGEST *val)
12355 {
12356   struct remote_state *rs = get_remote_state ();
12357   char *reply;
12358   ULONGEST uval;
12359
12360   set_remote_traceframe ();
12361
12362   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12363   putpkt (rs->buf);
12364   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12365   if (reply && *reply)
12366     {
12367       if (*reply == 'V')
12368         {
12369           unpack_varlen_hex (reply + 1, &uval);
12370           *val = (LONGEST) uval;
12371           return 1;
12372         }
12373     }
12374   return 0;
12375 }
12376
12377 static int
12378 remote_save_trace_data (struct target_ops *self, const char *filename)
12379 {
12380   struct remote_state *rs = get_remote_state ();
12381   char *p, *reply;
12382
12383   p = rs->buf;
12384   strcpy (p, "QTSave:");
12385   p += strlen (p);
12386   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12387     error (_("Remote file name too long for trace save packet"));
12388   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12389   *p++ = '\0';
12390   putpkt (rs->buf);
12391   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12392   if (*reply == '\0')
12393     error (_("Target does not support this command."));
12394   if (strcmp (reply, "OK") != 0)
12395     error (_("Bogus reply from target: %s"), reply);
12396   return 0;
12397 }
12398
12399 /* This is basically a memory transfer, but needs to be its own packet
12400    because we don't know how the target actually organizes its trace
12401    memory, plus we want to be able to ask for as much as possible, but
12402    not be unhappy if we don't get as much as we ask for.  */
12403
12404 static LONGEST
12405 remote_get_raw_trace_data (struct target_ops *self,
12406                            gdb_byte *buf, ULONGEST offset, LONGEST len)
12407 {
12408   struct remote_state *rs = get_remote_state ();
12409   char *reply;
12410   char *p;
12411   int rslt;
12412
12413   p = rs->buf;
12414   strcpy (p, "qTBuffer:");
12415   p += strlen (p);
12416   p += hexnumstr (p, offset);
12417   *p++ = ',';
12418   p += hexnumstr (p, len);
12419   *p++ = '\0';
12420
12421   putpkt (rs->buf);
12422   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12423   if (reply && *reply)
12424     {
12425       /* 'l' by itself means we're at the end of the buffer and
12426          there is nothing more to get.  */
12427       if (*reply == 'l')
12428         return 0;
12429
12430       /* Convert the reply into binary.  Limit the number of bytes to
12431          convert according to our passed-in buffer size, rather than
12432          what was returned in the packet; if the target is
12433          unexpectedly generous and gives us a bigger reply than we
12434          asked for, we don't want to crash.  */
12435       rslt = hex2bin (target_buf, buf, len);
12436       return rslt;
12437     }
12438
12439   /* Something went wrong, flag as an error.  */
12440   return -1;
12441 }
12442
12443 static void
12444 remote_set_disconnected_tracing (struct target_ops *self, int val)
12445 {
12446   struct remote_state *rs = get_remote_state ();
12447
12448   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12449     {
12450       char *reply;
12451
12452       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12453       putpkt (rs->buf);
12454       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12455       if (*reply == '\0')
12456         error (_("Target does not support this command."));
12457       if (strcmp (reply, "OK") != 0)
12458         error (_("Bogus reply from target: %s"), reply);
12459     }
12460   else if (val)
12461     warning (_("Target does not support disconnected tracing."));
12462 }
12463
12464 static int
12465 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12466 {
12467   struct thread_info *info = find_thread_ptid (ptid);
12468
12469   if (info && info->priv)
12470     return info->priv->core;
12471   return -1;
12472 }
12473
12474 static void
12475 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12476 {
12477   struct remote_state *rs = get_remote_state ();
12478   char *reply;
12479
12480   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12481   putpkt (rs->buf);
12482   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12483   if (*reply == '\0')
12484     error (_("Target does not support this command."));
12485   if (strcmp (reply, "OK") != 0)
12486     error (_("Bogus reply from target: %s"), reply);
12487 }
12488
12489 static struct traceframe_info *
12490 remote_traceframe_info (struct target_ops *self)
12491 {
12492   char *text;
12493
12494   text = target_read_stralloc (&current_target,
12495                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12496   if (text != NULL)
12497     {
12498       struct traceframe_info *info;
12499       struct cleanup *back_to = make_cleanup (xfree, text);
12500
12501       info = parse_traceframe_info (text);
12502       do_cleanups (back_to);
12503       return info;
12504     }
12505
12506   return NULL;
12507 }
12508
12509 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
12510    instruction on which a fast tracepoint may be placed.  Returns -1
12511    if the packet is not supported, and 0 if the minimum instruction
12512    length is unknown.  */
12513
12514 static int
12515 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12516 {
12517   struct remote_state *rs = get_remote_state ();
12518   char *reply;
12519
12520   /* If we're not debugging a process yet, the IPA can't be
12521      loaded.  */
12522   if (!target_has_execution)
12523     return 0;
12524
12525   /* Make sure the remote is pointing at the right process.  */
12526   set_general_process ();
12527
12528   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12529   putpkt (rs->buf);
12530   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12531   if (*reply == '\0')
12532     return -1;
12533   else
12534     {
12535       ULONGEST min_insn_len;
12536
12537       unpack_varlen_hex (reply, &min_insn_len);
12538
12539       return (int) min_insn_len;
12540     }
12541 }
12542
12543 static void
12544 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12545 {
12546   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12547     {
12548       struct remote_state *rs = get_remote_state ();
12549       char *buf = rs->buf;
12550       char *endbuf = rs->buf + get_remote_packet_size ();
12551       enum packet_result result;
12552
12553       gdb_assert (val >= 0 || val == -1);
12554       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12555       /* Send -1 as literal "-1" to avoid host size dependency.  */
12556       if (val < 0)
12557         {
12558           *buf++ = '-';
12559           buf += hexnumstr (buf, (ULONGEST) -val);
12560         }
12561       else
12562         buf += hexnumstr (buf, (ULONGEST) val);
12563
12564       putpkt (rs->buf);
12565       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12566       result = packet_ok (rs->buf,
12567                   &remote_protocol_packets[PACKET_QTBuffer_size]);
12568
12569       if (result != PACKET_OK)
12570         warning (_("Bogus reply from target: %s"), rs->buf);
12571     }
12572 }
12573
12574 static int
12575 remote_set_trace_notes (struct target_ops *self,
12576                         const char *user, const char *notes,
12577                         const char *stop_notes)
12578 {
12579   struct remote_state *rs = get_remote_state ();
12580   char *reply;
12581   char *buf = rs->buf;
12582   char *endbuf = rs->buf + get_remote_packet_size ();
12583   int nbytes;
12584
12585   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12586   if (user)
12587     {
12588       buf += xsnprintf (buf, endbuf - buf, "user:");
12589       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12590       buf += 2 * nbytes;
12591       *buf++ = ';';
12592     }
12593   if (notes)
12594     {
12595       buf += xsnprintf (buf, endbuf - buf, "notes:");
12596       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12597       buf += 2 * nbytes;
12598       *buf++ = ';';
12599     }
12600   if (stop_notes)
12601     {
12602       buf += xsnprintf (buf, endbuf - buf, "tstop:");
12603       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12604       buf += 2 * nbytes;
12605       *buf++ = ';';
12606     }
12607   /* Ensure the buffer is terminated.  */
12608   *buf = '\0';
12609
12610   putpkt (rs->buf);
12611   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12612   if (*reply == '\0')
12613     return 0;
12614
12615   if (strcmp (reply, "OK") != 0)
12616     error (_("Bogus reply from target: %s"), reply);
12617
12618   return 1;
12619 }
12620
12621 static int
12622 remote_use_agent (struct target_ops *self, int use)
12623 {
12624   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12625     {
12626       struct remote_state *rs = get_remote_state ();
12627
12628       /* If the stub supports QAgent.  */
12629       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12630       putpkt (rs->buf);
12631       getpkt (&rs->buf, &rs->buf_size, 0);
12632
12633       if (strcmp (rs->buf, "OK") == 0)
12634         {
12635           use_agent = use;
12636           return 1;
12637         }
12638     }
12639
12640   return 0;
12641 }
12642
12643 static int
12644 remote_can_use_agent (struct target_ops *self)
12645 {
12646   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12647 }
12648
12649 struct btrace_target_info
12650 {
12651   /* The ptid of the traced thread.  */
12652   ptid_t ptid;
12653
12654   /* The obtained branch trace configuration.  */
12655   struct btrace_config conf;
12656 };
12657
12658 /* Reset our idea of our target's btrace configuration.  */
12659
12660 static void
12661 remote_btrace_reset (void)
12662 {
12663   struct remote_state *rs = get_remote_state ();
12664
12665   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12666 }
12667
12668 /* Check whether the target supports branch tracing.  */
12669
12670 static int
12671 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12672 {
12673   if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12674     return 0;
12675   if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12676     return 0;
12677
12678   switch (format)
12679     {
12680       case BTRACE_FORMAT_NONE:
12681         return 0;
12682
12683       case BTRACE_FORMAT_BTS:
12684         return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12685
12686       case BTRACE_FORMAT_PT:
12687         /* The trace is decoded on the host.  Even if our target supports it,
12688            we still need to have libipt to decode the trace.  */
12689 #if defined (HAVE_LIBIPT)
12690         return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12691 #else /* !defined (HAVE_LIBIPT)  */
12692         return 0;
12693 #endif /* !defined (HAVE_LIBIPT)  */
12694     }
12695
12696   internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12697 }
12698
12699 /* Synchronize the configuration with the target.  */
12700
12701 static void
12702 btrace_sync_conf (const struct btrace_config *conf)
12703 {
12704   struct packet_config *packet;
12705   struct remote_state *rs;
12706   char *buf, *pos, *endbuf;
12707
12708   rs = get_remote_state ();
12709   buf = rs->buf;
12710   endbuf = buf + get_remote_packet_size ();
12711
12712   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12713   if (packet_config_support (packet) == PACKET_ENABLE
12714       && conf->bts.size != rs->btrace_config.bts.size)
12715     {
12716       pos = buf;
12717       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12718                         conf->bts.size);
12719
12720       putpkt (buf);
12721       getpkt (&buf, &rs->buf_size, 0);
12722
12723       if (packet_ok (buf, packet) == PACKET_ERROR)
12724         {
12725           if (buf[0] == 'E' && buf[1] == '.')
12726             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12727           else
12728             error (_("Failed to configure the BTS buffer size."));
12729         }
12730
12731       rs->btrace_config.bts.size = conf->bts.size;
12732     }
12733
12734   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12735   if (packet_config_support (packet) == PACKET_ENABLE
12736       && conf->pt.size != rs->btrace_config.pt.size)
12737     {
12738       pos = buf;
12739       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12740                         conf->pt.size);
12741
12742       putpkt (buf);
12743       getpkt (&buf, &rs->buf_size, 0);
12744
12745       if (packet_ok (buf, packet) == PACKET_ERROR)
12746         {
12747           if (buf[0] == 'E' && buf[1] == '.')
12748             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12749           else
12750             error (_("Failed to configure the trace buffer size."));
12751         }
12752
12753       rs->btrace_config.pt.size = conf->pt.size;
12754     }
12755 }
12756
12757 /* Read the current thread's btrace configuration from the target and
12758    store it into CONF.  */
12759
12760 static void
12761 btrace_read_config (struct btrace_config *conf)
12762 {
12763   char *xml;
12764
12765   xml = target_read_stralloc (&current_target,
12766                               TARGET_OBJECT_BTRACE_CONF, "");
12767   if (xml != NULL)
12768     {
12769       struct cleanup *cleanup;
12770
12771       cleanup = make_cleanup (xfree, xml);
12772       parse_xml_btrace_conf (conf, xml);
12773       do_cleanups (cleanup);
12774     }
12775 }
12776
12777 /* Enable branch tracing.  */
12778
12779 static struct btrace_target_info *
12780 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12781                       const struct btrace_config *conf)
12782 {
12783   struct btrace_target_info *tinfo = NULL;
12784   struct packet_config *packet = NULL;
12785   struct remote_state *rs = get_remote_state ();
12786   char *buf = rs->buf;
12787   char *endbuf = rs->buf + get_remote_packet_size ();
12788
12789   switch (conf->format)
12790     {
12791       case BTRACE_FORMAT_BTS:
12792         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12793         break;
12794
12795       case BTRACE_FORMAT_PT:
12796         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12797         break;
12798     }
12799
12800   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12801     error (_("Target does not support branch tracing."));
12802
12803   btrace_sync_conf (conf);
12804
12805   set_general_thread (ptid);
12806
12807   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12808   putpkt (rs->buf);
12809   getpkt (&rs->buf, &rs->buf_size, 0);
12810
12811   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12812     {
12813       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12814         error (_("Could not enable branch tracing for %s: %s"),
12815                target_pid_to_str (ptid), rs->buf + 2);
12816       else
12817         error (_("Could not enable branch tracing for %s."),
12818                target_pid_to_str (ptid));
12819     }
12820
12821   tinfo = XCNEW (struct btrace_target_info);
12822   tinfo->ptid = ptid;
12823
12824   /* If we fail to read the configuration, we lose some information, but the
12825      tracing itself is not impacted.  */
12826   TRY
12827     {
12828       btrace_read_config (&tinfo->conf);
12829     }
12830   CATCH (err, RETURN_MASK_ERROR)
12831     {
12832       if (err.message != NULL)
12833         warning ("%s", err.message);
12834     }
12835   END_CATCH
12836
12837   return tinfo;
12838 }
12839
12840 /* Disable branch tracing.  */
12841
12842 static void
12843 remote_disable_btrace (struct target_ops *self,
12844                        struct btrace_target_info *tinfo)
12845 {
12846   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12847   struct remote_state *rs = get_remote_state ();
12848   char *buf = rs->buf;
12849   char *endbuf = rs->buf + get_remote_packet_size ();
12850
12851   if (packet_config_support (packet) != PACKET_ENABLE)
12852     error (_("Target does not support branch tracing."));
12853
12854   set_general_thread (tinfo->ptid);
12855
12856   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12857   putpkt (rs->buf);
12858   getpkt (&rs->buf, &rs->buf_size, 0);
12859
12860   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12861     {
12862       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12863         error (_("Could not disable branch tracing for %s: %s"),
12864                target_pid_to_str (tinfo->ptid), rs->buf + 2);
12865       else
12866         error (_("Could not disable branch tracing for %s."),
12867                target_pid_to_str (tinfo->ptid));
12868     }
12869
12870   xfree (tinfo);
12871 }
12872
12873 /* Teardown branch tracing.  */
12874
12875 static void
12876 remote_teardown_btrace (struct target_ops *self,
12877                         struct btrace_target_info *tinfo)
12878 {
12879   /* We must not talk to the target during teardown.  */
12880   xfree (tinfo);
12881 }
12882
12883 /* Read the branch trace.  */
12884
12885 static enum btrace_error
12886 remote_read_btrace (struct target_ops *self,
12887                     struct btrace_data *btrace,
12888                     struct btrace_target_info *tinfo,
12889                     enum btrace_read_type type)
12890 {
12891   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12892   struct cleanup *cleanup;
12893   const char *annex;
12894   char *xml;
12895
12896   if (packet_config_support (packet) != PACKET_ENABLE)
12897     error (_("Target does not support branch tracing."));
12898
12899 #if !defined(HAVE_LIBEXPAT)
12900   error (_("Cannot process branch tracing result. XML parsing not supported."));
12901 #endif
12902
12903   switch (type)
12904     {
12905     case BTRACE_READ_ALL:
12906       annex = "all";
12907       break;
12908     case BTRACE_READ_NEW:
12909       annex = "new";
12910       break;
12911     case BTRACE_READ_DELTA:
12912       annex = "delta";
12913       break;
12914     default:
12915       internal_error (__FILE__, __LINE__,
12916                       _("Bad branch tracing read type: %u."),
12917                       (unsigned int) type);
12918     }
12919
12920   xml = target_read_stralloc (&current_target,
12921                               TARGET_OBJECT_BTRACE, annex);
12922   if (xml == NULL)
12923     return BTRACE_ERR_UNKNOWN;
12924
12925   cleanup = make_cleanup (xfree, xml);
12926   parse_xml_btrace (btrace, xml);
12927   do_cleanups (cleanup);
12928
12929   return BTRACE_ERR_NONE;
12930 }
12931
12932 static const struct btrace_config *
12933 remote_btrace_conf (struct target_ops *self,
12934                     const struct btrace_target_info *tinfo)
12935 {
12936   return &tinfo->conf;
12937 }
12938
12939 static int
12940 remote_augmented_libraries_svr4_read (struct target_ops *self)
12941 {
12942   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12943           == PACKET_ENABLE);
12944 }
12945
12946 /* Implementation of to_load.  */
12947
12948 static void
12949 remote_load (struct target_ops *self, const char *name, int from_tty)
12950 {
12951   generic_load (name, from_tty);
12952 }
12953
12954 /* Accepts an integer PID; returns a string representing a file that
12955    can be opened on the remote side to get the symbols for the child
12956    process.  Returns NULL if the operation is not supported.  */
12957
12958 static char *
12959 remote_pid_to_exec_file (struct target_ops *self, int pid)
12960 {
12961   static char *filename = NULL;
12962   struct inferior *inf;
12963   char *annex = NULL;
12964
12965   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12966     return NULL;
12967
12968   if (filename != NULL)
12969     xfree (filename);
12970
12971   inf = find_inferior_pid (pid);
12972   if (inf == NULL)
12973     internal_error (__FILE__, __LINE__,
12974                     _("not currently attached to process %d"), pid);
12975
12976   if (!inf->fake_pid_p)
12977     {
12978       const int annex_size = 9;
12979
12980       annex = (char *) alloca (annex_size);
12981       xsnprintf (annex, annex_size, "%x", pid);
12982     }
12983
12984   filename = target_read_stralloc (&current_target,
12985                                    TARGET_OBJECT_EXEC_FILE, annex);
12986
12987   return filename;
12988 }
12989
12990 /* Implement the to_can_do_single_step target_ops method.  */
12991
12992 static int
12993 remote_can_do_single_step (struct target_ops *ops)
12994 {
12995   /* We can only tell whether target supports single step or not by
12996      supported s and S vCont actions if the stub supports vContSupported
12997      feature.  If the stub doesn't support vContSupported feature,
12998      we have conservatively to think target doesn't supports single
12999      step.  */
13000   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13001     {
13002       struct remote_state *rs = get_remote_state ();
13003
13004       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13005         remote_vcont_probe (rs);
13006
13007       return rs->supports_vCont.s && rs->supports_vCont.S;
13008     }
13009   else
13010     return 0;
13011 }
13012
13013 /* Implementation of the to_execution_direction method for the remote
13014    target.  */
13015
13016 static enum exec_direction_kind
13017 remote_execution_direction (struct target_ops *self)
13018 {
13019   struct remote_state *rs = get_remote_state ();
13020
13021   return rs->last_resume_exec_dir;
13022 }
13023
13024 static void
13025 init_remote_ops (void)
13026 {
13027   remote_ops.to_shortname = "remote";
13028   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13029   remote_ops.to_doc =
13030     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13031 Specify the serial device it is connected to\n\
13032 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13033   remote_ops.to_open = remote_open;
13034   remote_ops.to_close = remote_close;
13035   remote_ops.to_detach = remote_detach;
13036   remote_ops.to_disconnect = remote_disconnect;
13037   remote_ops.to_resume = remote_resume;
13038   remote_ops.to_wait = remote_wait;
13039   remote_ops.to_fetch_registers = remote_fetch_registers;
13040   remote_ops.to_store_registers = remote_store_registers;
13041   remote_ops.to_prepare_to_store = remote_prepare_to_store;
13042   remote_ops.to_files_info = remote_files_info;
13043   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13044   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13045   remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13046   remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13047   remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13048   remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13049   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13050   remote_ops.to_stopped_data_address = remote_stopped_data_address;
13051   remote_ops.to_watchpoint_addr_within_range =
13052     remote_watchpoint_addr_within_range;
13053   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13054   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13055   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13056   remote_ops.to_region_ok_for_hw_watchpoint
13057      = remote_region_ok_for_hw_watchpoint;
13058   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13059   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13060   remote_ops.to_kill = remote_kill;
13061   remote_ops.to_load = remote_load;
13062   remote_ops.to_mourn_inferior = remote_mourn;
13063   remote_ops.to_pass_signals = remote_pass_signals;
13064   remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13065   remote_ops.to_program_signals = remote_program_signals;
13066   remote_ops.to_thread_alive = remote_thread_alive;
13067   remote_ops.to_thread_name = remote_thread_name;
13068   remote_ops.to_update_thread_list = remote_update_thread_list;
13069   remote_ops.to_pid_to_str = remote_pid_to_str;
13070   remote_ops.to_extra_thread_info = remote_threads_extra_info;
13071   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13072   remote_ops.to_stop = remote_stop;
13073   remote_ops.to_interrupt = remote_interrupt;
13074   remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
13075   remote_ops.to_xfer_partial = remote_xfer_partial;
13076   remote_ops.to_rcmd = remote_rcmd;
13077   remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13078   remote_ops.to_log_command = serial_log_command;
13079   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13080   remote_ops.to_stratum = process_stratum;
13081   remote_ops.to_has_all_memory = default_child_has_all_memory;
13082   remote_ops.to_has_memory = default_child_has_memory;
13083   remote_ops.to_has_stack = default_child_has_stack;
13084   remote_ops.to_has_registers = default_child_has_registers;
13085   remote_ops.to_has_execution = default_child_has_execution;
13086   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
13087   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13088   remote_ops.to_magic = OPS_MAGIC;
13089   remote_ops.to_memory_map = remote_memory_map;
13090   remote_ops.to_flash_erase = remote_flash_erase;
13091   remote_ops.to_flash_done = remote_flash_done;
13092   remote_ops.to_read_description = remote_read_description;
13093   remote_ops.to_search_memory = remote_search_memory;
13094   remote_ops.to_can_async_p = remote_can_async_p;
13095   remote_ops.to_is_async_p = remote_is_async_p;
13096   remote_ops.to_async = remote_async;
13097   remote_ops.to_thread_events = remote_thread_events;
13098   remote_ops.to_can_do_single_step = remote_can_do_single_step;
13099   remote_ops.to_terminal_inferior = remote_terminal_inferior;
13100   remote_ops.to_terminal_ours = remote_terminal_ours;
13101   remote_ops.to_supports_non_stop = remote_supports_non_stop;
13102   remote_ops.to_supports_multi_process = remote_supports_multi_process;
13103   remote_ops.to_supports_disable_randomization
13104     = remote_supports_disable_randomization;
13105   remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13106   remote_ops.to_fileio_open = remote_hostio_open;
13107   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13108   remote_ops.to_fileio_pread = remote_hostio_pread;
13109   remote_ops.to_fileio_fstat = remote_hostio_fstat;
13110   remote_ops.to_fileio_close = remote_hostio_close;
13111   remote_ops.to_fileio_unlink = remote_hostio_unlink;
13112   remote_ops.to_fileio_readlink = remote_hostio_readlink;
13113   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13114   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13115   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13116   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13117   remote_ops.to_trace_init = remote_trace_init;
13118   remote_ops.to_download_tracepoint = remote_download_tracepoint;
13119   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13120   remote_ops.to_download_trace_state_variable
13121     = remote_download_trace_state_variable;
13122   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13123   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13124   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13125   remote_ops.to_trace_start = remote_trace_start;
13126   remote_ops.to_get_trace_status = remote_get_trace_status;
13127   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13128   remote_ops.to_trace_stop = remote_trace_stop;
13129   remote_ops.to_trace_find = remote_trace_find;
13130   remote_ops.to_get_trace_state_variable_value
13131     = remote_get_trace_state_variable_value;
13132   remote_ops.to_save_trace_data = remote_save_trace_data;
13133   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13134   remote_ops.to_upload_trace_state_variables
13135     = remote_upload_trace_state_variables;
13136   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13137   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13138   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13139   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13140   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13141   remote_ops.to_set_trace_notes = remote_set_trace_notes;
13142   remote_ops.to_core_of_thread = remote_core_of_thread;
13143   remote_ops.to_verify_memory = remote_verify_memory;
13144   remote_ops.to_get_tib_address = remote_get_tib_address;
13145   remote_ops.to_set_permissions = remote_set_permissions;
13146   remote_ops.to_static_tracepoint_marker_at
13147     = remote_static_tracepoint_marker_at;
13148   remote_ops.to_static_tracepoint_markers_by_strid
13149     = remote_static_tracepoint_markers_by_strid;
13150   remote_ops.to_traceframe_info = remote_traceframe_info;
13151   remote_ops.to_use_agent = remote_use_agent;
13152   remote_ops.to_can_use_agent = remote_can_use_agent;
13153   remote_ops.to_supports_btrace = remote_supports_btrace;
13154   remote_ops.to_enable_btrace = remote_enable_btrace;
13155   remote_ops.to_disable_btrace = remote_disable_btrace;
13156   remote_ops.to_teardown_btrace = remote_teardown_btrace;
13157   remote_ops.to_read_btrace = remote_read_btrace;
13158   remote_ops.to_btrace_conf = remote_btrace_conf;
13159   remote_ops.to_augmented_libraries_svr4_read =
13160     remote_augmented_libraries_svr4_read;
13161   remote_ops.to_follow_fork = remote_follow_fork;
13162   remote_ops.to_follow_exec = remote_follow_exec;
13163   remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13164   remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13165   remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13166   remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13167   remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13168   remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13169   remote_ops.to_execution_direction = remote_execution_direction;
13170 }
13171
13172 /* Set up the extended remote vector by making a copy of the standard
13173    remote vector and adding to it.  */
13174
13175 static void
13176 init_extended_remote_ops (void)
13177 {
13178   extended_remote_ops = remote_ops;
13179
13180   extended_remote_ops.to_shortname = "extended-remote";
13181   extended_remote_ops.to_longname =
13182     "Extended remote serial target in gdb-specific protocol";
13183   extended_remote_ops.to_doc =
13184     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13185 Specify the serial device it is connected to (e.g. /dev/ttya).";
13186   extended_remote_ops.to_open = extended_remote_open;
13187   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13188   extended_remote_ops.to_detach = extended_remote_detach;
13189   extended_remote_ops.to_attach = extended_remote_attach;
13190   extended_remote_ops.to_post_attach = extended_remote_post_attach;
13191   extended_remote_ops.to_supports_disable_randomization
13192     = extended_remote_supports_disable_randomization;
13193 }
13194
13195 static int
13196 remote_can_async_p (struct target_ops *ops)
13197 {
13198   struct remote_state *rs = get_remote_state ();
13199
13200   if (!target_async_permitted)
13201     /* We only enable async when the user specifically asks for it.  */
13202     return 0;
13203
13204   /* We're async whenever the serial device is.  */
13205   return serial_can_async_p (rs->remote_desc);
13206 }
13207
13208 static int
13209 remote_is_async_p (struct target_ops *ops)
13210 {
13211   struct remote_state *rs = get_remote_state ();
13212
13213   if (!target_async_permitted)
13214     /* We only enable async when the user specifically asks for it.  */
13215     return 0;
13216
13217   /* We're async whenever the serial device is.  */
13218   return serial_is_async_p (rs->remote_desc);
13219 }
13220
13221 /* Pass the SERIAL event on and up to the client.  One day this code
13222    will be able to delay notifying the client of an event until the
13223    point where an entire packet has been received.  */
13224
13225 static serial_event_ftype remote_async_serial_handler;
13226
13227 static void
13228 remote_async_serial_handler (struct serial *scb, void *context)
13229 {
13230   /* Don't propogate error information up to the client.  Instead let
13231      the client find out about the error by querying the target.  */
13232   inferior_event_handler (INF_REG_EVENT, NULL);
13233 }
13234
13235 static void
13236 remote_async_inferior_event_handler (gdb_client_data data)
13237 {
13238   inferior_event_handler (INF_REG_EVENT, NULL);
13239 }
13240
13241 static void
13242 remote_async (struct target_ops *ops, int enable)
13243 {
13244   struct remote_state *rs = get_remote_state ();
13245
13246   if (enable)
13247     {
13248       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13249
13250       /* If there are pending events in the stop reply queue tell the
13251          event loop to process them.  */
13252       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13253         mark_async_event_handler (remote_async_inferior_event_token);
13254       /* For simplicity, below we clear the pending events token
13255          without remembering whether it is marked, so here we always
13256          mark it.  If there's actually no pending notification to
13257          process, this ends up being a no-op (other than a spurious
13258          event-loop wakeup).  */
13259       if (target_is_non_stop_p ())
13260         mark_async_event_handler (rs->notif_state->get_pending_events_token);
13261     }
13262   else
13263     {
13264       serial_async (rs->remote_desc, NULL, NULL);
13265       /* If the core is disabling async, it doesn't want to be
13266          disturbed with target events.  Clear all async event sources
13267          too.  */
13268       clear_async_event_handler (remote_async_inferior_event_token);
13269       if (target_is_non_stop_p ())
13270         clear_async_event_handler (rs->notif_state->get_pending_events_token);
13271     }
13272 }
13273
13274 /* Implementation of the to_thread_events method.  */
13275
13276 static void
13277 remote_thread_events (struct target_ops *ops, int enable)
13278 {
13279   struct remote_state *rs = get_remote_state ();
13280   size_t size = get_remote_packet_size ();
13281
13282   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13283     return;
13284
13285   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13286   putpkt (rs->buf);
13287   getpkt (&rs->buf, &rs->buf_size, 0);
13288
13289   switch (packet_ok (rs->buf,
13290                      &remote_protocol_packets[PACKET_QThreadEvents]))
13291     {
13292     case PACKET_OK:
13293       if (strcmp (rs->buf, "OK") != 0)
13294         error (_("Remote refused setting thread events: %s"), rs->buf);
13295       break;
13296     case PACKET_ERROR:
13297       warning (_("Remote failure reply: %s"), rs->buf);
13298       break;
13299     case PACKET_UNKNOWN:
13300       break;
13301     }
13302 }
13303
13304 static void
13305 set_remote_cmd (char *args, int from_tty)
13306 {
13307   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13308 }
13309
13310 static void
13311 show_remote_cmd (char *args, int from_tty)
13312 {
13313   /* We can't just use cmd_show_list here, because we want to skip
13314      the redundant "show remote Z-packet" and the legacy aliases.  */
13315   struct cleanup *showlist_chain;
13316   struct cmd_list_element *list = remote_show_cmdlist;
13317   struct ui_out *uiout = current_uiout;
13318
13319   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13320   for (; list != NULL; list = list->next)
13321     if (strcmp (list->name, "Z-packet") == 0)
13322       continue;
13323     else if (list->type == not_set_cmd)
13324       /* Alias commands are exactly like the original, except they
13325          don't have the normal type.  */
13326       continue;
13327     else
13328       {
13329         struct cleanup *option_chain
13330           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13331
13332         ui_out_field_string (uiout, "name", list->name);
13333         ui_out_text (uiout, ":  ");
13334         if (list->type == show_cmd)
13335           do_show_command ((char *) NULL, from_tty, list);
13336         else
13337           cmd_func (list, NULL, from_tty);
13338         /* Close the tuple.  */
13339         do_cleanups (option_chain);
13340       }
13341
13342   /* Close the tuple.  */
13343   do_cleanups (showlist_chain);
13344 }
13345
13346
13347 /* Function to be called whenever a new objfile (shlib) is detected.  */
13348 static void
13349 remote_new_objfile (struct objfile *objfile)
13350 {
13351   struct remote_state *rs = get_remote_state ();
13352
13353   if (rs->remote_desc != 0)             /* Have a remote connection.  */
13354     remote_check_symbols ();
13355 }
13356
13357 /* Pull all the tracepoints defined on the target and create local
13358    data structures representing them.  We don't want to create real
13359    tracepoints yet, we don't want to mess up the user's existing
13360    collection.  */
13361   
13362 static int
13363 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13364 {
13365   struct remote_state *rs = get_remote_state ();
13366   char *p;
13367
13368   /* Ask for a first packet of tracepoint definition.  */
13369   putpkt ("qTfP");
13370   getpkt (&rs->buf, &rs->buf_size, 0);
13371   p = rs->buf;
13372   while (*p && *p != 'l')
13373     {
13374       parse_tracepoint_definition (p, utpp);
13375       /* Ask for another packet of tracepoint definition.  */
13376       putpkt ("qTsP");
13377       getpkt (&rs->buf, &rs->buf_size, 0);
13378       p = rs->buf;
13379     }
13380   return 0;
13381 }
13382
13383 static int
13384 remote_upload_trace_state_variables (struct target_ops *self,
13385                                      struct uploaded_tsv **utsvp)
13386 {
13387   struct remote_state *rs = get_remote_state ();
13388   char *p;
13389
13390   /* Ask for a first packet of variable definition.  */
13391   putpkt ("qTfV");
13392   getpkt (&rs->buf, &rs->buf_size, 0);
13393   p = rs->buf;
13394   while (*p && *p != 'l')
13395     {
13396       parse_tsv_definition (p, utsvp);
13397       /* Ask for another packet of variable definition.  */
13398       putpkt ("qTsV");
13399       getpkt (&rs->buf, &rs->buf_size, 0);
13400       p = rs->buf;
13401     }
13402   return 0;
13403 }
13404
13405 /* The "set/show range-stepping" show hook.  */
13406
13407 static void
13408 show_range_stepping (struct ui_file *file, int from_tty,
13409                      struct cmd_list_element *c,
13410                      const char *value)
13411 {
13412   fprintf_filtered (file,
13413                     _("Debugger's willingness to use range stepping "
13414                       "is %s.\n"), value);
13415 }
13416
13417 /* The "set/show range-stepping" set hook.  */
13418
13419 static void
13420 set_range_stepping (char *ignore_args, int from_tty,
13421                     struct cmd_list_element *c)
13422 {
13423   struct remote_state *rs = get_remote_state ();
13424
13425   /* Whene enabling, check whether range stepping is actually
13426      supported by the target, and warn if not.  */
13427   if (use_range_stepping)
13428     {
13429       if (rs->remote_desc != NULL)
13430         {
13431           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13432             remote_vcont_probe (rs);
13433
13434           if (packet_support (PACKET_vCont) == PACKET_ENABLE
13435               && rs->supports_vCont.r)
13436             return;
13437         }
13438
13439       warning (_("Range stepping is not supported by the current target"));
13440     }
13441 }
13442
13443 void
13444 _initialize_remote (void)
13445 {
13446   struct cmd_list_element *cmd;
13447   const char *cmd_name;
13448
13449   /* architecture specific data */
13450   remote_gdbarch_data_handle =
13451     gdbarch_data_register_post_init (init_remote_state);
13452   remote_g_packet_data_handle =
13453     gdbarch_data_register_pre_init (remote_g_packet_data_init);
13454
13455   remote_pspace_data
13456     = register_program_space_data_with_cleanup (NULL,
13457                                                 remote_pspace_data_cleanup);
13458
13459   /* Initialize the per-target state.  At the moment there is only one
13460      of these, not one per target.  Only one target is active at a
13461      time.  */
13462   remote_state = new_remote_state ();
13463
13464   init_remote_ops ();
13465   add_target (&remote_ops);
13466
13467   init_extended_remote_ops ();
13468   add_target (&extended_remote_ops);
13469
13470   /* Hook into new objfile notification.  */
13471   observer_attach_new_objfile (remote_new_objfile);
13472   /* We're no longer interested in notification events of an inferior
13473      when it exits.  */
13474   observer_attach_inferior_exit (discard_pending_stop_replies);
13475
13476 #if 0
13477   init_remote_threadtests ();
13478 #endif
13479
13480   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13481   /* set/show remote ...  */
13482
13483   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13484 Remote protocol specific variables\n\
13485 Configure various remote-protocol specific variables such as\n\
13486 the packets being used"),
13487                   &remote_set_cmdlist, "set remote ",
13488                   0 /* allow-unknown */, &setlist);
13489   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13490 Remote protocol specific variables\n\
13491 Configure various remote-protocol specific variables such as\n\
13492 the packets being used"),
13493                   &remote_show_cmdlist, "show remote ",
13494                   0 /* allow-unknown */, &showlist);
13495
13496   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13497 Compare section data on target to the exec file.\n\
13498 Argument is a single section name (default: all loaded sections).\n\
13499 To compare only read-only loaded sections, specify the -r option."),
13500            &cmdlist);
13501
13502   add_cmd ("packet", class_maintenance, packet_command, _("\
13503 Send an arbitrary packet to a remote target.\n\
13504    maintenance packet TEXT\n\
13505 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13506 this command sends the string TEXT to the inferior, and displays the\n\
13507 response packet.  GDB supplies the initial `$' character, and the\n\
13508 terminating `#' character and checksum."),
13509            &maintenancelist);
13510
13511   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13512 Set whether to send break if interrupted."), _("\
13513 Show whether to send break if interrupted."), _("\
13514 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13515                            set_remotebreak, show_remotebreak,
13516                            &setlist, &showlist);
13517   cmd_name = "remotebreak";
13518   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13519   deprecate_cmd (cmd, "set remote interrupt-sequence");
13520   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13521   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13522   deprecate_cmd (cmd, "show remote interrupt-sequence");
13523
13524   add_setshow_enum_cmd ("interrupt-sequence", class_support,
13525                         interrupt_sequence_modes, &interrupt_sequence_mode,
13526                         _("\
13527 Set interrupt sequence to remote target."), _("\
13528 Show interrupt sequence to remote target."), _("\
13529 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13530                         NULL, show_interrupt_sequence,
13531                         &remote_set_cmdlist,
13532                         &remote_show_cmdlist);
13533
13534   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13535                            &interrupt_on_connect, _("\
13536 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
13537 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
13538 If set, interrupt sequence is sent to remote target."),
13539                            NULL, NULL,
13540                            &remote_set_cmdlist, &remote_show_cmdlist);
13541
13542   /* Install commands for configuring memory read/write packets.  */
13543
13544   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13545 Set the maximum number of bytes per memory write packet (deprecated)."),
13546            &setlist);
13547   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13548 Show the maximum number of bytes per memory write packet (deprecated)."),
13549            &showlist);
13550   add_cmd ("memory-write-packet-size", no_class,
13551            set_memory_write_packet_size, _("\
13552 Set the maximum number of bytes per memory-write packet.\n\
13553 Specify the number of bytes in a packet or 0 (zero) for the\n\
13554 default packet size.  The actual limit is further reduced\n\
13555 dependent on the target.  Specify ``fixed'' to disable the\n\
13556 further restriction and ``limit'' to enable that restriction."),
13557            &remote_set_cmdlist);
13558   add_cmd ("memory-read-packet-size", no_class,
13559            set_memory_read_packet_size, _("\
13560 Set the maximum number of bytes per memory-read packet.\n\
13561 Specify the number of bytes in a packet or 0 (zero) for the\n\
13562 default packet size.  The actual limit is further reduced\n\
13563 dependent on the target.  Specify ``fixed'' to disable the\n\
13564 further restriction and ``limit'' to enable that restriction."),
13565            &remote_set_cmdlist);
13566   add_cmd ("memory-write-packet-size", no_class,
13567            show_memory_write_packet_size,
13568            _("Show the maximum number of bytes per memory-write packet."),
13569            &remote_show_cmdlist);
13570   add_cmd ("memory-read-packet-size", no_class,
13571            show_memory_read_packet_size,
13572            _("Show the maximum number of bytes per memory-read packet."),
13573            &remote_show_cmdlist);
13574
13575   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13576                             &remote_hw_watchpoint_limit, _("\
13577 Set the maximum number of target hardware watchpoints."), _("\
13578 Show the maximum number of target hardware watchpoints."), _("\
13579 Specify a negative limit for unlimited."),
13580                             NULL, NULL, /* FIXME: i18n: The maximum
13581                                            number of target hardware
13582                                            watchpoints is %s.  */
13583                             &remote_set_cmdlist, &remote_show_cmdlist);
13584   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13585                             &remote_hw_watchpoint_length_limit, _("\
13586 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13587 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13588 Specify a negative limit for unlimited."),
13589                             NULL, NULL, /* FIXME: i18n: The maximum
13590                                            length (in bytes) of a target
13591                                            hardware watchpoint is %s.  */
13592                             &remote_set_cmdlist, &remote_show_cmdlist);
13593   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13594                             &remote_hw_breakpoint_limit, _("\
13595 Set the maximum number of target hardware breakpoints."), _("\
13596 Show the maximum number of target hardware breakpoints."), _("\
13597 Specify a negative limit for unlimited."),
13598                             NULL, NULL, /* FIXME: i18n: The maximum
13599                                            number of target hardware
13600                                            breakpoints is %s.  */
13601                             &remote_set_cmdlist, &remote_show_cmdlist);
13602
13603   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13604                              &remote_address_size, _("\
13605 Set the maximum size of the address (in bits) in a memory packet."), _("\
13606 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13607                              NULL,
13608                              NULL, /* FIXME: i18n: */
13609                              &setlist, &showlist);
13610
13611   init_all_packet_configs ();
13612
13613   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13614                          "X", "binary-download", 1);
13615
13616   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13617                          "vCont", "verbose-resume", 0);
13618
13619   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13620                          "QPassSignals", "pass-signals", 0);
13621
13622   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13623                          "QCatchSyscalls", "catch-syscalls", 0);
13624
13625   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13626                          "QProgramSignals", "program-signals", 0);
13627
13628   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13629                          "qSymbol", "symbol-lookup", 0);
13630
13631   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13632                          "P", "set-register", 1);
13633
13634   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13635                          "p", "fetch-register", 1);
13636
13637   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13638                          "Z0", "software-breakpoint", 0);
13639
13640   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13641                          "Z1", "hardware-breakpoint", 0);
13642
13643   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13644                          "Z2", "write-watchpoint", 0);
13645
13646   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13647                          "Z3", "read-watchpoint", 0);
13648
13649   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13650                          "Z4", "access-watchpoint", 0);
13651
13652   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13653                          "qXfer:auxv:read", "read-aux-vector", 0);
13654
13655   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13656                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
13657
13658   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13659                          "qXfer:features:read", "target-features", 0);
13660
13661   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13662                          "qXfer:libraries:read", "library-info", 0);
13663
13664   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13665                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13666
13667   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13668                          "qXfer:memory-map:read", "memory-map", 0);
13669
13670   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13671                          "qXfer:spu:read", "read-spu-object", 0);
13672
13673   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13674                          "qXfer:spu:write", "write-spu-object", 0);
13675
13676   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13677                         "qXfer:osdata:read", "osdata", 0);
13678
13679   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13680                          "qXfer:threads:read", "threads", 0);
13681
13682   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13683                          "qXfer:siginfo:read", "read-siginfo-object", 0);
13684
13685   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13686                          "qXfer:siginfo:write", "write-siginfo-object", 0);
13687
13688   add_packet_config_cmd
13689     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13690      "qXfer:traceframe-info:read", "traceframe-info", 0);
13691
13692   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13693                          "qXfer:uib:read", "unwind-info-block", 0);
13694
13695   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13696                          "qGetTLSAddr", "get-thread-local-storage-address",
13697                          0);
13698
13699   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13700                          "qGetTIBAddr", "get-thread-information-block-address",
13701                          0);
13702
13703   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13704                          "bc", "reverse-continue", 0);
13705
13706   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13707                          "bs", "reverse-step", 0);
13708
13709   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13710                          "qSupported", "supported-packets", 0);
13711
13712   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13713                          "qSearch:memory", "search-memory", 0);
13714
13715   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13716                          "qTStatus", "trace-status", 0);
13717
13718   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13719                          "vFile:setfs", "hostio-setfs", 0);
13720
13721   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13722                          "vFile:open", "hostio-open", 0);
13723
13724   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13725                          "vFile:pread", "hostio-pread", 0);
13726
13727   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13728                          "vFile:pwrite", "hostio-pwrite", 0);
13729
13730   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13731                          "vFile:close", "hostio-close", 0);
13732
13733   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13734                          "vFile:unlink", "hostio-unlink", 0);
13735
13736   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13737                          "vFile:readlink", "hostio-readlink", 0);
13738
13739   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13740                          "vFile:fstat", "hostio-fstat", 0);
13741
13742   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13743                          "vAttach", "attach", 0);
13744
13745   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13746                          "vRun", "run", 0);
13747
13748   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13749                          "QStartNoAckMode", "noack", 0);
13750
13751   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13752                          "vKill", "kill", 0);
13753
13754   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13755                          "qAttached", "query-attached", 0);
13756
13757   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13758                          "ConditionalTracepoints",
13759                          "conditional-tracepoints", 0);
13760
13761   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13762                          "ConditionalBreakpoints",
13763                          "conditional-breakpoints", 0);
13764
13765   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13766                          "BreakpointCommands",
13767                          "breakpoint-commands", 0);
13768
13769   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13770                          "FastTracepoints", "fast-tracepoints", 0);
13771
13772   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13773                          "TracepointSource", "TracepointSource", 0);
13774
13775   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13776                          "QAllow", "allow", 0);
13777
13778   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13779                          "StaticTracepoints", "static-tracepoints", 0);
13780
13781   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13782                          "InstallInTrace", "install-in-trace", 0);
13783
13784   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13785                          "qXfer:statictrace:read", "read-sdata-object", 0);
13786
13787   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13788                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13789
13790   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13791                          "QDisableRandomization", "disable-randomization", 0);
13792
13793   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13794                          "QAgent", "agent", 0);
13795
13796   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13797                          "QTBuffer:size", "trace-buffer-size", 0);
13798
13799   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13800        "Qbtrace:off", "disable-btrace", 0);
13801
13802   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13803        "Qbtrace:bts", "enable-btrace-bts", 0);
13804
13805   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13806        "Qbtrace:pt", "enable-btrace-pt", 0);
13807
13808   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13809        "qXfer:btrace", "read-btrace", 0);
13810
13811   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13812        "qXfer:btrace-conf", "read-btrace-conf", 0);
13813
13814   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13815        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13816
13817   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13818        "multiprocess-feature", "multiprocess-feature", 0);
13819
13820   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13821                          "swbreak-feature", "swbreak-feature", 0);
13822
13823   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13824                          "hwbreak-feature", "hwbreak-feature", 0);
13825
13826   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13827                          "fork-event-feature", "fork-event-feature", 0);
13828
13829   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13830                          "vfork-event-feature", "vfork-event-feature", 0);
13831
13832   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13833        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13834
13835   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13836                          "vContSupported", "verbose-resume-supported", 0);
13837
13838   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13839                          "exec-event-feature", "exec-event-feature", 0);
13840
13841   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13842                          "vCtrlC", "ctrl-c", 0);
13843
13844   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13845                          "QThreadEvents", "thread-events", 0);
13846
13847   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13848                          "N stop reply", "no-resumed-stop-reply", 0);
13849
13850   /* Assert that we've registered "set remote foo-packet" commands
13851      for all packet configs.  */
13852   {
13853     int i;
13854
13855     for (i = 0; i < PACKET_MAX; i++)
13856       {
13857         /* Ideally all configs would have a command associated.  Some
13858            still don't though.  */
13859         int excepted;
13860
13861         switch (i)
13862           {
13863           case PACKET_QNonStop:
13864           case PACKET_EnableDisableTracepoints_feature:
13865           case PACKET_tracenz_feature:
13866           case PACKET_DisconnectedTracing_feature:
13867           case PACKET_augmented_libraries_svr4_read_feature:
13868           case PACKET_qCRC:
13869             /* Additions to this list need to be well justified:
13870                pre-existing packets are OK; new packets are not.  */
13871             excepted = 1;
13872             break;
13873           default:
13874             excepted = 0;
13875             break;
13876           }
13877
13878         /* This catches both forgetting to add a config command, and
13879            forgetting to remove a packet from the exception list.  */
13880         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13881       }
13882   }
13883
13884   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
13885      Z sub-packet has its own set and show commands, but users may
13886      have sets to this variable in their .gdbinit files (or in their
13887      documentation).  */
13888   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13889                                 &remote_Z_packet_detect, _("\
13890 Set use of remote protocol `Z' packets"), _("\
13891 Show use of remote protocol `Z' packets "), _("\
13892 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13893 packets."),
13894                                 set_remote_protocol_Z_packet_cmd,
13895                                 show_remote_protocol_Z_packet_cmd,
13896                                 /* FIXME: i18n: Use of remote protocol
13897                                    `Z' packets is %s.  */
13898                                 &remote_set_cmdlist, &remote_show_cmdlist);
13899
13900   add_prefix_cmd ("remote", class_files, remote_command, _("\
13901 Manipulate files on the remote system\n\
13902 Transfer files to and from the remote target system."),
13903                   &remote_cmdlist, "remote ",
13904                   0 /* allow-unknown */, &cmdlist);
13905
13906   add_cmd ("put", class_files, remote_put_command,
13907            _("Copy a local file to the remote system."),
13908            &remote_cmdlist);
13909
13910   add_cmd ("get", class_files, remote_get_command,
13911            _("Copy a remote file to the local system."),
13912            &remote_cmdlist);
13913
13914   add_cmd ("delete", class_files, remote_delete_command,
13915            _("Delete a remote file."),
13916            &remote_cmdlist);
13917
13918   add_setshow_string_noescape_cmd ("exec-file", class_files,
13919                                    &remote_exec_file_var, _("\
13920 Set the remote pathname for \"run\""), _("\
13921 Show the remote pathname for \"run\""), NULL,
13922                                    set_remote_exec_file,
13923                                    show_remote_exec_file,
13924                                    &remote_set_cmdlist,
13925                                    &remote_show_cmdlist);
13926
13927   add_setshow_boolean_cmd ("range-stepping", class_run,
13928                            &use_range_stepping, _("\
13929 Enable or disable range stepping."), _("\
13930 Show whether target-assisted range stepping is enabled."), _("\
13931 If on, and the target supports it, when stepping a source line, GDB\n\
13932 tells the target to step the corresponding range of addresses itself instead\n\
13933 of issuing multiple single-steps.  This speeds up source level\n\
13934 stepping.  If off, GDB always issues single-steps, even if range\n\
13935 stepping is supported by the target.  The default is on."),
13936                            set_range_stepping,
13937                            show_range_stepping,
13938                            &setlist,
13939                            &showlist);
13940
13941   /* Eventually initialize fileio.  See fileio.c */
13942   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13943
13944   /* Take advantage of the fact that the TID field is not used, to tag
13945      special ptids with it set to != 0.  */
13946   magic_null_ptid = ptid_build (42000, -1, 1);
13947   not_sent_ptid = ptid_build (42000, -2, 1);
13948   any_thread_ptid = ptid_build (42000, 0, 1);
13949
13950   target_buf_size = 2048;
13951   target_buf = (char *) xmalloc (target_buf_size);
13952 }
13953