Check for truncated registers in process_g_packet
[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 #include "record-btrace.h"
74 #include <algorithm>
75
76 /* Temp hacks for tracepoint encoding migration.  */
77 static char *target_buf;
78 static long target_buf_size;
79
80 /* Per-program-space data key.  */
81 static const struct program_space_data *remote_pspace_data;
82
83 /* The variable registered as the control variable used by the
84    remote exec-file commands.  While the remote exec-file setting is
85    per-program-space, the set/show machinery uses this as the 
86    location of the remote exec-file value.  */
87 static char *remote_exec_file_var;
88
89 /* The size to align memory write packets, when practical.  The protocol
90    does not guarantee any alignment, and gdb will generate short
91    writes and unaligned writes, but even as a best-effort attempt this
92    can improve bulk transfers.  For instance, if a write is misaligned
93    relative to the target's data bus, the stub may need to make an extra
94    round trip fetching data from the target.  This doesn't make a
95    huge difference, but it's easy to do, so we try to be helpful.
96
97    The alignment chosen is arbitrary; usually data bus width is
98    important here, not the possibly larger cache line size.  */
99 enum { REMOTE_ALIGN_WRITES = 16 };
100
101 /* Prototypes for local functions.  */
102 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
103 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
104                                  int forever, int *is_notif);
105
106 static void remote_files_info (struct target_ops *ignore);
107
108 static void remote_prepare_to_store (struct target_ops *self,
109                                      struct regcache *regcache);
110
111 static void remote_open_1 (const char *, int, struct target_ops *,
112                            int extended_p);
113
114 static void remote_close (struct target_ops *self);
115
116 struct remote_state;
117
118 static int remote_vkill (int pid, struct remote_state *rs);
119
120 static void remote_kill_k (void);
121
122 static void remote_mourn (struct target_ops *ops);
123
124 static void extended_remote_restart (void);
125
126 static void remote_send (char **buf, long *sizeof_buf_p);
127
128 static int readchar (int timeout);
129
130 static void remote_serial_write (const char *str, int len);
131
132 static void remote_kill (struct target_ops *ops);
133
134 static int remote_can_async_p (struct target_ops *);
135
136 static int remote_is_async_p (struct target_ops *);
137
138 static void remote_async (struct target_ops *ops, int enable);
139
140 static void remote_thread_events (struct target_ops *ops, int enable);
141
142 static void interrupt_query (void);
143
144 static void set_general_thread (struct ptid ptid);
145 static void set_continue_thread (struct ptid ptid);
146
147 static void get_offsets (void);
148
149 static void skip_frame (void);
150
151 static long read_frame (char **buf_p, long *sizeof_buf);
152
153 static int hexnumlen (ULONGEST num);
154
155 static void init_remote_ops (void);
156
157 static void init_extended_remote_ops (void);
158
159 static void remote_stop (struct target_ops *self, ptid_t);
160
161 static int stubhex (int ch);
162
163 static int hexnumstr (char *, ULONGEST);
164
165 static int hexnumnstr (char *, ULONGEST, int);
166
167 static CORE_ADDR remote_address_masked (CORE_ADDR);
168
169 static void print_packet (const char *);
170
171 static void compare_sections_command (char *, int);
172
173 static void packet_command (char *, int);
174
175 static int stub_unpack_int (char *buff, int fieldlength);
176
177 static ptid_t remote_current_thread (ptid_t oldptid);
178
179 static int putpkt_binary (const char *buf, int cnt);
180
181 static void check_binary_download (CORE_ADDR addr);
182
183 struct packet_config;
184
185 static void show_packet_config_cmd (struct packet_config *config);
186
187 static void show_remote_protocol_packet_cmd (struct ui_file *file,
188                                              int from_tty,
189                                              struct cmd_list_element *c,
190                                              const char *value);
191
192 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
193 static ptid_t read_ptid (char *buf, char **obuf);
194
195 static void remote_set_permissions (struct target_ops *self);
196
197 static int remote_get_trace_status (struct target_ops *self,
198                                     struct trace_status *ts);
199
200 static int remote_upload_tracepoints (struct target_ops *self,
201                                       struct uploaded_tp **utpp);
202
203 static int remote_upload_trace_state_variables (struct target_ops *self,
204                                                 struct uploaded_tsv **utsvp);
205   
206 static void remote_query_supported (void);
207
208 static void remote_check_symbols (void);
209
210 void _initialize_remote (void);
211
212 struct stop_reply;
213 static void stop_reply_xfree (struct stop_reply *);
214 static void remote_parse_stop_reply (char *, struct stop_reply *);
215 static void push_stop_reply (struct stop_reply *);
216 static void discard_pending_stop_replies_in_queue (struct remote_state *);
217 static int peek_stop_reply (ptid_t ptid);
218
219 struct threads_listing_context;
220 static void remove_new_fork_children (struct threads_listing_context *);
221
222 static void remote_async_inferior_event_handler (gdb_client_data);
223
224 static void remote_terminal_ours (struct target_ops *self);
225
226 static int remote_read_description_p (struct target_ops *target);
227
228 static void remote_console_output (char *msg);
229
230 static int remote_supports_cond_breakpoints (struct target_ops *self);
231
232 static int remote_can_run_breakpoint_commands (struct target_ops *self);
233
234 static void remote_btrace_reset (void);
235
236 static void remote_btrace_maybe_reopen (void);
237
238 static int stop_reply_queue_length (void);
239
240 static void readahead_cache_invalidate (void);
241
242 static void remote_unpush_and_throw (void);
243
244 /* For "remote".  */
245
246 static struct cmd_list_element *remote_cmdlist;
247
248 /* For "set remote" and "show remote".  */
249
250 static struct cmd_list_element *remote_set_cmdlist;
251 static struct cmd_list_element *remote_show_cmdlist;
252
253 /* Stub vCont actions support.
254
255    Each field is a boolean flag indicating whether the stub reports
256    support for the corresponding action.  */
257
258 struct vCont_action_support
259 {
260   /* vCont;t */
261   int t;
262
263   /* vCont;r */
264   int r;
265
266   /* vCont;s */
267   int s;
268
269   /* vCont;S */
270   int S;
271 };
272
273 /* Controls whether GDB is willing to use range stepping.  */
274
275 static int use_range_stepping = 1;
276
277 #define OPAQUETHREADBYTES 8
278
279 /* a 64 bit opaque identifier */
280 typedef unsigned char threadref[OPAQUETHREADBYTES];
281
282 /* About this many threadisds fit in a packet.  */
283
284 #define MAXTHREADLISTRESULTS 32
285
286 /* Data for the vFile:pread readahead cache.  */
287
288 struct readahead_cache
289 {
290   /* The file descriptor for the file that is being cached.  -1 if the
291      cache is invalid.  */
292   int fd;
293
294   /* The offset into the file that the cache buffer corresponds
295      to.  */
296   ULONGEST offset;
297
298   /* The buffer holding the cache contents.  */
299   gdb_byte *buf;
300   /* The buffer's size.  We try to read as much as fits into a packet
301      at a time.  */
302   size_t bufsize;
303
304   /* Cache hit and miss counters.  */
305   ULONGEST hit_count;
306   ULONGEST miss_count;
307 };
308
309 /* Description of the remote protocol state for the currently
310    connected target.  This is per-target state, and independent of the
311    selected architecture.  */
312
313 struct remote_state
314 {
315   /* A buffer to use for incoming packets, and its current size.  The
316      buffer is grown dynamically for larger incoming packets.
317      Outgoing packets may also be constructed in this buffer.
318      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
320      packets.  */
321   char *buf;
322   long buf_size;
323
324   /* True if we're going through initial connection setup (finding out
325      about the remote side's threads, relocating symbols, etc.).  */
326   int starting_up;
327
328   /* If we negotiated packet size explicitly (and thus can bypass
329      heuristics for the largest packet size that will not overflow
330      a buffer in the stub), this will be set to that packet size.
331      Otherwise zero, meaning to use the guessed size.  */
332   long explicit_packet_size;
333
334   /* remote_wait is normally called when the target is running and
335      waits for a stop reply packet.  But sometimes we need to call it
336      when the target is already stopped.  We can send a "?" packet
337      and have remote_wait read the response.  Or, if we already have
338      the response, we can stash it in BUF and tell remote_wait to
339      skip calling getpkt.  This flag is set when BUF contains a
340      stop reply packet and the target is not waiting.  */
341   int cached_wait_status;
342
343   /* True, if in no ack mode.  That is, neither GDB nor the stub will
344      expect acks from each other.  The connection is assumed to be
345      reliable.  */
346   int noack_mode;
347
348   /* True if we're connected in extended remote mode.  */
349   int extended;
350
351   /* True if we resumed the target and we're waiting for the target to
352      stop.  In the mean time, we can't start another command/query.
353      The remote server wouldn't be ready to process it, so we'd
354      timeout waiting for a reply that would never come and eventually
355      we'd close the connection.  This can happen in asynchronous mode
356      because we allow GDB commands while the target is running.  */
357   int waiting_for_stop_reply;
358
359   /* The status of the stub support for the various vCont actions.  */
360   struct vCont_action_support supports_vCont;
361
362   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363      responded to that.  */
364   int ctrlc_pending_p;
365
366   /* True if we saw a Ctrl-C while reading or writing from/to the
367      remote descriptor.  At that point it is not safe to send a remote
368      interrupt packet, so we instead remember we saw the Ctrl-C and
369      process it once we're done with sending/receiving the current
370      packet, which should be shortly.  If however that takes too long,
371      and the user presses Ctrl-C again, we offer to disconnect.  */
372   int got_ctrlc_during_io;
373
374   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
375      remote_open knows that we don't have a file open when the program
376      starts.  */
377   struct serial *remote_desc;
378
379   /* These are the threads which we last sent to the remote system.  The
380      TID member will be -1 for all or -2 for not sent yet.  */
381   ptid_t general_thread;
382   ptid_t continue_thread;
383
384   /* This is the traceframe which we last selected on the remote system.
385      It will be -1 if no traceframe is selected.  */
386   int remote_traceframe_number;
387
388   char *last_pass_packet;
389
390   /* The last QProgramSignals packet sent to the target.  We bypass
391      sending a new program signals list down to the target if the new
392      packet is exactly the same as the last we sent.  IOW, we only let
393      the target know about program signals list changes.  */
394   char *last_program_signals_packet;
395
396   enum gdb_signal last_sent_signal;
397
398   int last_sent_step;
399
400   /* The execution direction of the last resume we got.  */
401   enum exec_direction_kind last_resume_exec_dir;
402
403   char *finished_object;
404   char *finished_annex;
405   ULONGEST finished_offset;
406
407   /* Should we try the 'ThreadInfo' query packet?
408
409      This variable (NOT available to the user: auto-detect only!)
410      determines whether GDB will use the new, simpler "ThreadInfo"
411      query or the older, more complex syntax for thread queries.
412      This is an auto-detect variable (set to true at each connect,
413      and set to false when the target fails to recognize it).  */
414   int use_threadinfo_query;
415   int use_threadextra_query;
416
417   threadref echo_nextthread;
418   threadref nextthread;
419   threadref resultthreadlist[MAXTHREADLISTRESULTS];
420
421   /* The state of remote notification.  */
422   struct remote_notif_state *notif_state;
423
424   /* The branch trace configuration.  */
425   struct btrace_config btrace_config;
426
427   /* The argument to the last "vFile:setfs:" packet we sent, used
428      to avoid sending repeated unnecessary "vFile:setfs:" packets.
429      Initialized to -1 to indicate that no "vFile:setfs:" packet
430      has yet been sent.  */
431   int fs_pid;
432
433   /* A readahead cache for vFile:pread.  Often, reading a binary
434      involves a sequence of small reads.  E.g., when parsing an ELF
435      file.  A readahead cache helps mostly the case of remote
436      debugging on a connection with higher latency, due to the
437      request/reply nature of the RSP.  We only cache data for a single
438      file descriptor at a time.  */
439   struct readahead_cache readahead_cache;
440 };
441
442 /* Private data that we'll store in (struct thread_info)->private.  */
443 struct private_thread_info
444 {
445   char *extra;
446   char *name;
447   int core;
448
449   /* Whether the target stopped for a breakpoint/watchpoint.  */
450   enum target_stop_reason stop_reason;
451
452   /* This is set to the data address of the access causing the target
453      to stop for a watchpoint.  */
454   CORE_ADDR watch_data_address;
455
456   /* Fields used by the vCont action coalescing implemented in
457      remote_resume / remote_commit_resume.  remote_resume stores each
458      thread's last resume request in these fields, so that a later
459      remote_commit_resume knows which is the proper action for this
460      thread to include in the vCont packet.  */
461
462   /* True if the last target_resume call for this thread was a step
463      request, false if a continue request.  */
464   int last_resume_step;
465
466   /* The signal specified in the last target_resume call for this
467      thread.  */
468   enum gdb_signal last_resume_sig;
469
470   /* Whether this thread was already vCont-resumed on the remote
471      side.  */
472   int vcont_resumed;
473 };
474
475 static void
476 free_private_thread_info (struct private_thread_info *info)
477 {
478   xfree (info->extra);
479   xfree (info->name);
480   xfree (info);
481 }
482
483 /* This data could be associated with a target, but we do not always
484    have access to the current target when we need it, so for now it is
485    static.  This will be fine for as long as only one target is in use
486    at a time.  */
487 static struct remote_state *remote_state;
488
489 static struct remote_state *
490 get_remote_state_raw (void)
491 {
492   return remote_state;
493 }
494
495 /* Allocate a new struct remote_state with xmalloc, initialize it, and
496    return it.  */
497
498 static struct remote_state *
499 new_remote_state (void)
500 {
501   struct remote_state *result = XCNEW (struct remote_state);
502
503   /* The default buffer size is unimportant; it will be expanded
504      whenever a larger buffer is needed. */
505   result->buf_size = 400;
506   result->buf = (char *) xmalloc (result->buf_size);
507   result->remote_traceframe_number = -1;
508   result->last_sent_signal = GDB_SIGNAL_0;
509   result->last_resume_exec_dir = EXEC_FORWARD;
510   result->fs_pid = -1;
511
512   return result;
513 }
514
515 /* Description of the remote protocol for a given architecture.  */
516
517 struct packet_reg
518 {
519   long offset; /* Offset into G packet.  */
520   long regnum; /* GDB's internal register number.  */
521   LONGEST pnum; /* Remote protocol register number.  */
522   int in_g_packet; /* Always part of G packet.  */
523   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
524      at present.  */
525   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
526      at present.  */
527 };
528
529 struct remote_arch_state
530 {
531   /* Description of the remote protocol registers.  */
532   long sizeof_g_packet;
533
534   /* Description of the remote protocol registers indexed by REGNUM
535      (making an array gdbarch_num_regs in size).  */
536   struct packet_reg *regs;
537
538   /* This is the size (in chars) of the first response to the ``g''
539      packet.  It is used as a heuristic when determining the maximum
540      size of memory-read and memory-write packets.  A target will
541      typically only reserve a buffer large enough to hold the ``g''
542      packet.  The size does not include packet overhead (headers and
543      trailers).  */
544   long actual_register_packet_size;
545
546   /* This is the maximum size (in chars) of a non read/write packet.
547      It is also used as a cap on the size of read/write packets.  */
548   long remote_packet_size;
549 };
550
551 /* Utility: generate error from an incoming stub packet.  */
552 static void
553 trace_error (char *buf)
554 {
555   if (*buf++ != 'E')
556     return;                     /* not an error msg */
557   switch (*buf)
558     {
559     case '1':                   /* malformed packet error */
560       if (*++buf == '0')        /*   general case: */
561         error (_("remote.c: error in outgoing packet."));
562       else
563         error (_("remote.c: error in outgoing packet at field #%ld."),
564                strtol (buf, NULL, 16));
565     default:
566       error (_("Target returns error code '%s'."), buf);
567     }
568 }
569
570 /* Utility: wait for reply from stub, while accepting "O" packets.  */
571 static char *
572 remote_get_noisy_reply (char **buf_p,
573                         long *sizeof_buf)
574 {
575   do                            /* Loop on reply from remote stub.  */
576     {
577       char *buf;
578
579       QUIT;                     /* Allow user to bail out with ^C.  */
580       getpkt (buf_p, sizeof_buf, 0);
581       buf = *buf_p;
582       if (buf[0] == 'E')
583         trace_error (buf);
584       else if (startswith (buf, "qRelocInsn:"))
585         {
586           ULONGEST ul;
587           CORE_ADDR from, to, org_to;
588           char *p, *pp;
589           int adjusted_size = 0;
590           int relocated = 0;
591
592           p = buf + strlen ("qRelocInsn:");
593           pp = unpack_varlen_hex (p, &ul);
594           if (*pp != ';')
595             error (_("invalid qRelocInsn packet: %s"), buf);
596           from = ul;
597
598           p = pp + 1;
599           unpack_varlen_hex (p, &ul);
600           to = ul;
601
602           org_to = to;
603
604           TRY
605             {
606               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
607               relocated = 1;
608             }
609           CATCH (ex, RETURN_MASK_ALL)
610             {
611               if (ex.error == MEMORY_ERROR)
612                 {
613                   /* Propagate memory errors silently back to the
614                      target.  The stub may have limited the range of
615                      addresses we can write to, for example.  */
616                 }
617               else
618                 {
619                   /* Something unexpectedly bad happened.  Be verbose
620                      so we can tell what, and propagate the error back
621                      to the stub, so it doesn't get stuck waiting for
622                      a response.  */
623                   exception_fprintf (gdb_stderr, ex,
624                                      _("warning: relocating instruction: "));
625                 }
626               putpkt ("E01");
627             }
628           END_CATCH
629
630           if (relocated)
631             {
632               adjusted_size = to - org_to;
633
634               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
635               putpkt (buf);
636             }
637         }
638       else if (buf[0] == 'O' && buf[1] != 'K')
639         remote_console_output (buf + 1);        /* 'O' message from stub */
640       else
641         return buf;             /* Here's the actual reply.  */
642     }
643   while (1);
644 }
645
646 /* Handle for retreving the remote protocol data from gdbarch.  */
647 static struct gdbarch_data *remote_gdbarch_data_handle;
648
649 static struct remote_arch_state *
650 get_remote_arch_state (void)
651 {
652   gdb_assert (target_gdbarch () != NULL);
653   return ((struct remote_arch_state *)
654           gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
655 }
656
657 /* Fetch the global remote target state.  */
658
659 static struct remote_state *
660 get_remote_state (void)
661 {
662   /* Make sure that the remote architecture state has been
663      initialized, because doing so might reallocate rs->buf.  Any
664      function which calls getpkt also needs to be mindful of changes
665      to rs->buf, but this call limits the number of places which run
666      into trouble.  */
667   get_remote_arch_state ();
668
669   return get_remote_state_raw ();
670 }
671
672 /* Cleanup routine for the remote module's pspace data.  */
673
674 static void
675 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
676 {
677   char *remote_exec_file = (char *) arg;
678
679   xfree (remote_exec_file);
680 }
681
682 /* Fetch the remote exec-file from the current program space.  */
683
684 static const char *
685 get_remote_exec_file (void)
686 {
687   char *remote_exec_file;
688
689   remote_exec_file
690     = (char *) program_space_data (current_program_space,
691                                    remote_pspace_data);
692   if (remote_exec_file == NULL)
693     return "";
694
695   return remote_exec_file;
696 }
697
698 /* Set the remote exec file for PSPACE.  */
699
700 static void
701 set_pspace_remote_exec_file (struct program_space *pspace,
702                         char *remote_exec_file)
703 {
704   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
705
706   xfree (old_file);
707   set_program_space_data (pspace, remote_pspace_data,
708                           xstrdup (remote_exec_file));
709 }
710
711 /* The "set/show remote exec-file" set command hook.  */
712
713 static void
714 set_remote_exec_file (char *ignored, int from_tty,
715                       struct cmd_list_element *c)
716 {
717   gdb_assert (remote_exec_file_var != NULL);
718   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
719 }
720
721 /* The "set/show remote exec-file" show command hook.  */
722
723 static void
724 show_remote_exec_file (struct ui_file *file, int from_tty,
725                        struct cmd_list_element *cmd, const char *value)
726 {
727   fprintf_filtered (file, "%s\n", remote_exec_file_var);
728 }
729
730 static int
731 compare_pnums (const void *lhs_, const void *rhs_)
732 {
733   const struct packet_reg * const *lhs
734     = (const struct packet_reg * const *) lhs_;
735   const struct packet_reg * const *rhs
736     = (const struct packet_reg * const *) rhs_;
737
738   if ((*lhs)->pnum < (*rhs)->pnum)
739     return -1;
740   else if ((*lhs)->pnum == (*rhs)->pnum)
741     return 0;
742   else
743     return 1;
744 }
745
746 static int
747 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
748 {
749   int regnum, num_remote_regs, offset;
750   struct packet_reg **remote_regs;
751
752   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
753     {
754       struct packet_reg *r = &regs[regnum];
755
756       if (register_size (gdbarch, regnum) == 0)
757         /* Do not try to fetch zero-sized (placeholder) registers.  */
758         r->pnum = -1;
759       else
760         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
761
762       r->regnum = regnum;
763     }
764
765   /* Define the g/G packet format as the contents of each register
766      with a remote protocol number, in order of ascending protocol
767      number.  */
768
769   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
770   for (num_remote_regs = 0, regnum = 0;
771        regnum < gdbarch_num_regs (gdbarch);
772        regnum++)
773     if (regs[regnum].pnum != -1)
774       remote_regs[num_remote_regs++] = &regs[regnum];
775
776   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
777          compare_pnums);
778
779   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
780     {
781       remote_regs[regnum]->in_g_packet = 1;
782       remote_regs[regnum]->offset = offset;
783       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
784     }
785
786   return offset;
787 }
788
789 /* Given the architecture described by GDBARCH, return the remote
790    protocol register's number and the register's offset in the g/G
791    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
792    If the target does not have a mapping for REGNUM, return false,
793    otherwise, return true.  */
794
795 int
796 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
797                                    int *pnum, int *poffset)
798 {
799   struct packet_reg *regs;
800   struct cleanup *old_chain;
801
802   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
803
804   regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
805   old_chain = make_cleanup (xfree, regs);
806
807   map_regcache_remote_table (gdbarch, regs);
808
809   *pnum = regs[regnum].pnum;
810   *poffset = regs[regnum].offset;
811
812   do_cleanups (old_chain);
813
814   return *pnum != -1;
815 }
816
817 static void *
818 init_remote_state (struct gdbarch *gdbarch)
819 {
820   struct remote_state *rs = get_remote_state_raw ();
821   struct remote_arch_state *rsa;
822
823   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
824
825   /* Use the architecture to build a regnum<->pnum table, which will be
826      1:1 unless a feature set specifies otherwise.  */
827   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
828                                       gdbarch_num_regs (gdbarch),
829                                       struct packet_reg);
830
831   /* Record the maximum possible size of the g packet - it may turn out
832      to be smaller.  */
833   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
834
835   /* Default maximum number of characters in a packet body.  Many
836      remote stubs have a hardwired buffer size of 400 bytes
837      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
838      as the maximum packet-size to ensure that the packet and an extra
839      NUL character can always fit in the buffer.  This stops GDB
840      trashing stubs that try to squeeze an extra NUL into what is
841      already a full buffer (As of 1999-12-04 that was most stubs).  */
842   rsa->remote_packet_size = 400 - 1;
843
844   /* This one is filled in when a ``g'' packet is received.  */
845   rsa->actual_register_packet_size = 0;
846
847   /* Should rsa->sizeof_g_packet needs more space than the
848      default, adjust the size accordingly.  Remember that each byte is
849      encoded as two characters.  32 is the overhead for the packet
850      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
851      (``$NN:G...#NN'') is a better guess, the below has been padded a
852      little.  */
853   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
854     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
855
856   /* Make sure that the packet buffer is plenty big enough for
857      this architecture.  */
858   if (rs->buf_size < rsa->remote_packet_size)
859     {
860       rs->buf_size = 2 * rsa->remote_packet_size;
861       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
862     }
863
864   return rsa;
865 }
866
867 /* Return the current allowed size of a remote packet.  This is
868    inferred from the current architecture, and should be used to
869    limit the length of outgoing packets.  */
870 static long
871 get_remote_packet_size (void)
872 {
873   struct remote_state *rs = get_remote_state ();
874   struct remote_arch_state *rsa = get_remote_arch_state ();
875
876   if (rs->explicit_packet_size)
877     return rs->explicit_packet_size;
878
879   return rsa->remote_packet_size;
880 }
881
882 static struct packet_reg *
883 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
884 {
885   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
886     return NULL;
887   else
888     {
889       struct packet_reg *r = &rsa->regs[regnum];
890
891       gdb_assert (r->regnum == regnum);
892       return r;
893     }
894 }
895
896 static struct packet_reg *
897 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
898 {
899   int i;
900
901   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
902     {
903       struct packet_reg *r = &rsa->regs[i];
904
905       if (r->pnum == pnum)
906         return r;
907     }
908   return NULL;
909 }
910
911 static struct target_ops remote_ops;
912
913 static struct target_ops extended_remote_ops;
914
915 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
916    ``forever'' still use the normal timeout mechanism.  This is
917    currently used by the ASYNC code to guarentee that target reads
918    during the initial connect always time-out.  Once getpkt has been
919    modified to return a timeout indication and, in turn
920    remote_wait()/wait_for_inferior() have gained a timeout parameter
921    this can go away.  */
922 static int wait_forever_enabled_p = 1;
923
924 /* Allow the user to specify what sequence to send to the remote
925    when he requests a program interruption: Although ^C is usually
926    what remote systems expect (this is the default, here), it is
927    sometimes preferable to send a break.  On other systems such
928    as the Linux kernel, a break followed by g, which is Magic SysRq g
929    is required in order to interrupt the execution.  */
930 const char interrupt_sequence_control_c[] = "Ctrl-C";
931 const char interrupt_sequence_break[] = "BREAK";
932 const char interrupt_sequence_break_g[] = "BREAK-g";
933 static const char *const interrupt_sequence_modes[] =
934   {
935     interrupt_sequence_control_c,
936     interrupt_sequence_break,
937     interrupt_sequence_break_g,
938     NULL
939   };
940 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
941
942 static void
943 show_interrupt_sequence (struct ui_file *file, int from_tty,
944                          struct cmd_list_element *c,
945                          const char *value)
946 {
947   if (interrupt_sequence_mode == interrupt_sequence_control_c)
948     fprintf_filtered (file,
949                       _("Send the ASCII ETX character (Ctrl-c) "
950                         "to the remote target to interrupt the "
951                         "execution of the program.\n"));
952   else if (interrupt_sequence_mode == interrupt_sequence_break)
953     fprintf_filtered (file,
954                       _("send a break signal to the remote target "
955                         "to interrupt the execution of the program.\n"));
956   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
957     fprintf_filtered (file,
958                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
959                         "the remote target to interrupt the execution "
960                         "of Linux kernel.\n"));
961   else
962     internal_error (__FILE__, __LINE__,
963                     _("Invalid value for interrupt_sequence_mode: %s."),
964                     interrupt_sequence_mode);
965 }
966
967 /* This boolean variable specifies whether interrupt_sequence is sent
968    to the remote target when gdb connects to it.
969    This is mostly needed when you debug the Linux kernel: The Linux kernel
970    expects BREAK g which is Magic SysRq g for connecting gdb.  */
971 static int interrupt_on_connect = 0;
972
973 /* This variable is used to implement the "set/show remotebreak" commands.
974    Since these commands are now deprecated in favor of "set/show remote
975    interrupt-sequence", it no longer has any effect on the code.  */
976 static int remote_break;
977
978 static void
979 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
980 {
981   if (remote_break)
982     interrupt_sequence_mode = interrupt_sequence_break;
983   else
984     interrupt_sequence_mode = interrupt_sequence_control_c;
985 }
986
987 static void
988 show_remotebreak (struct ui_file *file, int from_tty,
989                   struct cmd_list_element *c,
990                   const char *value)
991 {
992 }
993
994 /* This variable sets the number of bits in an address that are to be
995    sent in a memory ("M" or "m") packet.  Normally, after stripping
996    leading zeros, the entire address would be sent.  This variable
997    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
998    initial implementation of remote.c restricted the address sent in
999    memory packets to ``host::sizeof long'' bytes - (typically 32
1000    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
1001    address was never sent.  Since fixing this bug may cause a break in
1002    some remote targets this variable is principly provided to
1003    facilitate backward compatibility.  */
1004
1005 static unsigned int remote_address_size;
1006
1007 /* Temporary to track who currently owns the terminal.  See
1008    remote_terminal_* for more details.  */
1009
1010 static int remote_async_terminal_ours_p;
1011
1012 \f
1013 /* User configurable variables for the number of characters in a
1014    memory read/write packet.  MIN (rsa->remote_packet_size,
1015    rsa->sizeof_g_packet) is the default.  Some targets need smaller
1016    values (fifo overruns, et.al.) and some users need larger values
1017    (speed up transfers).  The variables ``preferred_*'' (the user
1018    request), ``current_*'' (what was actually set) and ``forced_*''
1019    (Positive - a soft limit, negative - a hard limit).  */
1020
1021 struct memory_packet_config
1022 {
1023   char *name;
1024   long size;
1025   int fixed_p;
1026 };
1027
1028 /* The default max memory-write-packet-size.  The 16k is historical.
1029    (It came from older GDB's using alloca for buffers and the
1030    knowledge (folklore?) that some hosts don't cope very well with
1031    large alloca calls.)  */
1032 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1033
1034 /* The minimum remote packet size for memory transfers.  Ensures we
1035    can write at least one byte.  */
1036 #define MIN_MEMORY_PACKET_SIZE 20
1037
1038 /* Compute the current size of a read/write packet.  Since this makes
1039    use of ``actual_register_packet_size'' the computation is dynamic.  */
1040
1041 static long
1042 get_memory_packet_size (struct memory_packet_config *config)
1043 {
1044   struct remote_state *rs = get_remote_state ();
1045   struct remote_arch_state *rsa = get_remote_arch_state ();
1046
1047   long what_they_get;
1048   if (config->fixed_p)
1049     {
1050       if (config->size <= 0)
1051         what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1052       else
1053         what_they_get = config->size;
1054     }
1055   else
1056     {
1057       what_they_get = get_remote_packet_size ();
1058       /* Limit the packet to the size specified by the user.  */
1059       if (config->size > 0
1060           && what_they_get > config->size)
1061         what_they_get = config->size;
1062
1063       /* Limit it to the size of the targets ``g'' response unless we have
1064          permission from the stub to use a larger packet size.  */
1065       if (rs->explicit_packet_size == 0
1066           && rsa->actual_register_packet_size > 0
1067           && what_they_get > rsa->actual_register_packet_size)
1068         what_they_get = rsa->actual_register_packet_size;
1069     }
1070   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1071     what_they_get = MIN_MEMORY_PACKET_SIZE;
1072
1073   /* Make sure there is room in the global buffer for this packet
1074      (including its trailing NUL byte).  */
1075   if (rs->buf_size < what_they_get + 1)
1076     {
1077       rs->buf_size = 2 * what_they_get;
1078       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1079     }
1080
1081   return what_they_get;
1082 }
1083
1084 /* Update the size of a read/write packet.  If they user wants
1085    something really big then do a sanity check.  */
1086
1087 static void
1088 set_memory_packet_size (char *args, struct memory_packet_config *config)
1089 {
1090   int fixed_p = config->fixed_p;
1091   long size = config->size;
1092
1093   if (args == NULL)
1094     error (_("Argument required (integer, `fixed' or `limited')."));
1095   else if (strcmp (args, "hard") == 0
1096       || strcmp (args, "fixed") == 0)
1097     fixed_p = 1;
1098   else if (strcmp (args, "soft") == 0
1099            || strcmp (args, "limit") == 0)
1100     fixed_p = 0;
1101   else
1102     {
1103       char *end;
1104
1105       size = strtoul (args, &end, 0);
1106       if (args == end)
1107         error (_("Invalid %s (bad syntax)."), config->name);
1108
1109       /* Instead of explicitly capping the size of a packet to or
1110          disallowing it, the user is allowed to set the size to
1111          something arbitrarily large.  */
1112     }
1113
1114   /* So that the query shows the correct value.  */
1115   if (size <= 0)
1116     size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1117
1118   /* Extra checks?  */
1119   if (fixed_p && !config->fixed_p)
1120     {
1121       if (! query (_("The target may not be able to correctly handle a %s\n"
1122                    "of %ld bytes. Change the packet size? "),
1123                    config->name, size))
1124         error (_("Packet size not changed."));
1125     }
1126   /* Update the config.  */
1127   config->fixed_p = fixed_p;
1128   config->size = size;
1129 }
1130
1131 static void
1132 show_memory_packet_size (struct memory_packet_config *config)
1133 {
1134   printf_filtered (_("The %s is %ld. "), config->name, config->size);
1135   if (config->fixed_p)
1136     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1137                      get_memory_packet_size (config));
1138   else
1139     printf_filtered (_("Packets are limited to %ld bytes.\n"),
1140                      get_memory_packet_size (config));
1141 }
1142
1143 static struct memory_packet_config memory_write_packet_config =
1144 {
1145   "memory-write-packet-size",
1146 };
1147
1148 static void
1149 set_memory_write_packet_size (char *args, int from_tty)
1150 {
1151   set_memory_packet_size (args, &memory_write_packet_config);
1152 }
1153
1154 static void
1155 show_memory_write_packet_size (char *args, int from_tty)
1156 {
1157   show_memory_packet_size (&memory_write_packet_config);
1158 }
1159
1160 static long
1161 get_memory_write_packet_size (void)
1162 {
1163   return get_memory_packet_size (&memory_write_packet_config);
1164 }
1165
1166 static struct memory_packet_config memory_read_packet_config =
1167 {
1168   "memory-read-packet-size",
1169 };
1170
1171 static void
1172 set_memory_read_packet_size (char *args, int from_tty)
1173 {
1174   set_memory_packet_size (args, &memory_read_packet_config);
1175 }
1176
1177 static void
1178 show_memory_read_packet_size (char *args, int from_tty)
1179 {
1180   show_memory_packet_size (&memory_read_packet_config);
1181 }
1182
1183 static long
1184 get_memory_read_packet_size (void)
1185 {
1186   long size = get_memory_packet_size (&memory_read_packet_config);
1187
1188   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1189      extra buffer size argument before the memory read size can be
1190      increased beyond this.  */
1191   if (size > get_remote_packet_size ())
1192     size = get_remote_packet_size ();
1193   return size;
1194 }
1195
1196 \f
1197 /* Generic configuration support for packets the stub optionally
1198    supports.  Allows the user to specify the use of the packet as well
1199    as allowing GDB to auto-detect support in the remote stub.  */
1200
1201 enum packet_support
1202   {
1203     PACKET_SUPPORT_UNKNOWN = 0,
1204     PACKET_ENABLE,
1205     PACKET_DISABLE
1206   };
1207
1208 struct packet_config
1209   {
1210     const char *name;
1211     const char *title;
1212
1213     /* If auto, GDB auto-detects support for this packet or feature,
1214        either through qSupported, or by trying the packet and looking
1215        at the response.  If true, GDB assumes the target supports this
1216        packet.  If false, the packet is disabled.  Configs that don't
1217        have an associated command always have this set to auto.  */
1218     enum auto_boolean detect;
1219
1220     /* Does the target support this packet?  */
1221     enum packet_support support;
1222   };
1223
1224 /* Analyze a packet's return value and update the packet config
1225    accordingly.  */
1226
1227 enum packet_result
1228 {
1229   PACKET_ERROR,
1230   PACKET_OK,
1231   PACKET_UNKNOWN
1232 };
1233
1234 static enum packet_support packet_config_support (struct packet_config *config);
1235 static enum packet_support packet_support (int packet);
1236
1237 static void
1238 show_packet_config_cmd (struct packet_config *config)
1239 {
1240   char *support = "internal-error";
1241
1242   switch (packet_config_support (config))
1243     {
1244     case PACKET_ENABLE:
1245       support = "enabled";
1246       break;
1247     case PACKET_DISABLE:
1248       support = "disabled";
1249       break;
1250     case PACKET_SUPPORT_UNKNOWN:
1251       support = "unknown";
1252       break;
1253     }
1254   switch (config->detect)
1255     {
1256     case AUTO_BOOLEAN_AUTO:
1257       printf_filtered (_("Support for the `%s' packet "
1258                          "is auto-detected, currently %s.\n"),
1259                        config->name, support);
1260       break;
1261     case AUTO_BOOLEAN_TRUE:
1262     case AUTO_BOOLEAN_FALSE:
1263       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1264                        config->name, support);
1265       break;
1266     }
1267 }
1268
1269 static void
1270 add_packet_config_cmd (struct packet_config *config, const char *name,
1271                        const char *title, int legacy)
1272 {
1273   char *set_doc;
1274   char *show_doc;
1275   char *cmd_name;
1276
1277   config->name = name;
1278   config->title = title;
1279   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1280                         name, title);
1281   show_doc = xstrprintf ("Show current use of remote "
1282                          "protocol `%s' (%s) packet",
1283                          name, title);
1284   /* set/show TITLE-packet {auto,on,off} */
1285   cmd_name = xstrprintf ("%s-packet", title);
1286   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1287                                 &config->detect, set_doc,
1288                                 show_doc, NULL, /* help_doc */
1289                                 NULL,
1290                                 show_remote_protocol_packet_cmd,
1291                                 &remote_set_cmdlist, &remote_show_cmdlist);
1292   /* The command code copies the documentation strings.  */
1293   xfree (set_doc);
1294   xfree (show_doc);
1295   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1296   if (legacy)
1297     {
1298       char *legacy_name;
1299
1300       legacy_name = xstrprintf ("%s-packet", name);
1301       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1302                      &remote_set_cmdlist);
1303       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1304                      &remote_show_cmdlist);
1305     }
1306 }
1307
1308 static enum packet_result
1309 packet_check_result (const char *buf)
1310 {
1311   if (buf[0] != '\0')
1312     {
1313       /* The stub recognized the packet request.  Check that the
1314          operation succeeded.  */
1315       if (buf[0] == 'E'
1316           && isxdigit (buf[1]) && isxdigit (buf[2])
1317           && buf[3] == '\0')
1318         /* "Enn"  - definitly an error.  */
1319         return PACKET_ERROR;
1320
1321       /* Always treat "E." as an error.  This will be used for
1322          more verbose error messages, such as E.memtypes.  */
1323       if (buf[0] == 'E' && buf[1] == '.')
1324         return PACKET_ERROR;
1325
1326       /* The packet may or may not be OK.  Just assume it is.  */
1327       return PACKET_OK;
1328     }
1329   else
1330     /* The stub does not support the packet.  */
1331     return PACKET_UNKNOWN;
1332 }
1333
1334 static enum packet_result
1335 packet_ok (const char *buf, struct packet_config *config)
1336 {
1337   enum packet_result result;
1338
1339   if (config->detect != AUTO_BOOLEAN_TRUE
1340       && config->support == PACKET_DISABLE)
1341     internal_error (__FILE__, __LINE__,
1342                     _("packet_ok: attempt to use a disabled packet"));
1343
1344   result = packet_check_result (buf);
1345   switch (result)
1346     {
1347     case PACKET_OK:
1348     case PACKET_ERROR:
1349       /* The stub recognized the packet request.  */
1350       if (config->support == PACKET_SUPPORT_UNKNOWN)
1351         {
1352           if (remote_debug)
1353             fprintf_unfiltered (gdb_stdlog,
1354                                 "Packet %s (%s) is supported\n",
1355                                 config->name, config->title);
1356           config->support = PACKET_ENABLE;
1357         }
1358       break;
1359     case PACKET_UNKNOWN:
1360       /* The stub does not support the packet.  */
1361       if (config->detect == AUTO_BOOLEAN_AUTO
1362           && config->support == PACKET_ENABLE)
1363         {
1364           /* If the stub previously indicated that the packet was
1365              supported then there is a protocol error.  */
1366           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1367                  config->name, config->title);
1368         }
1369       else if (config->detect == AUTO_BOOLEAN_TRUE)
1370         {
1371           /* The user set it wrong.  */
1372           error (_("Enabled packet %s (%s) not recognized by stub"),
1373                  config->name, config->title);
1374         }
1375
1376       if (remote_debug)
1377         fprintf_unfiltered (gdb_stdlog,
1378                             "Packet %s (%s) is NOT supported\n",
1379                             config->name, config->title);
1380       config->support = PACKET_DISABLE;
1381       break;
1382     }
1383
1384   return result;
1385 }
1386
1387 enum {
1388   PACKET_vCont = 0,
1389   PACKET_X,
1390   PACKET_qSymbol,
1391   PACKET_P,
1392   PACKET_p,
1393   PACKET_Z0,
1394   PACKET_Z1,
1395   PACKET_Z2,
1396   PACKET_Z3,
1397   PACKET_Z4,
1398   PACKET_vFile_setfs,
1399   PACKET_vFile_open,
1400   PACKET_vFile_pread,
1401   PACKET_vFile_pwrite,
1402   PACKET_vFile_close,
1403   PACKET_vFile_unlink,
1404   PACKET_vFile_readlink,
1405   PACKET_vFile_fstat,
1406   PACKET_qXfer_auxv,
1407   PACKET_qXfer_features,
1408   PACKET_qXfer_exec_file,
1409   PACKET_qXfer_libraries,
1410   PACKET_qXfer_libraries_svr4,
1411   PACKET_qXfer_memory_map,
1412   PACKET_qXfer_spu_read,
1413   PACKET_qXfer_spu_write,
1414   PACKET_qXfer_osdata,
1415   PACKET_qXfer_threads,
1416   PACKET_qXfer_statictrace_read,
1417   PACKET_qXfer_traceframe_info,
1418   PACKET_qXfer_uib,
1419   PACKET_qGetTIBAddr,
1420   PACKET_qGetTLSAddr,
1421   PACKET_qSupported,
1422   PACKET_qTStatus,
1423   PACKET_QPassSignals,
1424   PACKET_QCatchSyscalls,
1425   PACKET_QProgramSignals,
1426   PACKET_qCRC,
1427   PACKET_qSearch_memory,
1428   PACKET_vAttach,
1429   PACKET_vRun,
1430   PACKET_QStartNoAckMode,
1431   PACKET_vKill,
1432   PACKET_qXfer_siginfo_read,
1433   PACKET_qXfer_siginfo_write,
1434   PACKET_qAttached,
1435
1436   /* Support for conditional tracepoints.  */
1437   PACKET_ConditionalTracepoints,
1438
1439   /* Support for target-side breakpoint conditions.  */
1440   PACKET_ConditionalBreakpoints,
1441
1442   /* Support for target-side breakpoint commands.  */
1443   PACKET_BreakpointCommands,
1444
1445   /* Support for fast tracepoints.  */
1446   PACKET_FastTracepoints,
1447
1448   /* Support for static tracepoints.  */
1449   PACKET_StaticTracepoints,
1450
1451   /* Support for installing tracepoints while a trace experiment is
1452      running.  */
1453   PACKET_InstallInTrace,
1454
1455   PACKET_bc,
1456   PACKET_bs,
1457   PACKET_TracepointSource,
1458   PACKET_QAllow,
1459   PACKET_qXfer_fdpic,
1460   PACKET_QDisableRandomization,
1461   PACKET_QAgent,
1462   PACKET_QTBuffer_size,
1463   PACKET_Qbtrace_off,
1464   PACKET_Qbtrace_bts,
1465   PACKET_Qbtrace_pt,
1466   PACKET_qXfer_btrace,
1467
1468   /* Support for the QNonStop packet.  */
1469   PACKET_QNonStop,
1470
1471   /* Support for the QThreadEvents packet.  */
1472   PACKET_QThreadEvents,
1473
1474   /* Support for multi-process extensions.  */
1475   PACKET_multiprocess_feature,
1476
1477   /* Support for enabling and disabling tracepoints while a trace
1478      experiment is running.  */
1479   PACKET_EnableDisableTracepoints_feature,
1480
1481   /* Support for collecting strings using the tracenz bytecode.  */
1482   PACKET_tracenz_feature,
1483
1484   /* Support for continuing to run a trace experiment while GDB is
1485      disconnected.  */
1486   PACKET_DisconnectedTracing_feature,
1487
1488   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1489   PACKET_augmented_libraries_svr4_read_feature,
1490
1491   /* Support for the qXfer:btrace-conf:read packet.  */
1492   PACKET_qXfer_btrace_conf,
1493
1494   /* Support for the Qbtrace-conf:bts:size packet.  */
1495   PACKET_Qbtrace_conf_bts_size,
1496
1497   /* Support for swbreak+ feature.  */
1498   PACKET_swbreak_feature,
1499
1500   /* Support for hwbreak+ feature.  */
1501   PACKET_hwbreak_feature,
1502
1503   /* Support for fork events.  */
1504   PACKET_fork_event_feature,
1505
1506   /* Support for vfork events.  */
1507   PACKET_vfork_event_feature,
1508
1509   /* Support for the Qbtrace-conf:pt:size packet.  */
1510   PACKET_Qbtrace_conf_pt_size,
1511
1512   /* Support for exec events.  */
1513   PACKET_exec_event_feature,
1514
1515   /* Support for query supported vCont actions.  */
1516   PACKET_vContSupported,
1517
1518   /* Support remote CTRL-C.  */
1519   PACKET_vCtrlC,
1520
1521   /* Support TARGET_WAITKIND_NO_RESUMED.  */
1522   PACKET_no_resumed,
1523
1524   PACKET_MAX
1525 };
1526
1527 static struct packet_config remote_protocol_packets[PACKET_MAX];
1528
1529 /* Returns the packet's corresponding "set remote foo-packet" command
1530    state.  See struct packet_config for more details.  */
1531
1532 static enum auto_boolean
1533 packet_set_cmd_state (int packet)
1534 {
1535   return remote_protocol_packets[packet].detect;
1536 }
1537
1538 /* Returns whether a given packet or feature is supported.  This takes
1539    into account the state of the corresponding "set remote foo-packet"
1540    command, which may be used to bypass auto-detection.  */
1541
1542 static enum packet_support
1543 packet_config_support (struct packet_config *config)
1544 {
1545   switch (config->detect)
1546     {
1547     case AUTO_BOOLEAN_TRUE:
1548       return PACKET_ENABLE;
1549     case AUTO_BOOLEAN_FALSE:
1550       return PACKET_DISABLE;
1551     case AUTO_BOOLEAN_AUTO:
1552       return config->support;
1553     default:
1554       gdb_assert_not_reached (_("bad switch"));
1555     }
1556 }
1557
1558 /* Same as packet_config_support, but takes the packet's enum value as
1559    argument.  */
1560
1561 static enum packet_support
1562 packet_support (int packet)
1563 {
1564   struct packet_config *config = &remote_protocol_packets[packet];
1565
1566   return packet_config_support (config);
1567 }
1568
1569 static void
1570 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1571                                  struct cmd_list_element *c,
1572                                  const char *value)
1573 {
1574   struct packet_config *packet;
1575
1576   for (packet = remote_protocol_packets;
1577        packet < &remote_protocol_packets[PACKET_MAX];
1578        packet++)
1579     {
1580       if (&packet->detect == c->var)
1581         {
1582           show_packet_config_cmd (packet);
1583           return;
1584         }
1585     }
1586   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1587                   c->name);
1588 }
1589
1590 /* Should we try one of the 'Z' requests?  */
1591
1592 enum Z_packet_type
1593 {
1594   Z_PACKET_SOFTWARE_BP,
1595   Z_PACKET_HARDWARE_BP,
1596   Z_PACKET_WRITE_WP,
1597   Z_PACKET_READ_WP,
1598   Z_PACKET_ACCESS_WP,
1599   NR_Z_PACKET_TYPES
1600 };
1601
1602 /* For compatibility with older distributions.  Provide a ``set remote
1603    Z-packet ...'' command that updates all the Z packet types.  */
1604
1605 static enum auto_boolean remote_Z_packet_detect;
1606
1607 static void
1608 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1609                                   struct cmd_list_element *c)
1610 {
1611   int i;
1612
1613   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1614     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1615 }
1616
1617 static void
1618 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1619                                    struct cmd_list_element *c,
1620                                    const char *value)
1621 {
1622   int i;
1623
1624   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1625     {
1626       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1627     }
1628 }
1629
1630 /* Returns true if the multi-process extensions are in effect.  */
1631
1632 static int
1633 remote_multi_process_p (struct remote_state *rs)
1634 {
1635   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1636 }
1637
1638 /* Returns true if fork events are supported.  */
1639
1640 static int
1641 remote_fork_event_p (struct remote_state *rs)
1642 {
1643   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1644 }
1645
1646 /* Returns true if vfork events are supported.  */
1647
1648 static int
1649 remote_vfork_event_p (struct remote_state *rs)
1650 {
1651   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1652 }
1653
1654 /* Returns true if exec events are supported.  */
1655
1656 static int
1657 remote_exec_event_p (struct remote_state *rs)
1658 {
1659   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1660 }
1661
1662 /* Insert fork catchpoint target routine.  If fork events are enabled
1663    then return success, nothing more to do.  */
1664
1665 static int
1666 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1667 {
1668   struct remote_state *rs = get_remote_state ();
1669
1670   return !remote_fork_event_p (rs);
1671 }
1672
1673 /* Remove fork catchpoint target routine.  Nothing to do, just
1674    return success.  */
1675
1676 static int
1677 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1678 {
1679   return 0;
1680 }
1681
1682 /* Insert vfork catchpoint target routine.  If vfork events are enabled
1683    then return success, nothing more to do.  */
1684
1685 static int
1686 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1687 {
1688   struct remote_state *rs = get_remote_state ();
1689
1690   return !remote_vfork_event_p (rs);
1691 }
1692
1693 /* Remove vfork catchpoint target routine.  Nothing to do, just
1694    return success.  */
1695
1696 static int
1697 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1698 {
1699   return 0;
1700 }
1701
1702 /* Insert exec catchpoint target routine.  If exec events are
1703    enabled, just return success.  */
1704
1705 static int
1706 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1707 {
1708   struct remote_state *rs = get_remote_state ();
1709
1710   return !remote_exec_event_p (rs);
1711 }
1712
1713 /* Remove exec catchpoint target routine.  Nothing to do, just
1714    return success.  */
1715
1716 static int
1717 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1718 {
1719   return 0;
1720 }
1721
1722 \f
1723 /* Asynchronous signal handle registered as event loop source for
1724    when we have pending events ready to be passed to the core.  */
1725
1726 static struct async_event_handler *remote_async_inferior_event_token;
1727
1728 \f
1729
1730 static ptid_t magic_null_ptid;
1731 static ptid_t not_sent_ptid;
1732 static ptid_t any_thread_ptid;
1733
1734 /* Find out if the stub attached to PID (and hence GDB should offer to
1735    detach instead of killing it when bailing out).  */
1736
1737 static int
1738 remote_query_attached (int pid)
1739 {
1740   struct remote_state *rs = get_remote_state ();
1741   size_t size = get_remote_packet_size ();
1742
1743   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1744     return 0;
1745
1746   if (remote_multi_process_p (rs))
1747     xsnprintf (rs->buf, size, "qAttached:%x", pid);
1748   else
1749     xsnprintf (rs->buf, size, "qAttached");
1750
1751   putpkt (rs->buf);
1752   getpkt (&rs->buf, &rs->buf_size, 0);
1753
1754   switch (packet_ok (rs->buf,
1755                      &remote_protocol_packets[PACKET_qAttached]))
1756     {
1757     case PACKET_OK:
1758       if (strcmp (rs->buf, "1") == 0)
1759         return 1;
1760       break;
1761     case PACKET_ERROR:
1762       warning (_("Remote failure reply: %s"), rs->buf);
1763       break;
1764     case PACKET_UNKNOWN:
1765       break;
1766     }
1767
1768   return 0;
1769 }
1770
1771 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
1772    has been invented by GDB, instead of reported by the target.  Since
1773    we can be connected to a remote system before before knowing about
1774    any inferior, mark the target with execution when we find the first
1775    inferior.  If ATTACHED is 1, then we had just attached to this
1776    inferior.  If it is 0, then we just created this inferior.  If it
1777    is -1, then try querying the remote stub to find out if it had
1778    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
1779    attempt to open this inferior's executable as the main executable
1780    if no main executable is open already.  */
1781
1782 static struct inferior *
1783 remote_add_inferior (int fake_pid_p, int pid, int attached,
1784                      int try_open_exec)
1785 {
1786   struct inferior *inf;
1787
1788   /* Check whether this process we're learning about is to be
1789      considered attached, or if is to be considered to have been
1790      spawned by the stub.  */
1791   if (attached == -1)
1792     attached = remote_query_attached (pid);
1793
1794   if (gdbarch_has_global_solist (target_gdbarch ()))
1795     {
1796       /* If the target shares code across all inferiors, then every
1797          attach adds a new inferior.  */
1798       inf = add_inferior (pid);
1799
1800       /* ... and every inferior is bound to the same program space.
1801          However, each inferior may still have its own address
1802          space.  */
1803       inf->aspace = maybe_new_address_space ();
1804       inf->pspace = current_program_space;
1805     }
1806   else
1807     {
1808       /* In the traditional debugging scenario, there's a 1-1 match
1809          between program/address spaces.  We simply bind the inferior
1810          to the program space's address space.  */
1811       inf = current_inferior ();
1812       inferior_appeared (inf, pid);
1813     }
1814
1815   inf->attach_flag = attached;
1816   inf->fake_pid_p = fake_pid_p;
1817
1818   /* If no main executable is currently open then attempt to
1819      open the file that was executed to create this inferior.  */
1820   if (try_open_exec && get_exec_file (0) == NULL)
1821     exec_file_locate_attach (pid, 0, 1);
1822
1823   return inf;
1824 }
1825
1826 static struct private_thread_info *
1827   get_private_info_thread (struct thread_info *info);
1828
1829 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1830    according to RUNNING.  */
1831
1832 static void
1833 remote_add_thread (ptid_t ptid, int running, int executing)
1834 {
1835   struct remote_state *rs = get_remote_state ();
1836   struct thread_info *thread;
1837
1838   /* GDB historically didn't pull threads in the initial connection
1839      setup.  If the remote target doesn't even have a concept of
1840      threads (e.g., a bare-metal target), even if internally we
1841      consider that a single-threaded target, mentioning a new thread
1842      might be confusing to the user.  Be silent then, preserving the
1843      age old behavior.  */
1844   if (rs->starting_up)
1845     thread = add_thread_silent (ptid);
1846   else
1847     thread = add_thread (ptid);
1848
1849   get_private_info_thread (thread)->vcont_resumed = executing;
1850   set_executing (ptid, executing);
1851   set_running (ptid, running);
1852 }
1853
1854 /* Come here when we learn about a thread id from the remote target.
1855    It may be the first time we hear about such thread, so take the
1856    opportunity to add it to GDB's thread list.  In case this is the
1857    first time we're noticing its corresponding inferior, add it to
1858    GDB's inferior list as well.  EXECUTING indicates whether the
1859    thread is (internally) executing or stopped.  */
1860
1861 static void
1862 remote_notice_new_inferior (ptid_t currthread, int executing)
1863 {
1864   /* In non-stop mode, we assume new found threads are (externally)
1865      running until proven otherwise with a stop reply.  In all-stop,
1866      we can only get here if all threads are stopped.  */
1867   int running = target_is_non_stop_p () ? 1 : 0;
1868
1869   /* If this is a new thread, add it to GDB's thread list.
1870      If we leave it up to WFI to do this, bad things will happen.  */
1871
1872   if (in_thread_list (currthread) && is_exited (currthread))
1873     {
1874       /* We're seeing an event on a thread id we knew had exited.
1875          This has to be a new thread reusing the old id.  Add it.  */
1876       remote_add_thread (currthread, running, executing);
1877       return;
1878     }
1879
1880   if (!in_thread_list (currthread))
1881     {
1882       struct inferior *inf = NULL;
1883       int pid = ptid_get_pid (currthread);
1884
1885       if (ptid_is_pid (inferior_ptid)
1886           && pid == ptid_get_pid (inferior_ptid))
1887         {
1888           /* inferior_ptid has no thread member yet.  This can happen
1889              with the vAttach -> remote_wait,"TAAthread:" path if the
1890              stub doesn't support qC.  This is the first stop reported
1891              after an attach, so this is the main thread.  Update the
1892              ptid in the thread list.  */
1893           if (in_thread_list (pid_to_ptid (pid)))
1894             thread_change_ptid (inferior_ptid, currthread);
1895           else
1896             {
1897               remote_add_thread (currthread, running, executing);
1898               inferior_ptid = currthread;
1899             }
1900           return;
1901         }
1902
1903       if (ptid_equal (magic_null_ptid, inferior_ptid))
1904         {
1905           /* inferior_ptid is not set yet.  This can happen with the
1906              vRun -> remote_wait,"TAAthread:" path if the stub
1907              doesn't support qC.  This is the first stop reported
1908              after an attach, so this is the main thread.  Update the
1909              ptid in the thread list.  */
1910           thread_change_ptid (inferior_ptid, currthread);
1911           return;
1912         }
1913
1914       /* When connecting to a target remote, or to a target
1915          extended-remote which already was debugging an inferior, we
1916          may not know about it yet.  Add it before adding its child
1917          thread, so notifications are emitted in a sensible order.  */
1918       if (!in_inferior_list (ptid_get_pid (currthread)))
1919         {
1920           struct remote_state *rs = get_remote_state ();
1921           int fake_pid_p = !remote_multi_process_p (rs);
1922
1923           inf = remote_add_inferior (fake_pid_p,
1924                                      ptid_get_pid (currthread), -1, 1);
1925         }
1926
1927       /* This is really a new thread.  Add it.  */
1928       remote_add_thread (currthread, running, executing);
1929
1930       /* If we found a new inferior, let the common code do whatever
1931          it needs to with it (e.g., read shared libraries, insert
1932          breakpoints), unless we're just setting up an all-stop
1933          connection.  */
1934       if (inf != NULL)
1935         {
1936           struct remote_state *rs = get_remote_state ();
1937
1938           if (!rs->starting_up)
1939             notice_new_inferior (currthread, executing, 0);
1940         }
1941     }
1942 }
1943
1944 /* Return THREAD's private thread data, creating it if necessary.  */
1945
1946 static struct private_thread_info *
1947 get_private_info_thread (struct thread_info *thread)
1948 {
1949   gdb_assert (thread != NULL);
1950
1951   if (thread->priv == NULL)
1952     {
1953       struct private_thread_info *priv = XNEW (struct private_thread_info);
1954
1955       thread->private_dtor = free_private_thread_info;
1956       thread->priv = priv;
1957
1958       priv->core = -1;
1959       priv->extra = NULL;
1960       priv->name = NULL;
1961       priv->name = NULL;
1962       priv->last_resume_step = 0;
1963       priv->last_resume_sig = GDB_SIGNAL_0;
1964       priv->vcont_resumed = 0;
1965     }
1966
1967   return thread->priv;
1968 }
1969
1970 /* Return PTID's private thread data, creating it if necessary.  */
1971
1972 static struct private_thread_info *
1973 get_private_info_ptid (ptid_t ptid)
1974 {
1975   struct thread_info *info = find_thread_ptid (ptid);
1976
1977   return get_private_info_thread (info);
1978 }
1979
1980 /* Call this function as a result of
1981    1) A halt indication (T packet) containing a thread id
1982    2) A direct query of currthread
1983    3) Successful execution of set thread */
1984
1985 static void
1986 record_currthread (struct remote_state *rs, ptid_t currthread)
1987 {
1988   rs->general_thread = currthread;
1989 }
1990
1991 /* If 'QPassSignals' is supported, tell the remote stub what signals
1992    it can simply pass through to the inferior without reporting.  */
1993
1994 static void
1995 remote_pass_signals (struct target_ops *self,
1996                      int numsigs, unsigned char *pass_signals)
1997 {
1998   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1999     {
2000       char *pass_packet, *p;
2001       int count = 0, i;
2002       struct remote_state *rs = get_remote_state ();
2003
2004       gdb_assert (numsigs < 256);
2005       for (i = 0; i < numsigs; i++)
2006         {
2007           if (pass_signals[i])
2008             count++;
2009         }
2010       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2011       strcpy (pass_packet, "QPassSignals:");
2012       p = pass_packet + strlen (pass_packet);
2013       for (i = 0; i < numsigs; i++)
2014         {
2015           if (pass_signals[i])
2016             {
2017               if (i >= 16)
2018                 *p++ = tohex (i >> 4);
2019               *p++ = tohex (i & 15);
2020               if (count)
2021                 *p++ = ';';
2022               else
2023                 break;
2024               count--;
2025             }
2026         }
2027       *p = 0;
2028       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2029         {
2030           putpkt (pass_packet);
2031           getpkt (&rs->buf, &rs->buf_size, 0);
2032           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2033           if (rs->last_pass_packet)
2034             xfree (rs->last_pass_packet);
2035           rs->last_pass_packet = pass_packet;
2036         }
2037       else
2038         xfree (pass_packet);
2039     }
2040 }
2041
2042 /* If 'QCatchSyscalls' is supported, tell the remote stub
2043    to report syscalls to GDB.  */
2044
2045 static int
2046 remote_set_syscall_catchpoint (struct target_ops *self,
2047                                int pid, int needed, int any_count,
2048                                int table_size, int *table)
2049 {
2050   char *catch_packet;
2051   enum packet_result result;
2052   int n_sysno = 0;
2053
2054   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2055     {
2056       /* Not supported.  */
2057       return 1;
2058     }
2059
2060   if (needed && !any_count)
2061     {
2062       int i;
2063
2064       /* Count how many syscalls are to be caught (table[sysno] != 0).  */
2065       for (i = 0; i < table_size; i++)
2066         {
2067           if (table[i] != 0)
2068             n_sysno++;
2069         }
2070     }
2071
2072   if (remote_debug)
2073     {
2074       fprintf_unfiltered (gdb_stdlog,
2075                           "remote_set_syscall_catchpoint "
2076                           "pid %d needed %d any_count %d n_sysno %d\n",
2077                           pid, needed, any_count, n_sysno);
2078     }
2079
2080   if (needed)
2081     {
2082       /* Prepare a packet with the sysno list, assuming max 8+1
2083          characters for a sysno.  If the resulting packet size is too
2084          big, fallback on the non-selective packet.  */
2085       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2086
2087       catch_packet = (char *) xmalloc (maxpktsz);
2088       strcpy (catch_packet, "QCatchSyscalls:1");
2089       if (!any_count)
2090         {
2091           int i;
2092           char *p;
2093
2094           p = catch_packet;
2095           p += strlen (p);
2096
2097           /* Add in catch_packet each syscall to be caught (table[i] != 0).  */
2098           for (i = 0; i < table_size; i++)
2099             {
2100               if (table[i] != 0)
2101                 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2102             }
2103         }
2104       if (strlen (catch_packet) > get_remote_packet_size ())
2105         {
2106           /* catch_packet too big.  Fallback to less efficient
2107              non selective mode, with GDB doing the filtering.  */
2108           catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2109         }
2110     }
2111   else
2112     catch_packet = xstrdup ("QCatchSyscalls:0");
2113
2114   {
2115     struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2116     struct remote_state *rs = get_remote_state ();
2117
2118     putpkt (catch_packet);
2119     getpkt (&rs->buf, &rs->buf_size, 0);
2120     result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2121     do_cleanups (old_chain);
2122     if (result == PACKET_OK)
2123       return 0;
2124     else
2125       return -1;
2126   }
2127 }
2128
2129 /* If 'QProgramSignals' is supported, tell the remote stub what
2130    signals it should pass through to the inferior when detaching.  */
2131
2132 static void
2133 remote_program_signals (struct target_ops *self,
2134                         int numsigs, unsigned char *signals)
2135 {
2136   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2137     {
2138       char *packet, *p;
2139       int count = 0, i;
2140       struct remote_state *rs = get_remote_state ();
2141
2142       gdb_assert (numsigs < 256);
2143       for (i = 0; i < numsigs; i++)
2144         {
2145           if (signals[i])
2146             count++;
2147         }
2148       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2149       strcpy (packet, "QProgramSignals:");
2150       p = packet + strlen (packet);
2151       for (i = 0; i < numsigs; i++)
2152         {
2153           if (signal_pass_state (i))
2154             {
2155               if (i >= 16)
2156                 *p++ = tohex (i >> 4);
2157               *p++ = tohex (i & 15);
2158               if (count)
2159                 *p++ = ';';
2160               else
2161                 break;
2162               count--;
2163             }
2164         }
2165       *p = 0;
2166       if (!rs->last_program_signals_packet
2167           || strcmp (rs->last_program_signals_packet, packet) != 0)
2168         {
2169           putpkt (packet);
2170           getpkt (&rs->buf, &rs->buf_size, 0);
2171           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2172           xfree (rs->last_program_signals_packet);
2173           rs->last_program_signals_packet = packet;
2174         }
2175       else
2176         xfree (packet);
2177     }
2178 }
2179
2180 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2181    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2182    thread.  If GEN is set, set the general thread, if not, then set
2183    the step/continue thread.  */
2184 static void
2185 set_thread (struct ptid ptid, int gen)
2186 {
2187   struct remote_state *rs = get_remote_state ();
2188   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2189   char *buf = rs->buf;
2190   char *endbuf = rs->buf + get_remote_packet_size ();
2191
2192   if (ptid_equal (state, ptid))
2193     return;
2194
2195   *buf++ = 'H';
2196   *buf++ = gen ? 'g' : 'c';
2197   if (ptid_equal (ptid, magic_null_ptid))
2198     xsnprintf (buf, endbuf - buf, "0");
2199   else if (ptid_equal (ptid, any_thread_ptid))
2200     xsnprintf (buf, endbuf - buf, "0");
2201   else if (ptid_equal (ptid, minus_one_ptid))
2202     xsnprintf (buf, endbuf - buf, "-1");
2203   else
2204     write_ptid (buf, endbuf, ptid);
2205   putpkt (rs->buf);
2206   getpkt (&rs->buf, &rs->buf_size, 0);
2207   if (gen)
2208     rs->general_thread = ptid;
2209   else
2210     rs->continue_thread = ptid;
2211 }
2212
2213 static void
2214 set_general_thread (struct ptid ptid)
2215 {
2216   set_thread (ptid, 1);
2217 }
2218
2219 static void
2220 set_continue_thread (struct ptid ptid)
2221 {
2222   set_thread (ptid, 0);
2223 }
2224
2225 /* Change the remote current process.  Which thread within the process
2226    ends up selected isn't important, as long as it is the same process
2227    as what INFERIOR_PTID points to.
2228
2229    This comes from that fact that there is no explicit notion of
2230    "selected process" in the protocol.  The selected process for
2231    general operations is the process the selected general thread
2232    belongs to.  */
2233
2234 static void
2235 set_general_process (void)
2236 {
2237   struct remote_state *rs = get_remote_state ();
2238
2239   /* If the remote can't handle multiple processes, don't bother.  */
2240   if (!remote_multi_process_p (rs))
2241     return;
2242
2243   /* We only need to change the remote current thread if it's pointing
2244      at some other process.  */
2245   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2246     set_general_thread (inferior_ptid);
2247 }
2248
2249 \f
2250 /* Return nonzero if this is the main thread that we made up ourselves
2251    to model non-threaded targets as single-threaded.  */
2252
2253 static int
2254 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2255 {
2256   if (ptid_equal (ptid, magic_null_ptid))
2257     /* The main thread is always alive.  */
2258     return 1;
2259
2260   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2261     /* The main thread is always alive.  This can happen after a
2262        vAttach, if the remote side doesn't support
2263        multi-threading.  */
2264     return 1;
2265
2266   return 0;
2267 }
2268
2269 /* Return nonzero if the thread PTID is still alive on the remote
2270    system.  */
2271
2272 static int
2273 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2274 {
2275   struct remote_state *rs = get_remote_state ();
2276   char *p, *endp;
2277
2278   /* Check if this is a thread that we made up ourselves to model
2279      non-threaded targets as single-threaded.  */
2280   if (remote_thread_always_alive (ops, ptid))
2281     return 1;
2282
2283   p = rs->buf;
2284   endp = rs->buf + get_remote_packet_size ();
2285
2286   *p++ = 'T';
2287   write_ptid (p, endp, ptid);
2288
2289   putpkt (rs->buf);
2290   getpkt (&rs->buf, &rs->buf_size, 0);
2291   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2292 }
2293
2294 /* Return a pointer to a thread name if we know it and NULL otherwise.
2295    The thread_info object owns the memory for the name.  */
2296
2297 static const char *
2298 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2299 {
2300   if (info->priv != NULL)
2301     return info->priv->name;
2302
2303   return NULL;
2304 }
2305
2306 /* About these extended threadlist and threadinfo packets.  They are
2307    variable length packets but, the fields within them are often fixed
2308    length.  They are redundent enough to send over UDP as is the
2309    remote protocol in general.  There is a matching unit test module
2310    in libstub.  */
2311
2312 /* WARNING: This threadref data structure comes from the remote O.S.,
2313    libstub protocol encoding, and remote.c.  It is not particularly
2314    changable.  */
2315
2316 /* Right now, the internal structure is int. We want it to be bigger.
2317    Plan to fix this.  */
2318
2319 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2320
2321 /* gdb_ext_thread_info is an internal GDB data structure which is
2322    equivalent to the reply of the remote threadinfo packet.  */
2323
2324 struct gdb_ext_thread_info
2325   {
2326     threadref threadid;         /* External form of thread reference.  */
2327     int active;                 /* Has state interesting to GDB?
2328                                    regs, stack.  */
2329     char display[256];          /* Brief state display, name,
2330                                    blocked/suspended.  */
2331     char shortname[32];         /* To be used to name threads.  */
2332     char more_display[256];     /* Long info, statistics, queue depth,
2333                                    whatever.  */
2334   };
2335
2336 /* The volume of remote transfers can be limited by submitting
2337    a mask containing bits specifying the desired information.
2338    Use a union of these values as the 'selection' parameter to
2339    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2340
2341 #define TAG_THREADID 1
2342 #define TAG_EXISTS 2
2343 #define TAG_DISPLAY 4
2344 #define TAG_THREADNAME 8
2345 #define TAG_MOREDISPLAY 16
2346
2347 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2348
2349 static char *unpack_nibble (char *buf, int *val);
2350
2351 static char *unpack_byte (char *buf, int *value);
2352
2353 static char *pack_int (char *buf, int value);
2354
2355 static char *unpack_int (char *buf, int *value);
2356
2357 static char *unpack_string (char *src, char *dest, int length);
2358
2359 static char *pack_threadid (char *pkt, threadref *id);
2360
2361 static char *unpack_threadid (char *inbuf, threadref *id);
2362
2363 void int_to_threadref (threadref *id, int value);
2364
2365 static int threadref_to_int (threadref *ref);
2366
2367 static void copy_threadref (threadref *dest, threadref *src);
2368
2369 static int threadmatch (threadref *dest, threadref *src);
2370
2371 static char *pack_threadinfo_request (char *pkt, int mode,
2372                                       threadref *id);
2373
2374 static int remote_unpack_thread_info_response (char *pkt,
2375                                                threadref *expectedref,
2376                                                struct gdb_ext_thread_info
2377                                                *info);
2378
2379
2380 static int remote_get_threadinfo (threadref *threadid,
2381                                   int fieldset, /*TAG mask */
2382                                   struct gdb_ext_thread_info *info);
2383
2384 static char *pack_threadlist_request (char *pkt, int startflag,
2385                                       int threadcount,
2386                                       threadref *nextthread);
2387
2388 static int parse_threadlist_response (char *pkt,
2389                                       int result_limit,
2390                                       threadref *original_echo,
2391                                       threadref *resultlist,
2392                                       int *doneflag);
2393
2394 static int remote_get_threadlist (int startflag,
2395                                   threadref *nextthread,
2396                                   int result_limit,
2397                                   int *done,
2398                                   int *result_count,
2399                                   threadref *threadlist);
2400
2401 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2402
2403 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2404                                        void *context, int looplimit);
2405
2406 static int remote_newthread_step (threadref *ref, void *context);
2407
2408
2409 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2410    buffer we're allowed to write to.  Returns
2411    BUF+CHARACTERS_WRITTEN.  */
2412
2413 static char *
2414 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2415 {
2416   int pid, tid;
2417   struct remote_state *rs = get_remote_state ();
2418
2419   if (remote_multi_process_p (rs))
2420     {
2421       pid = ptid_get_pid (ptid);
2422       if (pid < 0)
2423         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2424       else
2425         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2426     }
2427   tid = ptid_get_lwp (ptid);
2428   if (tid < 0)
2429     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2430   else
2431     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2432
2433   return buf;
2434 }
2435
2436 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
2437    passed the last parsed char.  Returns null_ptid on error.  */
2438
2439 static ptid_t
2440 read_ptid (char *buf, char **obuf)
2441 {
2442   char *p = buf;
2443   char *pp;
2444   ULONGEST pid = 0, tid = 0;
2445
2446   if (*p == 'p')
2447     {
2448       /* Multi-process ptid.  */
2449       pp = unpack_varlen_hex (p + 1, &pid);
2450       if (*pp != '.')
2451         error (_("invalid remote ptid: %s"), p);
2452
2453       p = pp;
2454       pp = unpack_varlen_hex (p + 1, &tid);
2455       if (obuf)
2456         *obuf = pp;
2457       return ptid_build (pid, tid, 0);
2458     }
2459
2460   /* No multi-process.  Just a tid.  */
2461   pp = unpack_varlen_hex (p, &tid);
2462
2463   /* Return null_ptid when no thread id is found.  */
2464   if (p == pp)
2465     {
2466       if (obuf)
2467         *obuf = pp;
2468       return null_ptid;
2469     }
2470
2471   /* Since the stub is not sending a process id, then default to
2472      what's in inferior_ptid, unless it's null at this point.  If so,
2473      then since there's no way to know the pid of the reported
2474      threads, use the magic number.  */
2475   if (ptid_equal (inferior_ptid, null_ptid))
2476     pid = ptid_get_pid (magic_null_ptid);
2477   else
2478     pid = ptid_get_pid (inferior_ptid);
2479
2480   if (obuf)
2481     *obuf = pp;
2482   return ptid_build (pid, tid, 0);
2483 }
2484
2485 static int
2486 stubhex (int ch)
2487 {
2488   if (ch >= 'a' && ch <= 'f')
2489     return ch - 'a' + 10;
2490   if (ch >= '0' && ch <= '9')
2491     return ch - '0';
2492   if (ch >= 'A' && ch <= 'F')
2493     return ch - 'A' + 10;
2494   return -1;
2495 }
2496
2497 static int
2498 stub_unpack_int (char *buff, int fieldlength)
2499 {
2500   int nibble;
2501   int retval = 0;
2502
2503   while (fieldlength)
2504     {
2505       nibble = stubhex (*buff++);
2506       retval |= nibble;
2507       fieldlength--;
2508       if (fieldlength)
2509         retval = retval << 4;
2510     }
2511   return retval;
2512 }
2513
2514 static char *
2515 unpack_nibble (char *buf, int *val)
2516 {
2517   *val = fromhex (*buf++);
2518   return buf;
2519 }
2520
2521 static char *
2522 unpack_byte (char *buf, int *value)
2523 {
2524   *value = stub_unpack_int (buf, 2);
2525   return buf + 2;
2526 }
2527
2528 static char *
2529 pack_int (char *buf, int value)
2530 {
2531   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2532   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2533   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2534   buf = pack_hex_byte (buf, (value & 0xff));
2535   return buf;
2536 }
2537
2538 static char *
2539 unpack_int (char *buf, int *value)
2540 {
2541   *value = stub_unpack_int (buf, 8);
2542   return buf + 8;
2543 }
2544
2545 #if 0                   /* Currently unused, uncomment when needed.  */
2546 static char *pack_string (char *pkt, char *string);
2547
2548 static char *
2549 pack_string (char *pkt, char *string)
2550 {
2551   char ch;
2552   int len;
2553
2554   len = strlen (string);
2555   if (len > 200)
2556     len = 200;          /* Bigger than most GDB packets, junk???  */
2557   pkt = pack_hex_byte (pkt, len);
2558   while (len-- > 0)
2559     {
2560       ch = *string++;
2561       if ((ch == '\0') || (ch == '#'))
2562         ch = '*';               /* Protect encapsulation.  */
2563       *pkt++ = ch;
2564     }
2565   return pkt;
2566 }
2567 #endif /* 0 (unused) */
2568
2569 static char *
2570 unpack_string (char *src, char *dest, int length)
2571 {
2572   while (length--)
2573     *dest++ = *src++;
2574   *dest = '\0';
2575   return src;
2576 }
2577
2578 static char *
2579 pack_threadid (char *pkt, threadref *id)
2580 {
2581   char *limit;
2582   unsigned char *altid;
2583
2584   altid = (unsigned char *) id;
2585   limit = pkt + BUF_THREAD_ID_SIZE;
2586   while (pkt < limit)
2587     pkt = pack_hex_byte (pkt, *altid++);
2588   return pkt;
2589 }
2590
2591
2592 static char *
2593 unpack_threadid (char *inbuf, threadref *id)
2594 {
2595   char *altref;
2596   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2597   int x, y;
2598
2599   altref = (char *) id;
2600
2601   while (inbuf < limit)
2602     {
2603       x = stubhex (*inbuf++);
2604       y = stubhex (*inbuf++);
2605       *altref++ = (x << 4) | y;
2606     }
2607   return inbuf;
2608 }
2609
2610 /* Externally, threadrefs are 64 bits but internally, they are still
2611    ints.  This is due to a mismatch of specifications.  We would like
2612    to use 64bit thread references internally.  This is an adapter
2613    function.  */
2614
2615 void
2616 int_to_threadref (threadref *id, int value)
2617 {
2618   unsigned char *scan;
2619
2620   scan = (unsigned char *) id;
2621   {
2622     int i = 4;
2623     while (i--)
2624       *scan++ = 0;
2625   }
2626   *scan++ = (value >> 24) & 0xff;
2627   *scan++ = (value >> 16) & 0xff;
2628   *scan++ = (value >> 8) & 0xff;
2629   *scan++ = (value & 0xff);
2630 }
2631
2632 static int
2633 threadref_to_int (threadref *ref)
2634 {
2635   int i, value = 0;
2636   unsigned char *scan;
2637
2638   scan = *ref;
2639   scan += 4;
2640   i = 4;
2641   while (i-- > 0)
2642     value = (value << 8) | ((*scan++) & 0xff);
2643   return value;
2644 }
2645
2646 static void
2647 copy_threadref (threadref *dest, threadref *src)
2648 {
2649   int i;
2650   unsigned char *csrc, *cdest;
2651
2652   csrc = (unsigned char *) src;
2653   cdest = (unsigned char *) dest;
2654   i = 8;
2655   while (i--)
2656     *cdest++ = *csrc++;
2657 }
2658
2659 static int
2660 threadmatch (threadref *dest, threadref *src)
2661 {
2662   /* Things are broken right now, so just assume we got a match.  */
2663 #if 0
2664   unsigned char *srcp, *destp;
2665   int i, result;
2666   srcp = (char *) src;
2667   destp = (char *) dest;
2668
2669   result = 1;
2670   while (i-- > 0)
2671     result &= (*srcp++ == *destp++) ? 1 : 0;
2672   return result;
2673 #endif
2674   return 1;
2675 }
2676
2677 /*
2678    threadid:1,        # always request threadid
2679    context_exists:2,
2680    display:4,
2681    unique_name:8,
2682    more_display:16
2683  */
2684
2685 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2686
2687 static char *
2688 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2689 {
2690   *pkt++ = 'q';                         /* Info Query */
2691   *pkt++ = 'P';                         /* process or thread info */
2692   pkt = pack_int (pkt, mode);           /* mode */
2693   pkt = pack_threadid (pkt, id);        /* threadid */
2694   *pkt = '\0';                          /* terminate */
2695   return pkt;
2696 }
2697
2698 /* These values tag the fields in a thread info response packet.  */
2699 /* Tagging the fields allows us to request specific fields and to
2700    add more fields as time goes by.  */
2701
2702 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2703 #define TAG_EXISTS 2            /* Is this process defined enough to
2704                                    fetch registers and its stack?  */
2705 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2706 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2707 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2708                                    the process.  */
2709
2710 static int
2711 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2712                                     struct gdb_ext_thread_info *info)
2713 {
2714   struct remote_state *rs = get_remote_state ();
2715   int mask, length;
2716   int tag;
2717   threadref ref;
2718   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2719   int retval = 1;
2720
2721   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2722   info->active = 0;
2723   info->display[0] = '\0';
2724   info->shortname[0] = '\0';
2725   info->more_display[0] = '\0';
2726
2727   /* Assume the characters indicating the packet type have been
2728      stripped.  */
2729   pkt = unpack_int (pkt, &mask);        /* arg mask */
2730   pkt = unpack_threadid (pkt, &ref);
2731
2732   if (mask == 0)
2733     warning (_("Incomplete response to threadinfo request."));
2734   if (!threadmatch (&ref, expectedref))
2735     {                   /* This is an answer to a different request.  */
2736       warning (_("ERROR RMT Thread info mismatch."));
2737       return 0;
2738     }
2739   copy_threadref (&info->threadid, &ref);
2740
2741   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
2742
2743   /* Packets are terminated with nulls.  */
2744   while ((pkt < limit) && mask && *pkt)
2745     {
2746       pkt = unpack_int (pkt, &tag);     /* tag */
2747       pkt = unpack_byte (pkt, &length); /* length */
2748       if (!(tag & mask))                /* Tags out of synch with mask.  */
2749         {
2750           warning (_("ERROR RMT: threadinfo tag mismatch."));
2751           retval = 0;
2752           break;
2753         }
2754       if (tag == TAG_THREADID)
2755         {
2756           if (length != 16)
2757             {
2758               warning (_("ERROR RMT: length of threadid is not 16."));
2759               retval = 0;
2760               break;
2761             }
2762           pkt = unpack_threadid (pkt, &ref);
2763           mask = mask & ~TAG_THREADID;
2764           continue;
2765         }
2766       if (tag == TAG_EXISTS)
2767         {
2768           info->active = stub_unpack_int (pkt, length);
2769           pkt += length;
2770           mask = mask & ~(TAG_EXISTS);
2771           if (length > 8)
2772             {
2773               warning (_("ERROR RMT: 'exists' length too long."));
2774               retval = 0;
2775               break;
2776             }
2777           continue;
2778         }
2779       if (tag == TAG_THREADNAME)
2780         {
2781           pkt = unpack_string (pkt, &info->shortname[0], length);
2782           mask = mask & ~TAG_THREADNAME;
2783           continue;
2784         }
2785       if (tag == TAG_DISPLAY)
2786         {
2787           pkt = unpack_string (pkt, &info->display[0], length);
2788           mask = mask & ~TAG_DISPLAY;
2789           continue;
2790         }
2791       if (tag == TAG_MOREDISPLAY)
2792         {
2793           pkt = unpack_string (pkt, &info->more_display[0], length);
2794           mask = mask & ~TAG_MOREDISPLAY;
2795           continue;
2796         }
2797       warning (_("ERROR RMT: unknown thread info tag."));
2798       break;                    /* Not a tag we know about.  */
2799     }
2800   return retval;
2801 }
2802
2803 static int
2804 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2805                        struct gdb_ext_thread_info *info)
2806 {
2807   struct remote_state *rs = get_remote_state ();
2808   int result;
2809
2810   pack_threadinfo_request (rs->buf, fieldset, threadid);
2811   putpkt (rs->buf);
2812   getpkt (&rs->buf, &rs->buf_size, 0);
2813
2814   if (rs->buf[0] == '\0')
2815     return 0;
2816
2817   result = remote_unpack_thread_info_response (rs->buf + 2,
2818                                                threadid, info);
2819   return result;
2820 }
2821
2822 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2823
2824 static char *
2825 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2826                          threadref *nextthread)
2827 {
2828   *pkt++ = 'q';                 /* info query packet */
2829   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2830   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2831   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2832   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2833   *pkt = '\0';
2834   return pkt;
2835 }
2836
2837 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2838
2839 static int
2840 parse_threadlist_response (char *pkt, int result_limit,
2841                            threadref *original_echo, threadref *resultlist,
2842                            int *doneflag)
2843 {
2844   struct remote_state *rs = get_remote_state ();
2845   char *limit;
2846   int count, resultcount, done;
2847
2848   resultcount = 0;
2849   /* Assume the 'q' and 'M chars have been stripped.  */
2850   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2851   /* done parse past here */
2852   pkt = unpack_byte (pkt, &count);      /* count field */
2853   pkt = unpack_nibble (pkt, &done);
2854   /* The first threadid is the argument threadid.  */
2855   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2856   while ((count-- > 0) && (pkt < limit))
2857     {
2858       pkt = unpack_threadid (pkt, resultlist++);
2859       if (resultcount++ >= result_limit)
2860         break;
2861     }
2862   if (doneflag)
2863     *doneflag = done;
2864   return resultcount;
2865 }
2866
2867 /* Fetch the next batch of threads from the remote.  Returns -1 if the
2868    qL packet is not supported, 0 on error and 1 on success.  */
2869
2870 static int
2871 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2872                        int *done, int *result_count, threadref *threadlist)
2873 {
2874   struct remote_state *rs = get_remote_state ();
2875   int result = 1;
2876
2877   /* Trancate result limit to be smaller than the packet size.  */
2878   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2879       >= get_remote_packet_size ())
2880     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2881
2882   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2883   putpkt (rs->buf);
2884   getpkt (&rs->buf, &rs->buf_size, 0);
2885   if (*rs->buf == '\0')
2886     {
2887       /* Packet not supported.  */
2888       return -1;
2889     }
2890
2891   *result_count =
2892     parse_threadlist_response (rs->buf + 2, result_limit,
2893                                &rs->echo_nextthread, threadlist, done);
2894
2895   if (!threadmatch (&rs->echo_nextthread, nextthread))
2896     {
2897       /* FIXME: This is a good reason to drop the packet.  */
2898       /* Possably, there is a duplicate response.  */
2899       /* Possabilities :
2900          retransmit immediatly - race conditions
2901          retransmit after timeout - yes
2902          exit
2903          wait for packet, then exit
2904        */
2905       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2906       return 0;                 /* I choose simply exiting.  */
2907     }
2908   if (*result_count <= 0)
2909     {
2910       if (*done != 1)
2911         {
2912           warning (_("RMT ERROR : failed to get remote thread list."));
2913           result = 0;
2914         }
2915       return result;            /* break; */
2916     }
2917   if (*result_count > result_limit)
2918     {
2919       *result_count = 0;
2920       warning (_("RMT ERROR: threadlist response longer than requested."));
2921       return 0;
2922     }
2923   return result;
2924 }
2925
2926 /* Fetch the list of remote threads, with the qL packet, and call
2927    STEPFUNCTION for each thread found.  Stops iterating and returns 1
2928    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
2929    STEPFUNCTION returns false.  If the packet is not supported,
2930    returns -1.  */
2931
2932 static int
2933 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2934                             int looplimit)
2935 {
2936   struct remote_state *rs = get_remote_state ();
2937   int done, i, result_count;
2938   int startflag = 1;
2939   int result = 1;
2940   int loopcount = 0;
2941
2942   done = 0;
2943   while (!done)
2944     {
2945       if (loopcount++ > looplimit)
2946         {
2947           result = 0;
2948           warning (_("Remote fetch threadlist -infinite loop-."));
2949           break;
2950         }
2951       result = remote_get_threadlist (startflag, &rs->nextthread,
2952                                       MAXTHREADLISTRESULTS,
2953                                       &done, &result_count,
2954                                       rs->resultthreadlist);
2955       if (result <= 0)
2956         break;
2957       /* Clear for later iterations.  */
2958       startflag = 0;
2959       /* Setup to resume next batch of thread references, set nextthread.  */
2960       if (result_count >= 1)
2961         copy_threadref (&rs->nextthread,
2962                         &rs->resultthreadlist[result_count - 1]);
2963       i = 0;
2964       while (result_count--)
2965         {
2966           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2967             {
2968               result = 0;
2969               break;
2970             }
2971         }
2972     }
2973   return result;
2974 }
2975
2976 /* A thread found on the remote target.  */
2977
2978 typedef struct thread_item
2979 {
2980   /* The thread's PTID.  */
2981   ptid_t ptid;
2982
2983   /* The thread's extra info.  May be NULL.  */
2984   char *extra;
2985
2986   /* The thread's name.  May be NULL.  */
2987   char *name;
2988
2989   /* The core the thread was running on.  -1 if not known.  */
2990   int core;
2991 } thread_item_t;
2992 DEF_VEC_O(thread_item_t);
2993
2994 /* Context passed around to the various methods listing remote
2995    threads.  As new threads are found, they're added to the ITEMS
2996    vector.  */
2997
2998 struct threads_listing_context
2999 {
3000   /* The threads found on the remote target.  */
3001   VEC (thread_item_t) *items;
3002 };
3003
3004 /* Discard the contents of the constructed thread listing context.  */
3005
3006 static void
3007 clear_threads_listing_context (void *p)
3008 {
3009   struct threads_listing_context *context
3010     = (struct threads_listing_context *) p;
3011   int i;
3012   struct thread_item *item;
3013
3014   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3015     {
3016       xfree (item->extra);
3017       xfree (item->name);
3018     }
3019
3020   VEC_free (thread_item_t, context->items);
3021 }
3022
3023 /* Remove the thread specified as the related_pid field of WS
3024    from the CONTEXT list.  */
3025
3026 static void
3027 threads_listing_context_remove (struct target_waitstatus *ws,
3028                                 struct threads_listing_context *context)
3029 {
3030   struct thread_item *item;
3031   int i;
3032   ptid_t child_ptid = ws->value.related_pid;
3033
3034   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3035     {
3036       if (ptid_equal (item->ptid, child_ptid))
3037         {
3038           VEC_ordered_remove (thread_item_t, context->items, i);
3039           break;
3040         }
3041     }
3042 }
3043
3044 static int
3045 remote_newthread_step (threadref *ref, void *data)
3046 {
3047   struct threads_listing_context *context
3048     = (struct threads_listing_context *) data;
3049   struct thread_item item;
3050   int pid = ptid_get_pid (inferior_ptid);
3051
3052   item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3053   item.core = -1;
3054   item.name = NULL;
3055   item.extra = NULL;
3056
3057   VEC_safe_push (thread_item_t, context->items, &item);
3058
3059   return 1;                     /* continue iterator */
3060 }
3061
3062 #define CRAZY_MAX_THREADS 1000
3063
3064 static ptid_t
3065 remote_current_thread (ptid_t oldpid)
3066 {
3067   struct remote_state *rs = get_remote_state ();
3068
3069   putpkt ("qC");
3070   getpkt (&rs->buf, &rs->buf_size, 0);
3071   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3072     {
3073       char *obuf;
3074       ptid_t result;
3075
3076       result = read_ptid (&rs->buf[2], &obuf);
3077       if (*obuf != '\0' && remote_debug)
3078         fprintf_unfiltered (gdb_stdlog,
3079                             "warning: garbage in qC reply\n");
3080
3081       return result;
3082     }
3083   else
3084     return oldpid;
3085 }
3086
3087 /* List remote threads using the deprecated qL packet.  */
3088
3089 static int
3090 remote_get_threads_with_ql (struct target_ops *ops,
3091                             struct threads_listing_context *context)
3092 {
3093   if (remote_threadlist_iterator (remote_newthread_step, context,
3094                                   CRAZY_MAX_THREADS) >= 0)
3095     return 1;
3096
3097   return 0;
3098 }
3099
3100 #if defined(HAVE_LIBEXPAT)
3101
3102 static void
3103 start_thread (struct gdb_xml_parser *parser,
3104               const struct gdb_xml_element *element,
3105               void *user_data, VEC(gdb_xml_value_s) *attributes)
3106 {
3107   struct threads_listing_context *data
3108     = (struct threads_listing_context *) user_data;
3109
3110   struct thread_item item;
3111   char *id;
3112   struct gdb_xml_value *attr;
3113
3114   id = (char *) xml_find_attribute (attributes, "id")->value;
3115   item.ptid = read_ptid (id, NULL);
3116
3117   attr = xml_find_attribute (attributes, "core");
3118   if (attr != NULL)
3119     item.core = *(ULONGEST *) attr->value;
3120   else
3121     item.core = -1;
3122
3123   attr = xml_find_attribute (attributes, "name");
3124   item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3125
3126   item.extra = 0;
3127
3128   VEC_safe_push (thread_item_t, data->items, &item);
3129 }
3130
3131 static void
3132 end_thread (struct gdb_xml_parser *parser,
3133             const struct gdb_xml_element *element,
3134             void *user_data, const char *body_text)
3135 {
3136   struct threads_listing_context *data
3137     = (struct threads_listing_context *) user_data;
3138
3139   if (body_text && *body_text)
3140     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3141 }
3142
3143 const struct gdb_xml_attribute thread_attributes[] = {
3144   { "id", GDB_XML_AF_NONE, NULL, NULL },
3145   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3146   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3147   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3148 };
3149
3150 const struct gdb_xml_element thread_children[] = {
3151   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3152 };
3153
3154 const struct gdb_xml_element threads_children[] = {
3155   { "thread", thread_attributes, thread_children,
3156     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3157     start_thread, end_thread },
3158   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3159 };
3160
3161 const struct gdb_xml_element threads_elements[] = {
3162   { "threads", NULL, threads_children,
3163     GDB_XML_EF_NONE, NULL, NULL },
3164   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3165 };
3166
3167 #endif
3168
3169 /* List remote threads using qXfer:threads:read.  */
3170
3171 static int
3172 remote_get_threads_with_qxfer (struct target_ops *ops,
3173                                struct threads_listing_context *context)
3174 {
3175 #if defined(HAVE_LIBEXPAT)
3176   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3177     {
3178       char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3179       struct cleanup *back_to = make_cleanup (xfree, xml);
3180
3181       if (xml != NULL && *xml != '\0')
3182         {
3183           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3184                                threads_elements, xml, context);
3185         }
3186
3187       do_cleanups (back_to);
3188       return 1;
3189     }
3190 #endif
3191
3192   return 0;
3193 }
3194
3195 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3196
3197 static int
3198 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3199                                      struct threads_listing_context *context)
3200 {
3201   struct remote_state *rs = get_remote_state ();
3202
3203   if (rs->use_threadinfo_query)
3204     {
3205       char *bufp;
3206
3207       putpkt ("qfThreadInfo");
3208       getpkt (&rs->buf, &rs->buf_size, 0);
3209       bufp = rs->buf;
3210       if (bufp[0] != '\0')              /* q packet recognized */
3211         {
3212           while (*bufp++ == 'm')        /* reply contains one or more TID */
3213             {
3214               do
3215                 {
3216                   struct thread_item item;
3217
3218                   item.ptid = read_ptid (bufp, &bufp);
3219                   item.core = -1;
3220                   item.name = NULL;
3221                   item.extra = NULL;
3222
3223                   VEC_safe_push (thread_item_t, context->items, &item);
3224                 }
3225               while (*bufp++ == ',');   /* comma-separated list */
3226               putpkt ("qsThreadInfo");
3227               getpkt (&rs->buf, &rs->buf_size, 0);
3228               bufp = rs->buf;
3229             }
3230           return 1;
3231         }
3232       else
3233         {
3234           /* Packet not recognized.  */
3235           rs->use_threadinfo_query = 0;
3236         }
3237     }
3238
3239   return 0;
3240 }
3241
3242 /* Implement the to_update_thread_list function for the remote
3243    targets.  */
3244
3245 static void
3246 remote_update_thread_list (struct target_ops *ops)
3247 {
3248   struct threads_listing_context context;
3249   struct cleanup *old_chain;
3250   int got_list = 0;
3251
3252   context.items = NULL;
3253   old_chain = make_cleanup (clear_threads_listing_context, &context);
3254
3255   /* We have a few different mechanisms to fetch the thread list.  Try
3256      them all, starting with the most preferred one first, falling
3257      back to older methods.  */
3258   if (remote_get_threads_with_qxfer (ops, &context)
3259       || remote_get_threads_with_qthreadinfo (ops, &context)
3260       || remote_get_threads_with_ql (ops, &context))
3261     {
3262       int i;
3263       struct thread_item *item;
3264       struct thread_info *tp, *tmp;
3265
3266       got_list = 1;
3267
3268       if (VEC_empty (thread_item_t, context.items)
3269           && remote_thread_always_alive (ops, inferior_ptid))
3270         {
3271           /* Some targets don't really support threads, but still
3272              reply an (empty) thread list in response to the thread
3273              listing packets, instead of replying "packet not
3274              supported".  Exit early so we don't delete the main
3275              thread.  */
3276           do_cleanups (old_chain);
3277           return;
3278         }
3279
3280       /* CONTEXT now holds the current thread list on the remote
3281          target end.  Delete GDB-side threads no longer found on the
3282          target.  */
3283       ALL_THREADS_SAFE (tp, tmp)
3284         {
3285           for (i = 0;
3286                VEC_iterate (thread_item_t, context.items, i, item);
3287                ++i)
3288             {
3289               if (ptid_equal (item->ptid, tp->ptid))
3290                 break;
3291             }
3292
3293           if (i == VEC_length (thread_item_t, context.items))
3294             {
3295               /* Not found.  */
3296               delete_thread (tp->ptid);
3297             }
3298         }
3299
3300       /* Remove any unreported fork child threads from CONTEXT so
3301          that we don't interfere with follow fork, which is where
3302          creation of such threads is handled.  */
3303       remove_new_fork_children (&context);
3304
3305       /* And now add threads we don't know about yet to our list.  */
3306       for (i = 0;
3307            VEC_iterate (thread_item_t, context.items, i, item);
3308            ++i)
3309         {
3310           if (!ptid_equal (item->ptid, null_ptid))
3311             {
3312               struct private_thread_info *info;
3313               /* In non-stop mode, we assume new found threads are
3314                  executing until proven otherwise with a stop reply.
3315                  In all-stop, we can only get here if all threads are
3316                  stopped.  */
3317               int executing = target_is_non_stop_p () ? 1 : 0;
3318
3319               remote_notice_new_inferior (item->ptid, executing);
3320
3321               info = get_private_info_ptid (item->ptid);
3322               info->core = item->core;
3323               info->extra = item->extra;
3324               item->extra = NULL;
3325               info->name = item->name;
3326               item->name = NULL;
3327             }
3328         }
3329     }
3330
3331   if (!got_list)
3332     {
3333       /* If no thread listing method is supported, then query whether
3334          each known thread is alive, one by one, with the T packet.
3335          If the target doesn't support threads at all, then this is a
3336          no-op.  See remote_thread_alive.  */
3337       prune_threads ();
3338     }
3339
3340   do_cleanups (old_chain);
3341 }
3342
3343 /*
3344  * Collect a descriptive string about the given thread.
3345  * The target may say anything it wants to about the thread
3346  * (typically info about its blocked / runnable state, name, etc.).
3347  * This string will appear in the info threads display.
3348  *
3349  * Optional: targets are not required to implement this function.
3350  */
3351
3352 static char *
3353 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3354 {
3355   struct remote_state *rs = get_remote_state ();
3356   int result;
3357   int set;
3358   threadref id;
3359   struct gdb_ext_thread_info threadinfo;
3360   static char display_buf[100]; /* arbitrary...  */
3361   int n = 0;                    /* position in display_buf */
3362
3363   if (rs->remote_desc == 0)             /* paranoia */
3364     internal_error (__FILE__, __LINE__,
3365                     _("remote_threads_extra_info"));
3366
3367   if (ptid_equal (tp->ptid, magic_null_ptid)
3368       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3369     /* This is the main thread which was added by GDB.  The remote
3370        server doesn't know about it.  */
3371     return NULL;
3372
3373   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3374     {
3375       struct thread_info *info = find_thread_ptid (tp->ptid);
3376
3377       if (info && info->priv)
3378         return info->priv->extra;
3379       else
3380         return NULL;
3381     }
3382
3383   if (rs->use_threadextra_query)
3384     {
3385       char *b = rs->buf;
3386       char *endb = rs->buf + get_remote_packet_size ();
3387
3388       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3389       b += strlen (b);
3390       write_ptid (b, endb, tp->ptid);
3391
3392       putpkt (rs->buf);
3393       getpkt (&rs->buf, &rs->buf_size, 0);
3394       if (rs->buf[0] != 0)
3395         {
3396           n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3397           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3398           display_buf [result] = '\0';
3399           return display_buf;
3400         }
3401     }
3402
3403   /* If the above query fails, fall back to the old method.  */
3404   rs->use_threadextra_query = 0;
3405   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3406     | TAG_MOREDISPLAY | TAG_DISPLAY;
3407   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3408   if (remote_get_threadinfo (&id, set, &threadinfo))
3409     if (threadinfo.active)
3410       {
3411         if (*threadinfo.shortname)
3412           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3413                           " Name: %s,", threadinfo.shortname);
3414         if (*threadinfo.display)
3415           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3416                           " State: %s,", threadinfo.display);
3417         if (*threadinfo.more_display)
3418           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3419                           " Priority: %s", threadinfo.more_display);
3420
3421         if (n > 0)
3422           {
3423             /* For purely cosmetic reasons, clear up trailing commas.  */
3424             if (',' == display_buf[n-1])
3425               display_buf[n-1] = ' ';
3426             return display_buf;
3427           }
3428       }
3429   return NULL;
3430 }
3431 \f
3432
3433 static int
3434 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3435                                     struct static_tracepoint_marker *marker)
3436 {
3437   struct remote_state *rs = get_remote_state ();
3438   char *p = rs->buf;
3439
3440   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3441   p += strlen (p);
3442   p += hexnumstr (p, addr);
3443   putpkt (rs->buf);
3444   getpkt (&rs->buf, &rs->buf_size, 0);
3445   p = rs->buf;
3446
3447   if (*p == 'E')
3448     error (_("Remote failure reply: %s"), p);
3449
3450   if (*p++ == 'm')
3451     {
3452       parse_static_tracepoint_marker_definition (p, &p, marker);
3453       return 1;
3454     }
3455
3456   return 0;
3457 }
3458
3459 static VEC(static_tracepoint_marker_p) *
3460 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3461                                            const char *strid)
3462 {
3463   struct remote_state *rs = get_remote_state ();
3464   VEC(static_tracepoint_marker_p) *markers = NULL;
3465   struct static_tracepoint_marker *marker = NULL;
3466   struct cleanup *old_chain;
3467   char *p;
3468
3469   /* Ask for a first packet of static tracepoint marker
3470      definition.  */
3471   putpkt ("qTfSTM");
3472   getpkt (&rs->buf, &rs->buf_size, 0);
3473   p = rs->buf;
3474   if (*p == 'E')
3475     error (_("Remote failure reply: %s"), p);
3476
3477   old_chain = make_cleanup (free_current_marker, &marker);
3478
3479   while (*p++ == 'm')
3480     {
3481       if (marker == NULL)
3482         marker = XCNEW (struct static_tracepoint_marker);
3483
3484       do
3485         {
3486           parse_static_tracepoint_marker_definition (p, &p, marker);
3487
3488           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3489             {
3490               VEC_safe_push (static_tracepoint_marker_p,
3491                              markers, marker);
3492               marker = NULL;
3493             }
3494           else
3495             {
3496               release_static_tracepoint_marker (marker);
3497               memset (marker, 0, sizeof (*marker));
3498             }
3499         }
3500       while (*p++ == ',');      /* comma-separated list */
3501       /* Ask for another packet of static tracepoint definition.  */
3502       putpkt ("qTsSTM");
3503       getpkt (&rs->buf, &rs->buf_size, 0);
3504       p = rs->buf;
3505     }
3506
3507   do_cleanups (old_chain);
3508   return markers;
3509 }
3510
3511 \f
3512 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3513
3514 static ptid_t
3515 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3516 {
3517   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3518 }
3519 \f
3520
3521 /* Restart the remote side; this is an extended protocol operation.  */
3522
3523 static void
3524 extended_remote_restart (void)
3525 {
3526   struct remote_state *rs = get_remote_state ();
3527
3528   /* Send the restart command; for reasons I don't understand the
3529      remote side really expects a number after the "R".  */
3530   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3531   putpkt (rs->buf);
3532
3533   remote_fileio_reset ();
3534 }
3535 \f
3536 /* Clean up connection to a remote debugger.  */
3537
3538 static void
3539 remote_close (struct target_ops *self)
3540 {
3541   struct remote_state *rs = get_remote_state ();
3542
3543   if (rs->remote_desc == NULL)
3544     return; /* already closed */
3545
3546   /* Make sure we leave stdin registered in the event loop.  */
3547   remote_terminal_ours (self);
3548
3549   serial_close (rs->remote_desc);
3550   rs->remote_desc = NULL;
3551
3552   /* We don't have a connection to the remote stub anymore.  Get rid
3553      of all the inferiors and their threads we were controlling.
3554      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3555      will be unable to find the thread corresponding to (pid, 0, 0).  */
3556   inferior_ptid = null_ptid;
3557   discard_all_inferiors ();
3558
3559   /* We are closing the remote target, so we should discard
3560      everything of this target.  */
3561   discard_pending_stop_replies_in_queue (rs);
3562
3563   if (remote_async_inferior_event_token)
3564     delete_async_event_handler (&remote_async_inferior_event_token);
3565
3566   remote_notif_state_xfree (rs->notif_state);
3567
3568   trace_reset_local_state ();
3569 }
3570
3571 /* Query the remote side for the text, data and bss offsets.  */
3572
3573 static void
3574 get_offsets (void)
3575 {
3576   struct remote_state *rs = get_remote_state ();
3577   char *buf;
3578   char *ptr;
3579   int lose, num_segments = 0, do_sections, do_segments;
3580   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3581   struct section_offsets *offs;
3582   struct symfile_segment_data *data;
3583
3584   if (symfile_objfile == NULL)
3585     return;
3586
3587   putpkt ("qOffsets");
3588   getpkt (&rs->buf, &rs->buf_size, 0);
3589   buf = rs->buf;
3590
3591   if (buf[0] == '\000')
3592     return;                     /* Return silently.  Stub doesn't support
3593                                    this command.  */
3594   if (buf[0] == 'E')
3595     {
3596       warning (_("Remote failure reply: %s"), buf);
3597       return;
3598     }
3599
3600   /* Pick up each field in turn.  This used to be done with scanf, but
3601      scanf will make trouble if CORE_ADDR size doesn't match
3602      conversion directives correctly.  The following code will work
3603      with any size of CORE_ADDR.  */
3604   text_addr = data_addr = bss_addr = 0;
3605   ptr = buf;
3606   lose = 0;
3607
3608   if (startswith (ptr, "Text="))
3609     {
3610       ptr += 5;
3611       /* Don't use strtol, could lose on big values.  */
3612       while (*ptr && *ptr != ';')
3613         text_addr = (text_addr << 4) + fromhex (*ptr++);
3614
3615       if (startswith (ptr, ";Data="))
3616         {
3617           ptr += 6;
3618           while (*ptr && *ptr != ';')
3619             data_addr = (data_addr << 4) + fromhex (*ptr++);
3620         }
3621       else
3622         lose = 1;
3623
3624       if (!lose && startswith (ptr, ";Bss="))
3625         {
3626           ptr += 5;
3627           while (*ptr && *ptr != ';')
3628             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3629
3630           if (bss_addr != data_addr)
3631             warning (_("Target reported unsupported offsets: %s"), buf);
3632         }
3633       else
3634         lose = 1;
3635     }
3636   else if (startswith (ptr, "TextSeg="))
3637     {
3638       ptr += 8;
3639       /* Don't use strtol, could lose on big values.  */
3640       while (*ptr && *ptr != ';')
3641         text_addr = (text_addr << 4) + fromhex (*ptr++);
3642       num_segments = 1;
3643
3644       if (startswith (ptr, ";DataSeg="))
3645         {
3646           ptr += 9;
3647           while (*ptr && *ptr != ';')
3648             data_addr = (data_addr << 4) + fromhex (*ptr++);
3649           num_segments++;
3650         }
3651     }
3652   else
3653     lose = 1;
3654
3655   if (lose)
3656     error (_("Malformed response to offset query, %s"), buf);
3657   else if (*ptr != '\0')
3658     warning (_("Target reported unsupported offsets: %s"), buf);
3659
3660   offs = ((struct section_offsets *)
3661           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3662   memcpy (offs, symfile_objfile->section_offsets,
3663           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3664
3665   data = get_symfile_segment_data (symfile_objfile->obfd);
3666   do_segments = (data != NULL);
3667   do_sections = num_segments == 0;
3668
3669   if (num_segments > 0)
3670     {
3671       segments[0] = text_addr;
3672       segments[1] = data_addr;
3673     }
3674   /* If we have two segments, we can still try to relocate everything
3675      by assuming that the .text and .data offsets apply to the whole
3676      text and data segments.  Convert the offsets given in the packet
3677      to base addresses for symfile_map_offsets_to_segments.  */
3678   else if (data && data->num_segments == 2)
3679     {
3680       segments[0] = data->segment_bases[0] + text_addr;
3681       segments[1] = data->segment_bases[1] + data_addr;
3682       num_segments = 2;
3683     }
3684   /* If the object file has only one segment, assume that it is text
3685      rather than data; main programs with no writable data are rare,
3686      but programs with no code are useless.  Of course the code might
3687      have ended up in the data segment... to detect that we would need
3688      the permissions here.  */
3689   else if (data && data->num_segments == 1)
3690     {
3691       segments[0] = data->segment_bases[0] + text_addr;
3692       num_segments = 1;
3693     }
3694   /* There's no way to relocate by segment.  */
3695   else
3696     do_segments = 0;
3697
3698   if (do_segments)
3699     {
3700       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3701                                                  offs, num_segments, segments);
3702
3703       if (ret == 0 && !do_sections)
3704         error (_("Can not handle qOffsets TextSeg "
3705                  "response with this symbol file"));
3706
3707       if (ret > 0)
3708         do_sections = 0;
3709     }
3710
3711   if (data)
3712     free_symfile_segment_data (data);
3713
3714   if (do_sections)
3715     {
3716       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3717
3718       /* This is a temporary kludge to force data and bss to use the
3719          same offsets because that's what nlmconv does now.  The real
3720          solution requires changes to the stub and remote.c that I
3721          don't have time to do right now.  */
3722
3723       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3724       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3725     }
3726
3727   objfile_relocate (symfile_objfile, offs);
3728 }
3729
3730 /* Send interrupt_sequence to remote target.  */
3731 static void
3732 send_interrupt_sequence (void)
3733 {
3734   struct remote_state *rs = get_remote_state ();
3735
3736   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3737     remote_serial_write ("\x03", 1);
3738   else if (interrupt_sequence_mode == interrupt_sequence_break)
3739     serial_send_break (rs->remote_desc);
3740   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3741     {
3742       serial_send_break (rs->remote_desc);
3743       remote_serial_write ("g", 1);
3744     }
3745   else
3746     internal_error (__FILE__, __LINE__,
3747                     _("Invalid value for interrupt_sequence_mode: %s."),
3748                     interrupt_sequence_mode);
3749 }
3750
3751
3752 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3753    and extract the PTID.  Returns NULL_PTID if not found.  */
3754
3755 static ptid_t
3756 stop_reply_extract_thread (char *stop_reply)
3757 {
3758   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3759     {
3760       char *p;
3761
3762       /* Txx r:val ; r:val (...)  */
3763       p = &stop_reply[3];
3764
3765       /* Look for "register" named "thread".  */
3766       while (*p != '\0')
3767         {
3768           char *p1;
3769
3770           p1 = strchr (p, ':');
3771           if (p1 == NULL)
3772             return null_ptid;
3773
3774           if (strncmp (p, "thread", p1 - p) == 0)
3775             return read_ptid (++p1, &p);
3776
3777           p1 = strchr (p, ';');
3778           if (p1 == NULL)
3779             return null_ptid;
3780           p1++;
3781
3782           p = p1;
3783         }
3784     }
3785
3786   return null_ptid;
3787 }
3788
3789 /* Determine the remote side's current thread.  If we have a stop
3790    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3791    "thread" register we can extract the current thread from.  If not,
3792    ask the remote which is the current thread with qC.  The former
3793    method avoids a roundtrip.  */
3794
3795 static ptid_t
3796 get_current_thread (char *wait_status)
3797 {
3798   ptid_t ptid = null_ptid;
3799
3800   /* Note we don't use remote_parse_stop_reply as that makes use of
3801      the target architecture, which we haven't yet fully determined at
3802      this point.  */
3803   if (wait_status != NULL)
3804     ptid = stop_reply_extract_thread (wait_status);
3805   if (ptid_equal (ptid, null_ptid))
3806     ptid = remote_current_thread (inferior_ptid);
3807
3808   return ptid;
3809 }
3810
3811 /* Query the remote target for which is the current thread/process,
3812    add it to our tables, and update INFERIOR_PTID.  The caller is
3813    responsible for setting the state such that the remote end is ready
3814    to return the current thread.
3815
3816    This function is called after handling the '?' or 'vRun' packets,
3817    whose response is a stop reply from which we can also try
3818    extracting the thread.  If the target doesn't support the explicit
3819    qC query, we infer the current thread from that stop reply, passed
3820    in in WAIT_STATUS, which may be NULL.  */
3821
3822 static void
3823 add_current_inferior_and_thread (char *wait_status)
3824 {
3825   struct remote_state *rs = get_remote_state ();
3826   int fake_pid_p = 0;
3827   ptid_t ptid;
3828
3829   inferior_ptid = null_ptid;
3830
3831   /* Now, if we have thread information, update inferior_ptid.  */
3832   ptid = get_current_thread (wait_status);
3833
3834   if (!ptid_equal (ptid, null_ptid))
3835     {
3836       if (!remote_multi_process_p (rs))
3837         fake_pid_p = 1;
3838
3839       inferior_ptid = ptid;
3840     }
3841   else
3842     {
3843       /* Without this, some commands which require an active target
3844          (such as kill) won't work.  This variable serves (at least)
3845          double duty as both the pid of the target process (if it has
3846          such), and as a flag indicating that a target is active.  */
3847       inferior_ptid = magic_null_ptid;
3848       fake_pid_p = 1;
3849     }
3850
3851   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3852
3853   /* Add the main thread.  */
3854   add_thread_silent (inferior_ptid);
3855 }
3856
3857 /* Print info about a thread that was found already stopped on
3858    connection.  */
3859
3860 static void
3861 print_one_stopped_thread (struct thread_info *thread)
3862 {
3863   struct target_waitstatus *ws = &thread->suspend.waitstatus;
3864
3865   switch_to_thread (thread->ptid);
3866   stop_pc = get_frame_pc (get_current_frame ());
3867   set_current_sal_from_frame (get_current_frame ());
3868
3869   thread->suspend.waitstatus_pending_p = 0;
3870
3871   if (ws->kind == TARGET_WAITKIND_STOPPED)
3872     {
3873       enum gdb_signal sig = ws->value.sig;
3874
3875       if (signal_print_state (sig))
3876         observer_notify_signal_received (sig);
3877     }
3878   observer_notify_normal_stop (NULL, 1);
3879 }
3880
3881 /* Process all initial stop replies the remote side sent in response
3882    to the ? packet.  These indicate threads that were already stopped
3883    on initial connection.  We mark these threads as stopped and print
3884    their current frame before giving the user the prompt.  */
3885
3886 static void
3887 process_initial_stop_replies (int from_tty)
3888 {
3889   int pending_stop_replies = stop_reply_queue_length ();
3890   struct inferior *inf;
3891   struct thread_info *thread;
3892   struct thread_info *selected = NULL;
3893   struct thread_info *lowest_stopped = NULL;
3894   struct thread_info *first = NULL;
3895
3896   /* Consume the initial pending events.  */
3897   while (pending_stop_replies-- > 0)
3898     {
3899       ptid_t waiton_ptid = minus_one_ptid;
3900       ptid_t event_ptid;
3901       struct target_waitstatus ws;
3902       int ignore_event = 0;
3903       struct thread_info *thread;
3904
3905       memset (&ws, 0, sizeof (ws));
3906       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3907       if (remote_debug)
3908         print_target_wait_results (waiton_ptid, event_ptid, &ws);
3909
3910       switch (ws.kind)
3911         {
3912         case TARGET_WAITKIND_IGNORE:
3913         case TARGET_WAITKIND_NO_RESUMED:
3914         case TARGET_WAITKIND_SIGNALLED:
3915         case TARGET_WAITKIND_EXITED:
3916           /* We shouldn't see these, but if we do, just ignore.  */
3917           if (remote_debug)
3918             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3919           ignore_event = 1;
3920           break;
3921
3922         case TARGET_WAITKIND_EXECD:
3923           xfree (ws.value.execd_pathname);
3924           break;
3925         default:
3926           break;
3927         }
3928
3929       if (ignore_event)
3930         continue;
3931
3932       thread = find_thread_ptid (event_ptid);
3933
3934       if (ws.kind == TARGET_WAITKIND_STOPPED)
3935         {
3936           enum gdb_signal sig = ws.value.sig;
3937
3938           /* Stubs traditionally report SIGTRAP as initial signal,
3939              instead of signal 0.  Suppress it.  */
3940           if (sig == GDB_SIGNAL_TRAP)
3941             sig = GDB_SIGNAL_0;
3942           thread->suspend.stop_signal = sig;
3943           ws.value.sig = sig;
3944         }
3945
3946       thread->suspend.waitstatus = ws;
3947
3948       if (ws.kind != TARGET_WAITKIND_STOPPED
3949           || ws.value.sig != GDB_SIGNAL_0)
3950         thread->suspend.waitstatus_pending_p = 1;
3951
3952       set_executing (event_ptid, 0);
3953       set_running (event_ptid, 0);
3954       thread->priv->vcont_resumed = 0;
3955     }
3956
3957   /* "Notice" the new inferiors before anything related to
3958      registers/memory.  */
3959   ALL_INFERIORS (inf)
3960     {
3961       if (inf->pid == 0)
3962         continue;
3963
3964       inf->needs_setup = 1;
3965
3966       if (non_stop)
3967         {
3968           thread = any_live_thread_of_process (inf->pid);
3969           notice_new_inferior (thread->ptid,
3970                                thread->state == THREAD_RUNNING,
3971                                from_tty);
3972         }
3973     }
3974
3975   /* If all-stop on top of non-stop, pause all threads.  Note this
3976      records the threads' stop pc, so must be done after "noticing"
3977      the inferiors.  */
3978   if (!non_stop)
3979     {
3980       stop_all_threads ();
3981
3982       /* If all threads of an inferior were already stopped, we
3983          haven't setup the inferior yet.  */
3984       ALL_INFERIORS (inf)
3985         {
3986           if (inf->pid == 0)
3987             continue;
3988
3989           if (inf->needs_setup)
3990             {
3991               thread = any_live_thread_of_process (inf->pid);
3992               switch_to_thread_no_regs (thread);
3993               setup_inferior (0);
3994             }
3995         }
3996     }
3997
3998   /* Now go over all threads that are stopped, and print their current
3999      frame.  If all-stop, then if there's a signalled thread, pick
4000      that as current.  */
4001   ALL_NON_EXITED_THREADS (thread)
4002     {
4003       if (first == NULL)
4004         first = thread;
4005
4006       if (!non_stop)
4007         set_running (thread->ptid, 0);
4008       else if (thread->state != THREAD_STOPPED)
4009         continue;
4010
4011       if (selected == NULL
4012           && thread->suspend.waitstatus_pending_p)
4013         selected = thread;
4014
4015       if (lowest_stopped == NULL
4016           || thread->inf->num < lowest_stopped->inf->num
4017           || thread->per_inf_num < lowest_stopped->per_inf_num)
4018         lowest_stopped = thread;
4019
4020       if (non_stop)
4021         print_one_stopped_thread (thread);
4022     }
4023
4024   /* In all-stop, we only print the status of one thread, and leave
4025      others with their status pending.  */
4026   if (!non_stop)
4027     {
4028       thread = selected;
4029       if (thread == NULL)
4030         thread = lowest_stopped;
4031       if (thread == NULL)
4032         thread = first;
4033
4034       print_one_stopped_thread (thread);
4035     }
4036
4037   /* For "info program".  */
4038   thread = inferior_thread ();
4039   if (thread->state == THREAD_STOPPED)
4040     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4041 }
4042
4043 /* Start the remote connection and sync state.  */
4044
4045 static void
4046 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4047 {
4048   struct remote_state *rs = get_remote_state ();
4049   struct packet_config *noack_config;
4050   char *wait_status = NULL;
4051
4052   /* Signal other parts that we're going through the initial setup,
4053      and so things may not be stable yet.  E.g., we don't try to
4054      install tracepoints until we've relocated symbols.  Also, a
4055      Ctrl-C before we're connected and synced up can't interrupt the
4056      target.  Instead, it offers to drop the (potentially wedged)
4057      connection.  */
4058   rs->starting_up = 1;
4059
4060   QUIT;
4061
4062   if (interrupt_on_connect)
4063     send_interrupt_sequence ();
4064
4065   /* Ack any packet which the remote side has already sent.  */
4066   remote_serial_write ("+", 1);
4067
4068   /* The first packet we send to the target is the optional "supported
4069      packets" request.  If the target can answer this, it will tell us
4070      which later probes to skip.  */
4071   remote_query_supported ();
4072
4073   /* If the stub wants to get a QAllow, compose one and send it.  */
4074   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4075     remote_set_permissions (target);
4076
4077   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4078      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
4079      as a reply to known packet.  For packet "vFile:setfs:" it is an
4080      invalid reply and GDB would return error in
4081      remote_hostio_set_filesystem, making remote files access impossible.
4082      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
4083      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
4084   {
4085     const char v_mustreplyempty[] = "vMustReplyEmpty";
4086
4087     putpkt (v_mustreplyempty);
4088     getpkt (&rs->buf, &rs->buf_size, 0);
4089     if (strcmp (rs->buf, "OK") == 0)
4090       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4091     else if (strcmp (rs->buf, "") != 0)
4092       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4093              rs->buf);
4094   }
4095
4096   /* Next, we possibly activate noack mode.
4097
4098      If the QStartNoAckMode packet configuration is set to AUTO,
4099      enable noack mode if the stub reported a wish for it with
4100      qSupported.
4101
4102      If set to TRUE, then enable noack mode even if the stub didn't
4103      report it in qSupported.  If the stub doesn't reply OK, the
4104      session ends with an error.
4105
4106      If FALSE, then don't activate noack mode, regardless of what the
4107      stub claimed should be the default with qSupported.  */
4108
4109   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4110   if (packet_config_support (noack_config) != PACKET_DISABLE)
4111     {
4112       putpkt ("QStartNoAckMode");
4113       getpkt (&rs->buf, &rs->buf_size, 0);
4114       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4115         rs->noack_mode = 1;
4116     }
4117
4118   if (extended_p)
4119     {
4120       /* Tell the remote that we are using the extended protocol.  */
4121       putpkt ("!");
4122       getpkt (&rs->buf, &rs->buf_size, 0);
4123     }
4124
4125   /* Let the target know which signals it is allowed to pass down to
4126      the program.  */
4127   update_signals_program_target ();
4128
4129   /* Next, if the target can specify a description, read it.  We do
4130      this before anything involving memory or registers.  */
4131   target_find_description ();
4132
4133   /* Next, now that we know something about the target, update the
4134      address spaces in the program spaces.  */
4135   update_address_spaces ();
4136
4137   /* On OSs where the list of libraries is global to all
4138      processes, we fetch them early.  */
4139   if (gdbarch_has_global_solist (target_gdbarch ()))
4140     solib_add (NULL, from_tty, target, auto_solib_add);
4141
4142   if (target_is_non_stop_p ())
4143     {
4144       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4145         error (_("Non-stop mode requested, but remote "
4146                  "does not support non-stop"));
4147
4148       putpkt ("QNonStop:1");
4149       getpkt (&rs->buf, &rs->buf_size, 0);
4150
4151       if (strcmp (rs->buf, "OK") != 0)
4152         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4153
4154       /* Find about threads and processes the stub is already
4155          controlling.  We default to adding them in the running state.
4156          The '?' query below will then tell us about which threads are
4157          stopped.  */
4158       remote_update_thread_list (target);
4159     }
4160   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4161     {
4162       /* Don't assume that the stub can operate in all-stop mode.
4163          Request it explicitly.  */
4164       putpkt ("QNonStop:0");
4165       getpkt (&rs->buf, &rs->buf_size, 0);
4166
4167       if (strcmp (rs->buf, "OK") != 0)
4168         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4169     }
4170
4171   /* Upload TSVs regardless of whether the target is running or not.  The
4172      remote stub, such as GDBserver, may have some predefined or builtin
4173      TSVs, even if the target is not running.  */
4174   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4175     {
4176       struct uploaded_tsv *uploaded_tsvs = NULL;
4177
4178       remote_upload_trace_state_variables (target, &uploaded_tsvs);
4179       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4180     }
4181
4182   /* Check whether the target is running now.  */
4183   putpkt ("?");
4184   getpkt (&rs->buf, &rs->buf_size, 0);
4185
4186   if (!target_is_non_stop_p ())
4187     {
4188       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4189         {
4190           if (!extended_p)
4191             error (_("The target is not running (try extended-remote?)"));
4192
4193           /* We're connected, but not running.  Drop out before we
4194              call start_remote.  */
4195           rs->starting_up = 0;
4196           return;
4197         }
4198       else
4199         {
4200           /* Save the reply for later.  */
4201           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4202           strcpy (wait_status, rs->buf);
4203         }
4204
4205       /* Fetch thread list.  */
4206       target_update_thread_list ();
4207
4208       /* Let the stub know that we want it to return the thread.  */
4209       set_continue_thread (minus_one_ptid);
4210
4211       if (thread_count () == 0)
4212         {
4213           /* Target has no concept of threads at all.  GDB treats
4214              non-threaded target as single-threaded; add a main
4215              thread.  */
4216           add_current_inferior_and_thread (wait_status);
4217         }
4218       else
4219         {
4220           /* We have thread information; select the thread the target
4221              says should be current.  If we're reconnecting to a
4222              multi-threaded program, this will ideally be the thread
4223              that last reported an event before GDB disconnected.  */
4224           inferior_ptid = get_current_thread (wait_status);
4225           if (ptid_equal (inferior_ptid, null_ptid))
4226             {
4227               /* Odd... The target was able to list threads, but not
4228                  tell us which thread was current (no "thread"
4229                  register in T stop reply?).  Just pick the first
4230                  thread in the thread list then.  */
4231               
4232               if (remote_debug)
4233                 fprintf_unfiltered (gdb_stdlog,
4234                                     "warning: couldn't determine remote "
4235                                     "current thread; picking first in list.\n");
4236
4237               inferior_ptid = thread_list->ptid;
4238             }
4239         }
4240
4241       /* init_wait_for_inferior should be called before get_offsets in order
4242          to manage `inserted' flag in bp loc in a correct state.
4243          breakpoint_init_inferior, called from init_wait_for_inferior, set
4244          `inserted' flag to 0, while before breakpoint_re_set, called from
4245          start_remote, set `inserted' flag to 1.  In the initialization of
4246          inferior, breakpoint_init_inferior should be called first, and then
4247          breakpoint_re_set can be called.  If this order is broken, state of
4248          `inserted' flag is wrong, and cause some problems on breakpoint
4249          manipulation.  */
4250       init_wait_for_inferior ();
4251
4252       get_offsets ();           /* Get text, data & bss offsets.  */
4253
4254       /* If we could not find a description using qXfer, and we know
4255          how to do it some other way, try again.  This is not
4256          supported for non-stop; it could be, but it is tricky if
4257          there are no stopped threads when we connect.  */
4258       if (remote_read_description_p (target)
4259           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4260         {
4261           target_clear_description ();
4262           target_find_description ();
4263         }
4264
4265       /* Use the previously fetched status.  */
4266       gdb_assert (wait_status != NULL);
4267       strcpy (rs->buf, wait_status);
4268       rs->cached_wait_status = 1;
4269
4270       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4271     }
4272   else
4273     {
4274       /* Clear WFI global state.  Do this before finding about new
4275          threads and inferiors, and setting the current inferior.
4276          Otherwise we would clear the proceed status of the current
4277          inferior when we want its stop_soon state to be preserved
4278          (see notice_new_inferior).  */
4279       init_wait_for_inferior ();
4280
4281       /* In non-stop, we will either get an "OK", meaning that there
4282          are no stopped threads at this time; or, a regular stop
4283          reply.  In the latter case, there may be more than one thread
4284          stopped --- we pull them all out using the vStopped
4285          mechanism.  */
4286       if (strcmp (rs->buf, "OK") != 0)
4287         {
4288           struct notif_client *notif = &notif_client_stop;
4289
4290           /* remote_notif_get_pending_replies acks this one, and gets
4291              the rest out.  */
4292           rs->notif_state->pending_event[notif_client_stop.id]
4293             = remote_notif_parse (notif, rs->buf);
4294           remote_notif_get_pending_events (notif);
4295         }
4296
4297       if (thread_count () == 0)
4298         {
4299           if (!extended_p)
4300             error (_("The target is not running (try extended-remote?)"));
4301
4302           /* We're connected, but not running.  Drop out before we
4303              call start_remote.  */
4304           rs->starting_up = 0;
4305           return;
4306         }
4307
4308       /* In non-stop mode, any cached wait status will be stored in
4309          the stop reply queue.  */
4310       gdb_assert (wait_status == NULL);
4311
4312       /* Report all signals during attach/startup.  */
4313       remote_pass_signals (target, 0, NULL);
4314
4315       /* If there are already stopped threads, mark them stopped and
4316          report their stops before giving the prompt to the user.  */
4317       process_initial_stop_replies (from_tty);
4318
4319       if (target_can_async_p ())
4320         target_async (1);
4321     }
4322
4323   /* If we connected to a live target, do some additional setup.  */
4324   if (target_has_execution)
4325     {
4326       if (symfile_objfile)      /* No use without a symbol-file.  */
4327         remote_check_symbols ();
4328     }
4329
4330   /* Possibly the target has been engaged in a trace run started
4331      previously; find out where things are at.  */
4332   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4333     {
4334       struct uploaded_tp *uploaded_tps = NULL;
4335
4336       if (current_trace_status ()->running)
4337         printf_filtered (_("Trace is already running on the target.\n"));
4338
4339       remote_upload_tracepoints (target, &uploaded_tps);
4340
4341       merge_uploaded_tracepoints (&uploaded_tps);
4342     }
4343
4344   /* Possibly the target has been engaged in a btrace record started
4345      previously; find out where things are at.  */
4346   remote_btrace_maybe_reopen ();
4347
4348   /* The thread and inferior lists are now synchronized with the
4349      target, our symbols have been relocated, and we're merged the
4350      target's tracepoints with ours.  We're done with basic start
4351      up.  */
4352   rs->starting_up = 0;
4353
4354   /* Maybe breakpoints are global and need to be inserted now.  */
4355   if (breakpoints_should_be_inserted_now ())
4356     insert_breakpoints ();
4357 }
4358
4359 /* Open a connection to a remote debugger.
4360    NAME is the filename used for communication.  */
4361
4362 static void
4363 remote_open (const char *name, int from_tty)
4364 {
4365   remote_open_1 (name, from_tty, &remote_ops, 0);
4366 }
4367
4368 /* Open a connection to a remote debugger using the extended
4369    remote gdb protocol.  NAME is the filename used for communication.  */
4370
4371 static void
4372 extended_remote_open (const char *name, int from_tty)
4373 {
4374   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4375 }
4376
4377 /* Reset all packets back to "unknown support".  Called when opening a
4378    new connection to a remote target.  */
4379
4380 static void
4381 reset_all_packet_configs_support (void)
4382 {
4383   int i;
4384
4385   for (i = 0; i < PACKET_MAX; i++)
4386     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4387 }
4388
4389 /* Initialize all packet configs.  */
4390
4391 static void
4392 init_all_packet_configs (void)
4393 {
4394   int i;
4395
4396   for (i = 0; i < PACKET_MAX; i++)
4397     {
4398       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4399       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4400     }
4401 }
4402
4403 /* Symbol look-up.  */
4404
4405 static void
4406 remote_check_symbols (void)
4407 {
4408   struct remote_state *rs = get_remote_state ();
4409   char *msg, *reply, *tmp;
4410   int end;
4411   long reply_size;
4412   struct cleanup *old_chain;
4413
4414   /* The remote side has no concept of inferiors that aren't running
4415      yet, it only knows about running processes.  If we're connected
4416      but our current inferior is not running, we should not invite the
4417      remote target to request symbol lookups related to its
4418      (unrelated) current process.  */
4419   if (!target_has_execution)
4420     return;
4421
4422   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4423     return;
4424
4425   /* Make sure the remote is pointing at the right process.  Note
4426      there's no way to select "no process".  */
4427   set_general_process ();
4428
4429   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4430      because we need both at the same time.  */
4431   msg = (char *) xmalloc (get_remote_packet_size ());
4432   old_chain = make_cleanup (xfree, msg);
4433   reply = (char *) xmalloc (get_remote_packet_size ());
4434   make_cleanup (free_current_contents, &reply);
4435   reply_size = get_remote_packet_size ();
4436
4437   /* Invite target to request symbol lookups.  */
4438
4439   putpkt ("qSymbol::");
4440   getpkt (&reply, &reply_size, 0);
4441   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4442
4443   while (startswith (reply, "qSymbol:"))
4444     {
4445       struct bound_minimal_symbol sym;
4446
4447       tmp = &reply[8];
4448       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4449       msg[end] = '\0';
4450       sym = lookup_minimal_symbol (msg, NULL, NULL);
4451       if (sym.minsym == NULL)
4452         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4453       else
4454         {
4455           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4456           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4457
4458           /* If this is a function address, return the start of code
4459              instead of any data function descriptor.  */
4460           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4461                                                          sym_addr,
4462                                                          &current_target);
4463
4464           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4465                      phex_nz (sym_addr, addr_size), &reply[8]);
4466         }
4467   
4468       putpkt (msg);
4469       getpkt (&reply, &reply_size, 0);
4470     }
4471
4472   do_cleanups (old_chain);
4473 }
4474
4475 static struct serial *
4476 remote_serial_open (const char *name)
4477 {
4478   static int udp_warning = 0;
4479
4480   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4481      of in ser-tcp.c, because it is the remote protocol assuming that the
4482      serial connection is reliable and not the serial connection promising
4483      to be.  */
4484   if (!udp_warning && startswith (name, "udp:"))
4485     {
4486       warning (_("The remote protocol may be unreliable over UDP.\n"
4487                  "Some events may be lost, rendering further debugging "
4488                  "impossible."));
4489       udp_warning = 1;
4490     }
4491
4492   return serial_open (name);
4493 }
4494
4495 /* Inform the target of our permission settings.  The permission flags
4496    work without this, but if the target knows the settings, it can do
4497    a couple things.  First, it can add its own check, to catch cases
4498    that somehow manage to get by the permissions checks in target
4499    methods.  Second, if the target is wired to disallow particular
4500    settings (for instance, a system in the field that is not set up to
4501    be able to stop at a breakpoint), it can object to any unavailable
4502    permissions.  */
4503
4504 void
4505 remote_set_permissions (struct target_ops *self)
4506 {
4507   struct remote_state *rs = get_remote_state ();
4508
4509   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4510              "WriteReg:%x;WriteMem:%x;"
4511              "InsertBreak:%x;InsertTrace:%x;"
4512              "InsertFastTrace:%x;Stop:%x",
4513              may_write_registers, may_write_memory,
4514              may_insert_breakpoints, may_insert_tracepoints,
4515              may_insert_fast_tracepoints, may_stop);
4516   putpkt (rs->buf);
4517   getpkt (&rs->buf, &rs->buf_size, 0);
4518
4519   /* If the target didn't like the packet, warn the user.  Do not try
4520      to undo the user's settings, that would just be maddening.  */
4521   if (strcmp (rs->buf, "OK") != 0)
4522     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4523 }
4524
4525 /* This type describes each known response to the qSupported
4526    packet.  */
4527 struct protocol_feature
4528 {
4529   /* The name of this protocol feature.  */
4530   const char *name;
4531
4532   /* The default for this protocol feature.  */
4533   enum packet_support default_support;
4534
4535   /* The function to call when this feature is reported, or after
4536      qSupported processing if the feature is not supported.
4537      The first argument points to this structure.  The second
4538      argument indicates whether the packet requested support be
4539      enabled, disabled, or probed (or the default, if this function
4540      is being called at the end of processing and this feature was
4541      not reported).  The third argument may be NULL; if not NULL, it
4542      is a NUL-terminated string taken from the packet following
4543      this feature's name and an equals sign.  */
4544   void (*func) (const struct protocol_feature *, enum packet_support,
4545                 const char *);
4546
4547   /* The corresponding packet for this feature.  Only used if
4548      FUNC is remote_supported_packet.  */
4549   int packet;
4550 };
4551
4552 static void
4553 remote_supported_packet (const struct protocol_feature *feature,
4554                          enum packet_support support,
4555                          const char *argument)
4556 {
4557   if (argument)
4558     {
4559       warning (_("Remote qSupported response supplied an unexpected value for"
4560                  " \"%s\"."), feature->name);
4561       return;
4562     }
4563
4564   remote_protocol_packets[feature->packet].support = support;
4565 }
4566
4567 static void
4568 remote_packet_size (const struct protocol_feature *feature,
4569                     enum packet_support support, const char *value)
4570 {
4571   struct remote_state *rs = get_remote_state ();
4572
4573   int packet_size;
4574   char *value_end;
4575
4576   if (support != PACKET_ENABLE)
4577     return;
4578
4579   if (value == NULL || *value == '\0')
4580     {
4581       warning (_("Remote target reported \"%s\" without a size."),
4582                feature->name);
4583       return;
4584     }
4585
4586   errno = 0;
4587   packet_size = strtol (value, &value_end, 16);
4588   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4589     {
4590       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4591                feature->name, value);
4592       return;
4593     }
4594
4595   /* Record the new maximum packet size.  */
4596   rs->explicit_packet_size = packet_size;
4597 }
4598
4599 static const struct protocol_feature remote_protocol_features[] = {
4600   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4601   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4602     PACKET_qXfer_auxv },
4603   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4604     PACKET_qXfer_exec_file },
4605   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4606     PACKET_qXfer_features },
4607   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4608     PACKET_qXfer_libraries },
4609   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4610     PACKET_qXfer_libraries_svr4 },
4611   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4612     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4613   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4614     PACKET_qXfer_memory_map },
4615   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4616     PACKET_qXfer_spu_read },
4617   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4618     PACKET_qXfer_spu_write },
4619   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4620     PACKET_qXfer_osdata },
4621   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4622     PACKET_qXfer_threads },
4623   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4624     PACKET_qXfer_traceframe_info },
4625   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4626     PACKET_QPassSignals },
4627   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4628     PACKET_QCatchSyscalls },
4629   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4630     PACKET_QProgramSignals },
4631   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4632     PACKET_QStartNoAckMode },
4633   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4634     PACKET_multiprocess_feature },
4635   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4636   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4637     PACKET_qXfer_siginfo_read },
4638   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4639     PACKET_qXfer_siginfo_write },
4640   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4641     PACKET_ConditionalTracepoints },
4642   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4643     PACKET_ConditionalBreakpoints },
4644   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4645     PACKET_BreakpointCommands },
4646   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4647     PACKET_FastTracepoints },
4648   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4649     PACKET_StaticTracepoints },
4650   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4651    PACKET_InstallInTrace},
4652   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4653     PACKET_DisconnectedTracing_feature },
4654   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4655     PACKET_bc },
4656   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4657     PACKET_bs },
4658   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4659     PACKET_TracepointSource },
4660   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4661     PACKET_QAllow },
4662   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4663     PACKET_EnableDisableTracepoints_feature },
4664   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4665     PACKET_qXfer_fdpic },
4666   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4667     PACKET_qXfer_uib },
4668   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4669     PACKET_QDisableRandomization },
4670   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4671   { "QTBuffer:size", PACKET_DISABLE,
4672     remote_supported_packet, PACKET_QTBuffer_size},
4673   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4674   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4675   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4676   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4677   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4678     PACKET_qXfer_btrace },
4679   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4680     PACKET_qXfer_btrace_conf },
4681   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4682     PACKET_Qbtrace_conf_bts_size },
4683   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4684   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4685   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4686     PACKET_fork_event_feature },
4687   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4688     PACKET_vfork_event_feature },
4689   { "exec-events", PACKET_DISABLE, remote_supported_packet,
4690     PACKET_exec_event_feature },
4691   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4692     PACKET_Qbtrace_conf_pt_size },
4693   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4694   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4695   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4696 };
4697
4698 static char *remote_support_xml;
4699
4700 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4701
4702 void
4703 register_remote_support_xml (const char *xml)
4704 {
4705 #if defined(HAVE_LIBEXPAT)
4706   if (remote_support_xml == NULL)
4707     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4708   else
4709     {
4710       char *copy = xstrdup (remote_support_xml + 13);
4711       char *p = strtok (copy, ",");
4712
4713       do
4714         {
4715           if (strcmp (p, xml) == 0)
4716             {
4717               /* already there */
4718               xfree (copy);
4719               return;
4720             }
4721         }
4722       while ((p = strtok (NULL, ",")) != NULL);
4723       xfree (copy);
4724
4725       remote_support_xml = reconcat (remote_support_xml,
4726                                      remote_support_xml, ",", xml,
4727                                      (char *) NULL);
4728     }
4729 #endif
4730 }
4731
4732 static char *
4733 remote_query_supported_append (char *msg, const char *append)
4734 {
4735   if (msg)
4736     return reconcat (msg, msg, ";", append, (char *) NULL);
4737   else
4738     return xstrdup (append);
4739 }
4740
4741 static void
4742 remote_query_supported (void)
4743 {
4744   struct remote_state *rs = get_remote_state ();
4745   char *next;
4746   int i;
4747   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4748
4749   /* The packet support flags are handled differently for this packet
4750      than for most others.  We treat an error, a disabled packet, and
4751      an empty response identically: any features which must be reported
4752      to be used will be automatically disabled.  An empty buffer
4753      accomplishes this, since that is also the representation for a list
4754      containing no features.  */
4755
4756   rs->buf[0] = 0;
4757   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4758     {
4759       char *q = NULL;
4760       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4761
4762       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4763         q = remote_query_supported_append (q, "multiprocess+");
4764
4765       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4766         q = remote_query_supported_append (q, "swbreak+");
4767       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4768         q = remote_query_supported_append (q, "hwbreak+");
4769
4770       q = remote_query_supported_append (q, "qRelocInsn+");
4771
4772       if (packet_set_cmd_state (PACKET_fork_event_feature)
4773           != AUTO_BOOLEAN_FALSE)
4774         q = remote_query_supported_append (q, "fork-events+");
4775       if (packet_set_cmd_state (PACKET_vfork_event_feature)
4776           != AUTO_BOOLEAN_FALSE)
4777         q = remote_query_supported_append (q, "vfork-events+");
4778       if (packet_set_cmd_state (PACKET_exec_event_feature)
4779           != AUTO_BOOLEAN_FALSE)
4780         q = remote_query_supported_append (q, "exec-events+");
4781
4782       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4783         q = remote_query_supported_append (q, "vContSupported+");
4784
4785       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4786         q = remote_query_supported_append (q, "QThreadEvents+");
4787
4788       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4789         q = remote_query_supported_append (q, "no-resumed+");
4790
4791       /* Keep this one last to work around a gdbserver <= 7.10 bug in
4792          the qSupported:xmlRegisters=i386 handling.  */
4793       if (remote_support_xml != NULL)
4794         q = remote_query_supported_append (q, remote_support_xml);
4795
4796       q = reconcat (q, "qSupported:", q, (char *) NULL);
4797       putpkt (q);
4798
4799       do_cleanups (old_chain);
4800
4801       getpkt (&rs->buf, &rs->buf_size, 0);
4802
4803       /* If an error occured, warn, but do not return - just reset the
4804          buffer to empty and go on to disable features.  */
4805       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4806           == PACKET_ERROR)
4807         {
4808           warning (_("Remote failure reply: %s"), rs->buf);
4809           rs->buf[0] = 0;
4810         }
4811     }
4812
4813   memset (seen, 0, sizeof (seen));
4814
4815   next = rs->buf;
4816   while (*next)
4817     {
4818       enum packet_support is_supported;
4819       char *p, *end, *name_end, *value;
4820
4821       /* First separate out this item from the rest of the packet.  If
4822          there's another item after this, we overwrite the separator
4823          (terminated strings are much easier to work with).  */
4824       p = next;
4825       end = strchr (p, ';');
4826       if (end == NULL)
4827         {
4828           end = p + strlen (p);
4829           next = end;
4830         }
4831       else
4832         {
4833           *end = '\0';
4834           next = end + 1;
4835
4836           if (end == p)
4837             {
4838               warning (_("empty item in \"qSupported\" response"));
4839               continue;
4840             }
4841         }
4842
4843       name_end = strchr (p, '=');
4844       if (name_end)
4845         {
4846           /* This is a name=value entry.  */
4847           is_supported = PACKET_ENABLE;
4848           value = name_end + 1;
4849           *name_end = '\0';
4850         }
4851       else
4852         {
4853           value = NULL;
4854           switch (end[-1])
4855             {
4856             case '+':
4857               is_supported = PACKET_ENABLE;
4858               break;
4859
4860             case '-':
4861               is_supported = PACKET_DISABLE;
4862               break;
4863
4864             case '?':
4865               is_supported = PACKET_SUPPORT_UNKNOWN;
4866               break;
4867
4868             default:
4869               warning (_("unrecognized item \"%s\" "
4870                          "in \"qSupported\" response"), p);
4871               continue;
4872             }
4873           end[-1] = '\0';
4874         }
4875
4876       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4877         if (strcmp (remote_protocol_features[i].name, p) == 0)
4878           {
4879             const struct protocol_feature *feature;
4880
4881             seen[i] = 1;
4882             feature = &remote_protocol_features[i];
4883             feature->func (feature, is_supported, value);
4884             break;
4885           }
4886     }
4887
4888   /* If we increased the packet size, make sure to increase the global
4889      buffer size also.  We delay this until after parsing the entire
4890      qSupported packet, because this is the same buffer we were
4891      parsing.  */
4892   if (rs->buf_size < rs->explicit_packet_size)
4893     {
4894       rs->buf_size = rs->explicit_packet_size;
4895       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4896     }
4897
4898   /* Handle the defaults for unmentioned features.  */
4899   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4900     if (!seen[i])
4901       {
4902         const struct protocol_feature *feature;
4903
4904         feature = &remote_protocol_features[i];
4905         feature->func (feature, feature->default_support, NULL);
4906       }
4907 }
4908
4909 /* Serial QUIT handler for the remote serial descriptor.
4910
4911    Defers handling a Ctrl-C until we're done with the current
4912    command/response packet sequence, unless:
4913
4914    - We're setting up the connection.  Don't send a remote interrupt
4915      request, as we're not fully synced yet.  Quit immediately
4916      instead.
4917
4918    - The target has been resumed in the foreground
4919      (target_terminal_is_ours is false) with a synchronous resume
4920      packet, and we're blocked waiting for the stop reply, thus a
4921      Ctrl-C should be immediately sent to the target.
4922
4923    - We get a second Ctrl-C while still within the same serial read or
4924      write.  In that case the serial is seemingly wedged --- offer to
4925      quit/disconnect.
4926
4927    - We see a second Ctrl-C without target response, after having
4928      previously interrupted the target.  In that case the target/stub
4929      is probably wedged --- offer to quit/disconnect.
4930 */
4931
4932 static void
4933 remote_serial_quit_handler (void)
4934 {
4935   struct remote_state *rs = get_remote_state ();
4936
4937   if (check_quit_flag ())
4938     {
4939       /* If we're starting up, we're not fully synced yet.  Quit
4940          immediately.  */
4941       if (rs->starting_up)
4942         quit ();
4943       else if (rs->got_ctrlc_during_io)
4944         {
4945           if (query (_("The target is not responding to GDB commands.\n"
4946                        "Stop debugging it? ")))
4947             remote_unpush_and_throw ();
4948         }
4949       /* If ^C has already been sent once, offer to disconnect.  */
4950       else if (!target_terminal_is_ours () && rs->ctrlc_pending_p)
4951         interrupt_query ();
4952       /* All-stop protocol, and blocked waiting for stop reply.  Send
4953          an interrupt request.  */
4954       else if (!target_terminal_is_ours () && rs->waiting_for_stop_reply)
4955         target_interrupt (inferior_ptid);
4956       else
4957         rs->got_ctrlc_during_io = 1;
4958     }
4959 }
4960
4961 /* Remove any of the remote.c targets from target stack.  Upper targets depend
4962    on it so remove them first.  */
4963
4964 static void
4965 remote_unpush_target (void)
4966 {
4967   pop_all_targets_at_and_above (process_stratum);
4968 }
4969
4970 static void
4971 remote_unpush_and_throw (void)
4972 {
4973   remote_unpush_target ();
4974   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
4975 }
4976
4977 static void
4978 remote_open_1 (const char *name, int from_tty,
4979                struct target_ops *target, int extended_p)
4980 {
4981   struct remote_state *rs = get_remote_state ();
4982
4983   if (name == 0)
4984     error (_("To open a remote debug connection, you need to specify what\n"
4985            "serial device is attached to the remote system\n"
4986            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4987
4988   /* See FIXME above.  */
4989   if (!target_async_permitted)
4990     wait_forever_enabled_p = 1;
4991
4992   /* If we're connected to a running target, target_preopen will kill it.
4993      Ask this question first, before target_preopen has a chance to kill
4994      anything.  */
4995   if (rs->remote_desc != NULL && !have_inferiors ())
4996     {
4997       if (from_tty
4998           && !query (_("Already connected to a remote target.  Disconnect? ")))
4999         error (_("Still connected."));
5000     }
5001
5002   /* Here the possibly existing remote target gets unpushed.  */
5003   target_preopen (from_tty);
5004
5005   /* Make sure we send the passed signals list the next time we resume.  */
5006   xfree (rs->last_pass_packet);
5007   rs->last_pass_packet = NULL;
5008
5009   /* Make sure we send the program signals list the next time we
5010      resume.  */
5011   xfree (rs->last_program_signals_packet);
5012   rs->last_program_signals_packet = NULL;
5013
5014   remote_fileio_reset ();
5015   reopen_exec_file ();
5016   reread_symbols ();
5017
5018   rs->remote_desc = remote_serial_open (name);
5019   if (!rs->remote_desc)
5020     perror_with_name (name);
5021
5022   if (baud_rate != -1)
5023     {
5024       if (serial_setbaudrate (rs->remote_desc, baud_rate))
5025         {
5026           /* The requested speed could not be set.  Error out to
5027              top level after closing remote_desc.  Take care to
5028              set remote_desc to NULL to avoid closing remote_desc
5029              more than once.  */
5030           serial_close (rs->remote_desc);
5031           rs->remote_desc = NULL;
5032           perror_with_name (name);
5033         }
5034     }
5035
5036   serial_setparity (rs->remote_desc, serial_parity);
5037   serial_raw (rs->remote_desc);
5038
5039   /* If there is something sitting in the buffer we might take it as a
5040      response to a command, which would be bad.  */
5041   serial_flush_input (rs->remote_desc);
5042
5043   if (from_tty)
5044     {
5045       puts_filtered ("Remote debugging using ");
5046       puts_filtered (name);
5047       puts_filtered ("\n");
5048     }
5049   push_target (target);         /* Switch to using remote target now.  */
5050
5051   /* Register extra event sources in the event loop.  */
5052   remote_async_inferior_event_token
5053     = create_async_event_handler (remote_async_inferior_event_handler,
5054                                   NULL);
5055   rs->notif_state = remote_notif_state_allocate ();
5056
5057   /* Reset the target state; these things will be queried either by
5058      remote_query_supported or as they are needed.  */
5059   reset_all_packet_configs_support ();
5060   rs->cached_wait_status = 0;
5061   rs->explicit_packet_size = 0;
5062   rs->noack_mode = 0;
5063   rs->extended = extended_p;
5064   rs->waiting_for_stop_reply = 0;
5065   rs->ctrlc_pending_p = 0;
5066   rs->got_ctrlc_during_io = 0;
5067
5068   rs->general_thread = not_sent_ptid;
5069   rs->continue_thread = not_sent_ptid;
5070   rs->remote_traceframe_number = -1;
5071
5072   rs->last_resume_exec_dir = EXEC_FORWARD;
5073
5074   /* Probe for ability to use "ThreadInfo" query, as required.  */
5075   rs->use_threadinfo_query = 1;
5076   rs->use_threadextra_query = 1;
5077
5078   readahead_cache_invalidate ();
5079
5080   /* Start out by owning the terminal.  */
5081   remote_async_terminal_ours_p = 1;
5082
5083   if (target_async_permitted)
5084     {
5085       /* FIXME: cagney/1999-09-23: During the initial connection it is
5086          assumed that the target is already ready and able to respond to
5087          requests.  Unfortunately remote_start_remote() eventually calls
5088          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
5089          around this.  Eventually a mechanism that allows
5090          wait_for_inferior() to expect/get timeouts will be
5091          implemented.  */
5092       wait_forever_enabled_p = 0;
5093     }
5094
5095   /* First delete any symbols previously loaded from shared libraries.  */
5096   no_shared_libraries (NULL, 0);
5097
5098   /* Start afresh.  */
5099   init_thread_list ();
5100
5101   /* Start the remote connection.  If error() or QUIT, discard this
5102      target (we'd otherwise be in an inconsistent state) and then
5103      propogate the error on up the exception chain.  This ensures that
5104      the caller doesn't stumble along blindly assuming that the
5105      function succeeded.  The CLI doesn't have this problem but other
5106      UI's, such as MI do.
5107
5108      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5109      this function should return an error indication letting the
5110      caller restore the previous state.  Unfortunately the command
5111      ``target remote'' is directly wired to this function making that
5112      impossible.  On a positive note, the CLI side of this problem has
5113      been fixed - the function set_cmd_context() makes it possible for
5114      all the ``target ....'' commands to share a common callback
5115      function.  See cli-dump.c.  */
5116   {
5117
5118     TRY
5119       {
5120         remote_start_remote (from_tty, target, extended_p);
5121       }
5122     CATCH (ex, RETURN_MASK_ALL)
5123       {
5124         /* Pop the partially set up target - unless something else did
5125            already before throwing the exception.  */
5126         if (rs->remote_desc != NULL)
5127           remote_unpush_target ();
5128         if (target_async_permitted)
5129           wait_forever_enabled_p = 1;
5130         throw_exception (ex);
5131       }
5132     END_CATCH
5133   }
5134
5135   remote_btrace_reset ();
5136
5137   if (target_async_permitted)
5138     wait_forever_enabled_p = 1;
5139 }
5140
5141 /* Detach the specified process.  */
5142
5143 static void
5144 remote_detach_pid (int pid)
5145 {
5146   struct remote_state *rs = get_remote_state ();
5147
5148   if (remote_multi_process_p (rs))
5149     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5150   else
5151     strcpy (rs->buf, "D");
5152
5153   putpkt (rs->buf);
5154   getpkt (&rs->buf, &rs->buf_size, 0);
5155
5156   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5157     ;
5158   else if (rs->buf[0] == '\0')
5159     error (_("Remote doesn't know how to detach"));
5160   else
5161     error (_("Can't detach process."));
5162 }
5163
5164 /* This detaches a program to which we previously attached, using
5165    inferior_ptid to identify the process.  After this is done, GDB
5166    can be used to debug some other program.  We better not have left
5167    any breakpoints in the target program or it'll die when it hits
5168    one.  */
5169
5170 static void
5171 remote_detach_1 (const char *args, int from_tty)
5172 {
5173   int pid = ptid_get_pid (inferior_ptid);
5174   struct remote_state *rs = get_remote_state ();
5175   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5176   int is_fork_parent;
5177
5178   if (args)
5179     error (_("Argument given to \"detach\" when remotely debugging."));
5180
5181   if (!target_has_execution)
5182     error (_("No process to detach from."));
5183
5184   target_announce_detach (from_tty);
5185
5186   /* Tell the remote target to detach.  */
5187   remote_detach_pid (pid);
5188
5189   /* Exit only if this is the only active inferior.  */
5190   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5191     puts_filtered (_("Ending remote debugging.\n"));
5192
5193   /* Check to see if we are detaching a fork parent.  Note that if we
5194      are detaching a fork child, tp == NULL.  */
5195   is_fork_parent = (tp != NULL
5196                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5197
5198   /* If doing detach-on-fork, we don't mourn, because that will delete
5199      breakpoints that should be available for the followed inferior.  */
5200   if (!is_fork_parent)
5201     target_mourn_inferior (inferior_ptid);
5202   else
5203     {
5204       inferior_ptid = null_ptid;
5205       detach_inferior (pid);
5206     }
5207 }
5208
5209 static void
5210 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5211 {
5212   remote_detach_1 (args, from_tty);
5213 }
5214
5215 static void
5216 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5217 {
5218   remote_detach_1 (args, from_tty);
5219 }
5220
5221 /* Target follow-fork function for remote targets.  On entry, and
5222    at return, the current inferior is the fork parent.
5223
5224    Note that although this is currently only used for extended-remote,
5225    it is named remote_follow_fork in anticipation of using it for the
5226    remote target as well.  */
5227
5228 static int
5229 remote_follow_fork (struct target_ops *ops, int follow_child,
5230                     int detach_fork)
5231 {
5232   struct remote_state *rs = get_remote_state ();
5233   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5234
5235   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5236       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5237     {
5238       /* When following the parent and detaching the child, we detach
5239          the child here.  For the case of following the child and
5240          detaching the parent, the detach is done in the target-
5241          independent follow fork code in infrun.c.  We can't use
5242          target_detach when detaching an unfollowed child because
5243          the client side doesn't know anything about the child.  */
5244       if (detach_fork && !follow_child)
5245         {
5246           /* Detach the fork child.  */
5247           ptid_t child_ptid;
5248           pid_t child_pid;
5249
5250           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5251           child_pid = ptid_get_pid (child_ptid);
5252
5253           remote_detach_pid (child_pid);
5254           detach_inferior (child_pid);
5255         }
5256     }
5257   return 0;
5258 }
5259
5260 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5261    in the program space of the new inferior.  On entry and at return the
5262    current inferior is the exec'ing inferior.  INF is the new exec'd
5263    inferior, which may be the same as the exec'ing inferior unless
5264    follow-exec-mode is "new".  */
5265
5266 static void
5267 remote_follow_exec (struct target_ops *ops,
5268                     struct inferior *inf, char *execd_pathname)
5269 {
5270   /* We know that this is a target file name, so if it has the "target:"
5271      prefix we strip it off before saving it in the program space.  */
5272   if (is_target_filename (execd_pathname))
5273     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5274
5275   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5276 }
5277
5278 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5279
5280 static void
5281 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5282 {
5283   if (args)
5284     error (_("Argument given to \"disconnect\" when remotely debugging."));
5285
5286   /* Make sure we unpush even the extended remote targets.  Calling
5287      target_mourn_inferior won't unpush, and remote_mourn won't
5288      unpush if there is more than one inferior left.  */
5289   unpush_target (target);
5290   generic_mourn_inferior ();
5291
5292   if (from_tty)
5293     puts_filtered ("Ending remote debugging.\n");
5294 }
5295
5296 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5297    be chatty about it.  */
5298
5299 static void
5300 extended_remote_attach (struct target_ops *target, const char *args,
5301                         int from_tty)
5302 {
5303   struct remote_state *rs = get_remote_state ();
5304   int pid;
5305   char *wait_status = NULL;
5306
5307   pid = parse_pid_to_attach (args);
5308
5309   /* Remote PID can be freely equal to getpid, do not check it here the same
5310      way as in other targets.  */
5311
5312   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5313     error (_("This target does not support attaching to a process"));
5314
5315   if (from_tty)
5316     {
5317       char *exec_file = get_exec_file (0);
5318
5319       if (exec_file)
5320         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5321                            target_pid_to_str (pid_to_ptid (pid)));
5322       else
5323         printf_unfiltered (_("Attaching to %s\n"),
5324                            target_pid_to_str (pid_to_ptid (pid)));
5325
5326       gdb_flush (gdb_stdout);
5327     }
5328
5329   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5330   putpkt (rs->buf);
5331   getpkt (&rs->buf, &rs->buf_size, 0);
5332
5333   switch (packet_ok (rs->buf,
5334                      &remote_protocol_packets[PACKET_vAttach]))
5335     {
5336     case PACKET_OK:
5337       if (!target_is_non_stop_p ())
5338         {
5339           /* Save the reply for later.  */
5340           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5341           strcpy (wait_status, rs->buf);
5342         }
5343       else if (strcmp (rs->buf, "OK") != 0)
5344         error (_("Attaching to %s failed with: %s"),
5345                target_pid_to_str (pid_to_ptid (pid)),
5346                rs->buf);
5347       break;
5348     case PACKET_UNKNOWN:
5349       error (_("This target does not support attaching to a process"));
5350     default:
5351       error (_("Attaching to %s failed"),
5352              target_pid_to_str (pid_to_ptid (pid)));
5353     }
5354
5355   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5356
5357   inferior_ptid = pid_to_ptid (pid);
5358
5359   if (target_is_non_stop_p ())
5360     {
5361       struct thread_info *thread;
5362
5363       /* Get list of threads.  */
5364       remote_update_thread_list (target);
5365
5366       thread = first_thread_of_process (pid);
5367       if (thread)
5368         inferior_ptid = thread->ptid;
5369       else
5370         inferior_ptid = pid_to_ptid (pid);
5371
5372       /* Invalidate our notion of the remote current thread.  */
5373       record_currthread (rs, minus_one_ptid);
5374     }
5375   else
5376     {
5377       /* Now, if we have thread information, update inferior_ptid.  */
5378       inferior_ptid = remote_current_thread (inferior_ptid);
5379
5380       /* Add the main thread to the thread list.  */
5381       add_thread_silent (inferior_ptid);
5382     }
5383
5384   /* Next, if the target can specify a description, read it.  We do
5385      this before anything involving memory or registers.  */
5386   target_find_description ();
5387
5388   if (!target_is_non_stop_p ())
5389     {
5390       /* Use the previously fetched status.  */
5391       gdb_assert (wait_status != NULL);
5392
5393       if (target_can_async_p ())
5394         {
5395           struct notif_event *reply
5396             =  remote_notif_parse (&notif_client_stop, wait_status);
5397
5398           push_stop_reply ((struct stop_reply *) reply);
5399
5400           target_async (1);
5401         }
5402       else
5403         {
5404           gdb_assert (wait_status != NULL);
5405           strcpy (rs->buf, wait_status);
5406           rs->cached_wait_status = 1;
5407         }
5408     }
5409   else
5410     gdb_assert (wait_status == NULL);
5411 }
5412
5413 /* Implementation of the to_post_attach method.  */
5414
5415 static void
5416 extended_remote_post_attach (struct target_ops *ops, int pid)
5417 {
5418   /* Get text, data & bss offsets.  */
5419   get_offsets ();
5420
5421   /* In certain cases GDB might not have had the chance to start
5422      symbol lookup up until now.  This could happen if the debugged
5423      binary is not using shared libraries, the vsyscall page is not
5424      present (on Linux) and the binary itself hadn't changed since the
5425      debugging process was started.  */
5426   if (symfile_objfile != NULL)
5427     remote_check_symbols();
5428 }
5429
5430 \f
5431 /* Check for the availability of vCont.  This function should also check
5432    the response.  */
5433
5434 static void
5435 remote_vcont_probe (struct remote_state *rs)
5436 {
5437   char *buf;
5438
5439   strcpy (rs->buf, "vCont?");
5440   putpkt (rs->buf);
5441   getpkt (&rs->buf, &rs->buf_size, 0);
5442   buf = rs->buf;
5443
5444   /* Make sure that the features we assume are supported.  */
5445   if (startswith (buf, "vCont"))
5446     {
5447       char *p = &buf[5];
5448       int support_c, support_C;
5449
5450       rs->supports_vCont.s = 0;
5451       rs->supports_vCont.S = 0;
5452       support_c = 0;
5453       support_C = 0;
5454       rs->supports_vCont.t = 0;
5455       rs->supports_vCont.r = 0;
5456       while (p && *p == ';')
5457         {
5458           p++;
5459           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5460             rs->supports_vCont.s = 1;
5461           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5462             rs->supports_vCont.S = 1;
5463           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5464             support_c = 1;
5465           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5466             support_C = 1;
5467           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5468             rs->supports_vCont.t = 1;
5469           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5470             rs->supports_vCont.r = 1;
5471
5472           p = strchr (p, ';');
5473         }
5474
5475       /* If c, and C are not all supported, we can't use vCont.  Clearing
5476          BUF will make packet_ok disable the packet.  */
5477       if (!support_c || !support_C)
5478         buf[0] = 0;
5479     }
5480
5481   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5482 }
5483
5484 /* Helper function for building "vCont" resumptions.  Write a
5485    resumption to P.  ENDP points to one-passed-the-end of the buffer
5486    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5487    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5488    resumed thread should be single-stepped and/or signalled.  If PTID
5489    equals minus_one_ptid, then all threads are resumed; if PTID
5490    represents a process, then all threads of the process are resumed;
5491    the thread to be stepped and/or signalled is given in the global
5492    INFERIOR_PTID.  */
5493
5494 static char *
5495 append_resumption (char *p, char *endp,
5496                    ptid_t ptid, int step, enum gdb_signal siggnal)
5497 {
5498   struct remote_state *rs = get_remote_state ();
5499
5500   if (step && siggnal != GDB_SIGNAL_0)
5501     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5502   else if (step
5503            /* GDB is willing to range step.  */
5504            && use_range_stepping
5505            /* Target supports range stepping.  */
5506            && rs->supports_vCont.r
5507            /* We don't currently support range stepping multiple
5508               threads with a wildcard (though the protocol allows it,
5509               so stubs shouldn't make an active effort to forbid
5510               it).  */
5511            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5512     {
5513       struct thread_info *tp;
5514
5515       if (ptid_equal (ptid, minus_one_ptid))
5516         {
5517           /* If we don't know about the target thread's tid, then
5518              we're resuming magic_null_ptid (see caller).  */
5519           tp = find_thread_ptid (magic_null_ptid);
5520         }
5521       else
5522         tp = find_thread_ptid (ptid);
5523       gdb_assert (tp != NULL);
5524
5525       if (tp->control.may_range_step)
5526         {
5527           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5528
5529           p += xsnprintf (p, endp - p, ";r%s,%s",
5530                           phex_nz (tp->control.step_range_start,
5531                                    addr_size),
5532                           phex_nz (tp->control.step_range_end,
5533                                    addr_size));
5534         }
5535       else
5536         p += xsnprintf (p, endp - p, ";s");
5537     }
5538   else if (step)
5539     p += xsnprintf (p, endp - p, ";s");
5540   else if (siggnal != GDB_SIGNAL_0)
5541     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5542   else
5543     p += xsnprintf (p, endp - p, ";c");
5544
5545   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5546     {
5547       ptid_t nptid;
5548
5549       /* All (-1) threads of process.  */
5550       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5551
5552       p += xsnprintf (p, endp - p, ":");
5553       p = write_ptid (p, endp, nptid);
5554     }
5555   else if (!ptid_equal (ptid, minus_one_ptid))
5556     {
5557       p += xsnprintf (p, endp - p, ":");
5558       p = write_ptid (p, endp, ptid);
5559     }
5560
5561   return p;
5562 }
5563
5564 /* Clear the thread's private info on resume.  */
5565
5566 static void
5567 resume_clear_thread_private_info (struct thread_info *thread)
5568 {
5569   if (thread->priv != NULL)
5570     {
5571       thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5572       thread->priv->watch_data_address = 0;
5573     }
5574 }
5575
5576 /* Append a vCont continue-with-signal action for threads that have a
5577    non-zero stop signal.  */
5578
5579 static char *
5580 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5581 {
5582   struct thread_info *thread;
5583
5584   ALL_NON_EXITED_THREADS (thread)
5585     if (ptid_match (thread->ptid, ptid)
5586         && !ptid_equal (inferior_ptid, thread->ptid)
5587         && thread->suspend.stop_signal != GDB_SIGNAL_0)
5588       {
5589         p = append_resumption (p, endp, thread->ptid,
5590                                0, thread->suspend.stop_signal);
5591         thread->suspend.stop_signal = GDB_SIGNAL_0;
5592         resume_clear_thread_private_info (thread);
5593       }
5594
5595   return p;
5596 }
5597
5598 /* Set the target running, using the packets that use Hc
5599    (c/s/C/S).  */
5600
5601 static void
5602 remote_resume_with_hc (struct target_ops *ops,
5603                        ptid_t ptid, int step, enum gdb_signal siggnal)
5604 {
5605   struct remote_state *rs = get_remote_state ();
5606   struct thread_info *thread;
5607   char *buf;
5608
5609   rs->last_sent_signal = siggnal;
5610   rs->last_sent_step = step;
5611
5612   /* The c/s/C/S resume packets use Hc, so set the continue
5613      thread.  */
5614   if (ptid_equal (ptid, minus_one_ptid))
5615     set_continue_thread (any_thread_ptid);
5616   else
5617     set_continue_thread (ptid);
5618
5619   ALL_NON_EXITED_THREADS (thread)
5620     resume_clear_thread_private_info (thread);
5621
5622   buf = rs->buf;
5623   if (execution_direction == EXEC_REVERSE)
5624     {
5625       /* We don't pass signals to the target in reverse exec mode.  */
5626       if (info_verbose && siggnal != GDB_SIGNAL_0)
5627         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5628                  siggnal);
5629
5630       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5631         error (_("Remote reverse-step not supported."));
5632       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5633         error (_("Remote reverse-continue not supported."));
5634
5635       strcpy (buf, step ? "bs" : "bc");
5636     }
5637   else if (siggnal != GDB_SIGNAL_0)
5638     {
5639       buf[0] = step ? 'S' : 'C';
5640       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5641       buf[2] = tohex (((int) siggnal) & 0xf);
5642       buf[3] = '\0';
5643     }
5644   else
5645     strcpy (buf, step ? "s" : "c");
5646
5647   putpkt (buf);
5648 }
5649
5650 /* Resume the remote inferior by using a "vCont" packet.  The thread
5651    to be resumed is PTID; STEP and SIGGNAL indicate whether the
5652    resumed thread should be single-stepped and/or signalled.  If PTID
5653    equals minus_one_ptid, then all threads are resumed; the thread to
5654    be stepped and/or signalled is given in the global INFERIOR_PTID.
5655    This function returns non-zero iff it resumes the inferior.
5656
5657    This function issues a strict subset of all possible vCont commands
5658    at the moment.  */
5659
5660 static int
5661 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5662 {
5663   struct remote_state *rs = get_remote_state ();
5664   char *p;
5665   char *endp;
5666
5667   /* No reverse execution actions defined for vCont.  */
5668   if (execution_direction == EXEC_REVERSE)
5669     return 0;
5670
5671   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5672     remote_vcont_probe (rs);
5673
5674   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5675     return 0;
5676
5677   p = rs->buf;
5678   endp = rs->buf + get_remote_packet_size ();
5679
5680   /* If we could generate a wider range of packets, we'd have to worry
5681      about overflowing BUF.  Should there be a generic
5682      "multi-part-packet" packet?  */
5683
5684   p += xsnprintf (p, endp - p, "vCont");
5685
5686   if (ptid_equal (ptid, magic_null_ptid))
5687     {
5688       /* MAGIC_NULL_PTID means that we don't have any active threads,
5689          so we don't have any TID numbers the inferior will
5690          understand.  Make sure to only send forms that do not specify
5691          a TID.  */
5692       append_resumption (p, endp, minus_one_ptid, step, siggnal);
5693     }
5694   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5695     {
5696       /* Resume all threads (of all processes, or of a single
5697          process), with preference for INFERIOR_PTID.  This assumes
5698          inferior_ptid belongs to the set of all threads we are about
5699          to resume.  */
5700       if (step || siggnal != GDB_SIGNAL_0)
5701         {
5702           /* Step inferior_ptid, with or without signal.  */
5703           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5704         }
5705
5706       /* Also pass down any pending signaled resumption for other
5707          threads not the current.  */
5708       p = append_pending_thread_resumptions (p, endp, ptid);
5709
5710       /* And continue others without a signal.  */
5711       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5712     }
5713   else
5714     {
5715       /* Scheduler locking; resume only PTID.  */
5716       append_resumption (p, endp, ptid, step, siggnal);
5717     }
5718
5719   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5720   putpkt (rs->buf);
5721
5722   if (target_is_non_stop_p ())
5723     {
5724       /* In non-stop, the stub replies to vCont with "OK".  The stop
5725          reply will be reported asynchronously by means of a `%Stop'
5726          notification.  */
5727       getpkt (&rs->buf, &rs->buf_size, 0);
5728       if (strcmp (rs->buf, "OK") != 0)
5729         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5730     }
5731
5732   return 1;
5733 }
5734
5735 /* Tell the remote machine to resume.  */
5736
5737 static void
5738 remote_resume (struct target_ops *ops,
5739                ptid_t ptid, int step, enum gdb_signal siggnal)
5740 {
5741   struct remote_state *rs = get_remote_state ();
5742
5743   /* When connected in non-stop mode, the core resumes threads
5744      individually.  Resuming remote threads directly in target_resume
5745      would thus result in sending one packet per thread.  Instead, to
5746      minimize roundtrip latency, here we just store the resume
5747      request; the actual remote resumption will be done in
5748      target_commit_resume / remote_commit_resume, where we'll be able
5749      to do vCont action coalescing.  */
5750   if (target_is_non_stop_p () && execution_direction != EXEC_REVERSE)
5751     {
5752       struct private_thread_info *remote_thr;
5753
5754       if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5755         remote_thr = get_private_info_ptid (inferior_ptid);
5756       else
5757         remote_thr = get_private_info_ptid (ptid);
5758       remote_thr->last_resume_step = step;
5759       remote_thr->last_resume_sig = siggnal;
5760       return;
5761     }
5762
5763   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5764      (explained in remote-notif.c:handle_notification) so
5765      remote_notif_process is not called.  We need find a place where
5766      it is safe to start a 'vNotif' sequence.  It is good to do it
5767      before resuming inferior, because inferior was stopped and no RSP
5768      traffic at that moment.  */
5769   if (!target_is_non_stop_p ())
5770     remote_notif_process (rs->notif_state, &notif_client_stop);
5771
5772   rs->last_resume_exec_dir = execution_direction;
5773
5774   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
5775   if (!remote_resume_with_vcont (ptid, step, siggnal))
5776     remote_resume_with_hc (ops, ptid, step, siggnal);
5777
5778   /* We are about to start executing the inferior, let's register it
5779      with the event loop.  NOTE: this is the one place where all the
5780      execution commands end up.  We could alternatively do this in each
5781      of the execution commands in infcmd.c.  */
5782   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5783      into infcmd.c in order to allow inferior function calls to work
5784      NOT asynchronously.  */
5785   if (target_can_async_p ())
5786     target_async (1);
5787
5788   /* We've just told the target to resume.  The remote server will
5789      wait for the inferior to stop, and then send a stop reply.  In
5790      the mean time, we can't start another command/query ourselves
5791      because the stub wouldn't be ready to process it.  This applies
5792      only to the base all-stop protocol, however.  In non-stop (which
5793      only supports vCont), the stub replies with an "OK", and is
5794      immediate able to process further serial input.  */
5795   if (!target_is_non_stop_p ())
5796     rs->waiting_for_stop_reply = 1;
5797 }
5798
5799 static void check_pending_events_prevent_wildcard_vcont
5800   (int *may_global_wildcard_vcont);
5801 static int is_pending_fork_parent_thread (struct thread_info *thread);
5802
5803 /* Private per-inferior info for target remote processes.  */
5804
5805 struct private_inferior
5806 {
5807   /* Whether we can send a wildcard vCont for this process.  */
5808   int may_wildcard_vcont;
5809 };
5810
5811 /* Structure used to track the construction of a vCont packet in the
5812    outgoing packet buffer.  This is used to send multiple vCont
5813    packets if we have more actions than would fit a single packet.  */
5814
5815 struct vcont_builder
5816 {
5817   /* Pointer to the first action.  P points here if no action has been
5818      appended yet.  */
5819   char *first_action;
5820
5821   /* Where the next action will be appended.  */
5822   char *p;
5823
5824   /* The end of the buffer.  Must never write past this.  */
5825   char *endp;
5826 };
5827
5828 /* Prepare the outgoing buffer for a new vCont packet.  */
5829
5830 static void
5831 vcont_builder_restart (struct vcont_builder *builder)
5832 {
5833   struct remote_state *rs = get_remote_state ();
5834
5835   builder->p = rs->buf;
5836   builder->endp = rs->buf + get_remote_packet_size ();
5837   builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
5838   builder->first_action = builder->p;
5839 }
5840
5841 /* If the vCont packet being built has any action, send it to the
5842    remote end.  */
5843
5844 static void
5845 vcont_builder_flush (struct vcont_builder *builder)
5846 {
5847   struct remote_state *rs;
5848
5849   if (builder->p == builder->first_action)
5850     return;
5851
5852   rs = get_remote_state ();
5853   putpkt (rs->buf);
5854   getpkt (&rs->buf, &rs->buf_size, 0);
5855   if (strcmp (rs->buf, "OK") != 0)
5856     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5857 }
5858
5859 /* The largest action is range-stepping, with its two addresses.  This
5860    is more than sufficient.  If a new, bigger action is created, it'll
5861    quickly trigger a failed assertion in append_resumption (and we'll
5862    just bump this).  */
5863 #define MAX_ACTION_SIZE 200
5864
5865 /* Append a new vCont action in the outgoing packet being built.  If
5866    the action doesn't fit the packet along with previous actions, push
5867    what we've got so far to the remote end and start over a new vCont
5868    packet (with the new action).  */
5869
5870 static void
5871 vcont_builder_push_action (struct vcont_builder *builder,
5872                            ptid_t ptid, int step, enum gdb_signal siggnal)
5873 {
5874   char buf[MAX_ACTION_SIZE + 1];
5875   char *endp;
5876   size_t rsize;
5877
5878   endp = append_resumption (buf, buf + sizeof (buf),
5879                             ptid, step, siggnal);
5880
5881   /* Check whether this new action would fit in the vCont packet along
5882      with previous actions.  If not, send what we've got so far and
5883      start a new vCont packet.  */
5884   rsize = endp - buf;
5885   if (rsize > builder->endp - builder->p)
5886     {
5887       vcont_builder_flush (builder);
5888       vcont_builder_restart (builder);
5889
5890       /* Should now fit.  */
5891       gdb_assert (rsize <= builder->endp - builder->p);
5892     }
5893
5894   memcpy (builder->p, buf, rsize);
5895   builder->p += rsize;
5896   *builder->p = '\0';
5897 }
5898
5899 /* to_commit_resume implementation.  */
5900
5901 static void
5902 remote_commit_resume (struct target_ops *ops)
5903 {
5904   struct remote_state *rs = get_remote_state ();
5905   struct inferior *inf;
5906   struct thread_info *tp;
5907   int any_process_wildcard;
5908   int may_global_wildcard_vcont;
5909   struct vcont_builder vcont_builder;
5910
5911   /* If connected in all-stop mode, we'd send the remote resume
5912      request directly from remote_resume.  Likewise if
5913      reverse-debugging, as there are no defined vCont actions for
5914      reverse execution.  */
5915   if (!target_is_non_stop_p () || execution_direction == EXEC_REVERSE)
5916     return;
5917
5918   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
5919      instead of resuming all threads of each process individually.
5920      However, if any thread of a process must remain halted, we can't
5921      send wildcard resumes and must send one action per thread.
5922
5923      Care must be taken to not resume threads/processes the server
5924      side already told us are stopped, but the core doesn't know about
5925      yet, because the events are still in the vStopped notification
5926      queue.  For example:
5927
5928        #1 => vCont s:p1.1;c
5929        #2 <= OK
5930        #3 <= %Stopped T05 p1.1
5931        #4 => vStopped
5932        #5 <= T05 p1.2
5933        #6 => vStopped
5934        #7 <= OK
5935        #8 (infrun handles the stop for p1.1 and continues stepping)
5936        #9 => vCont s:p1.1;c
5937
5938      The last vCont above would resume thread p1.2 by mistake, because
5939      the server has no idea that the event for p1.2 had not been
5940      handled yet.
5941
5942      The server side must similarly ignore resume actions for the
5943      thread that has a pending %Stopped notification (and any other
5944      threads with events pending), until GDB acks the notification
5945      with vStopped.  Otherwise, e.g., the following case is
5946      mishandled:
5947
5948        #1 => g  (or any other packet)
5949        #2 <= [registers]
5950        #3 <= %Stopped T05 p1.2
5951        #4 => vCont s:p1.1;c
5952        #5 <= OK
5953
5954      Above, the server must not resume thread p1.2.  GDB can't know
5955      that p1.2 stopped until it acks the %Stopped notification, and
5956      since from GDB's perspective all threads should be running, it
5957      sends a "c" action.
5958
5959      Finally, special care must also be given to handling fork/vfork
5960      events.  A (v)fork event actually tells us that two processes
5961      stopped -- the parent and the child.  Until we follow the fork,
5962      we must not resume the child.  Therefore, if we have a pending
5963      fork follow, we must not send a global wildcard resume action
5964      (vCont;c).  We can still send process-wide wildcards though.  */
5965
5966   /* Start by assuming a global wildcard (vCont;c) is possible.  */
5967   may_global_wildcard_vcont = 1;
5968
5969   /* And assume every process is individually wildcard-able too.  */
5970   ALL_NON_EXITED_INFERIORS (inf)
5971     {
5972       if (inf->priv == NULL)
5973         inf->priv = XNEW (struct private_inferior);
5974       inf->priv->may_wildcard_vcont = 1;
5975     }
5976
5977   /* Check for any pending events (not reported or processed yet) and
5978      disable process and global wildcard resumes appropriately.  */
5979   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
5980
5981   ALL_NON_EXITED_THREADS (tp)
5982     {
5983       /* If a thread of a process is not meant to be resumed, then we
5984          can't wildcard that process.  */
5985       if (!tp->executing)
5986         {
5987           tp->inf->priv->may_wildcard_vcont = 0;
5988
5989           /* And if we can't wildcard a process, we can't wildcard
5990              everything either.  */
5991           may_global_wildcard_vcont = 0;
5992           continue;
5993         }
5994
5995       /* If a thread is the parent of an unfollowed fork, then we
5996          can't do a global wildcard, as that would resume the fork
5997          child.  */
5998       if (is_pending_fork_parent_thread (tp))
5999         may_global_wildcard_vcont = 0;
6000     }
6001
6002   /* Now let's build the vCont packet(s).  Actions must be appended
6003      from narrower to wider scopes (thread -> process -> global).  If
6004      we end up with too many actions for a single packet vcont_builder
6005      flushes the current vCont packet to the remote side and starts a
6006      new one.  */
6007   vcont_builder_restart (&vcont_builder);
6008
6009   /* Threads first.  */
6010   ALL_NON_EXITED_THREADS (tp)
6011     {
6012       struct private_thread_info *remote_thr = tp->priv;
6013
6014       if (!tp->executing || remote_thr->vcont_resumed)
6015         continue;
6016
6017       gdb_assert (!thread_is_in_step_over_chain (tp));
6018
6019       if (!remote_thr->last_resume_step
6020           && remote_thr->last_resume_sig == GDB_SIGNAL_0
6021           && tp->inf->priv->may_wildcard_vcont)
6022         {
6023           /* We'll send a wildcard resume instead.  */
6024           remote_thr->vcont_resumed = 1;
6025           continue;
6026         }
6027
6028       vcont_builder_push_action (&vcont_builder, tp->ptid,
6029                                  remote_thr->last_resume_step,
6030                                  remote_thr->last_resume_sig);
6031       remote_thr->vcont_resumed = 1;
6032     }
6033
6034   /* Now check whether we can send any process-wide wildcard.  This is
6035      to avoid sending a global wildcard in the case nothing is
6036      supposed to be resumed.  */
6037   any_process_wildcard = 0;
6038
6039   ALL_NON_EXITED_INFERIORS (inf)
6040     {
6041       if (inf->priv->may_wildcard_vcont)
6042         {
6043           any_process_wildcard = 1;
6044           break;
6045         }
6046     }
6047
6048   if (any_process_wildcard)
6049     {
6050       /* If all processes are wildcard-able, then send a single "c"
6051          action, otherwise, send an "all (-1) threads of process"
6052          continue action for each running process, if any.  */
6053       if (may_global_wildcard_vcont)
6054         {
6055           vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6056                                      0, GDB_SIGNAL_0);
6057         }
6058       else
6059         {
6060           ALL_NON_EXITED_INFERIORS (inf)
6061             {
6062               if (inf->priv->may_wildcard_vcont)
6063                 {
6064                   vcont_builder_push_action (&vcont_builder,
6065                                              pid_to_ptid (inf->pid),
6066                                              0, GDB_SIGNAL_0);
6067                 }
6068             }
6069         }
6070     }
6071
6072   vcont_builder_flush (&vcont_builder);
6073 }
6074
6075 \f
6076
6077 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
6078    thread, all threads of a remote process, or all threads of all
6079    processes.  */
6080
6081 static void
6082 remote_stop_ns (ptid_t ptid)
6083 {
6084   struct remote_state *rs = get_remote_state ();
6085   char *p = rs->buf;
6086   char *endp = rs->buf + get_remote_packet_size ();
6087
6088   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6089     remote_vcont_probe (rs);
6090
6091   if (!rs->supports_vCont.t)
6092     error (_("Remote server does not support stopping threads"));
6093
6094   if (ptid_equal (ptid, minus_one_ptid)
6095       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6096     p += xsnprintf (p, endp - p, "vCont;t");
6097   else
6098     {
6099       ptid_t nptid;
6100
6101       p += xsnprintf (p, endp - p, "vCont;t:");
6102
6103       if (ptid_is_pid (ptid))
6104           /* All (-1) threads of process.  */
6105         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6106       else
6107         {
6108           /* Small optimization: if we already have a stop reply for
6109              this thread, no use in telling the stub we want this
6110              stopped.  */
6111           if (peek_stop_reply (ptid))
6112             return;
6113
6114           nptid = ptid;
6115         }
6116
6117       write_ptid (p, endp, nptid);
6118     }
6119
6120   /* In non-stop, we get an immediate OK reply.  The stop reply will
6121      come in asynchronously by notification.  */
6122   putpkt (rs->buf);
6123   getpkt (&rs->buf, &rs->buf_size, 0);
6124   if (strcmp (rs->buf, "OK") != 0)
6125     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6126 }
6127
6128 /* All-stop version of target_interrupt.  Sends a break or a ^C to
6129    interrupt the remote target.  It is undefined which thread of which
6130    process reports the interrupt.  */
6131
6132 static void
6133 remote_interrupt_as (void)
6134 {
6135   struct remote_state *rs = get_remote_state ();
6136
6137   rs->ctrlc_pending_p = 1;
6138
6139   /* If the inferior is stopped already, but the core didn't know
6140      about it yet, just ignore the request.  The cached wait status
6141      will be collected in remote_wait.  */
6142   if (rs->cached_wait_status)
6143     return;
6144
6145   /* Send interrupt_sequence to remote target.  */
6146   send_interrupt_sequence ();
6147 }
6148
6149 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
6150    the remote target.  It is undefined which thread of which process
6151    reports the interrupt.  Throws an error if the packet is not
6152    supported by the server.  */
6153
6154 static void
6155 remote_interrupt_ns (void)
6156 {
6157   struct remote_state *rs = get_remote_state ();
6158   char *p = rs->buf;
6159   char *endp = rs->buf + get_remote_packet_size ();
6160
6161   xsnprintf (p, endp - p, "vCtrlC");
6162
6163   /* In non-stop, we get an immediate OK reply.  The stop reply will
6164      come in asynchronously by notification.  */
6165   putpkt (rs->buf);
6166   getpkt (&rs->buf, &rs->buf_size, 0);
6167
6168   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6169     {
6170     case PACKET_OK:
6171       break;
6172     case PACKET_UNKNOWN:
6173       error (_("No support for interrupting the remote target."));
6174     case PACKET_ERROR:
6175       error (_("Interrupting target failed: %s"), rs->buf);
6176     }
6177 }
6178
6179 /* Implement the to_stop function for the remote targets.  */
6180
6181 static void
6182 remote_stop (struct target_ops *self, ptid_t ptid)
6183 {
6184   if (remote_debug)
6185     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6186
6187   if (target_is_non_stop_p ())
6188     remote_stop_ns (ptid);
6189   else
6190     {
6191       /* We don't currently have a way to transparently pause the
6192          remote target in all-stop mode.  Interrupt it instead.  */
6193       remote_interrupt_as ();
6194     }
6195 }
6196
6197 /* Implement the to_interrupt function for the remote targets.  */
6198
6199 static void
6200 remote_interrupt (struct target_ops *self, ptid_t ptid)
6201 {
6202   struct remote_state *rs = get_remote_state ();
6203
6204   if (remote_debug)
6205     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6206
6207   if (target_is_non_stop_p ())
6208     remote_interrupt_ns ();
6209   else
6210     remote_interrupt_as ();
6211 }
6212
6213 /* Implement the to_pass_ctrlc function for the remote targets.  */
6214
6215 static void
6216 remote_pass_ctrlc (struct target_ops *self)
6217 {
6218   struct remote_state *rs = get_remote_state ();
6219
6220   if (remote_debug)
6221     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6222
6223   /* If we're starting up, we're not fully synced yet.  Quit
6224      immediately.  */
6225   if (rs->starting_up)
6226     quit ();
6227   /* If ^C has already been sent once, offer to disconnect.  */
6228   else if (rs->ctrlc_pending_p)
6229     interrupt_query ();
6230   else
6231     target_interrupt (inferior_ptid);
6232 }
6233
6234 /* Ask the user what to do when an interrupt is received.  */
6235
6236 static void
6237 interrupt_query (void)
6238 {
6239   struct remote_state *rs = get_remote_state ();
6240
6241   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6242     {
6243       if (query (_("The target is not responding to interrupt requests.\n"
6244                    "Stop debugging it? ")))
6245         {
6246           remote_unpush_target ();
6247           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6248         }
6249     }
6250   else
6251     {
6252       if (query (_("Interrupted while waiting for the program.\n"
6253                    "Give up waiting? ")))
6254         quit ();
6255     }
6256 }
6257
6258 /* Enable/disable target terminal ownership.  Most targets can use
6259    terminal groups to control terminal ownership.  Remote targets are
6260    different in that explicit transfer of ownership to/from GDB/target
6261    is required.  */
6262
6263 static void
6264 remote_terminal_inferior (struct target_ops *self)
6265 {
6266   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
6267      idempotent.  The event-loop GDB talking to an asynchronous target
6268      with a synchronous command calls this function from both
6269      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
6270      transfer the terminal to the target when it shouldn't this guard
6271      can go away.  */
6272   if (!remote_async_terminal_ours_p)
6273     return;
6274   remote_async_terminal_ours_p = 0;
6275   /* NOTE: At this point we could also register our selves as the
6276      recipient of all input.  Any characters typed could then be
6277      passed on down to the target.  */
6278 }
6279
6280 static void
6281 remote_terminal_ours (struct target_ops *self)
6282 {
6283   /* See FIXME in remote_terminal_inferior.  */
6284   if (remote_async_terminal_ours_p)
6285     return;
6286   remote_async_terminal_ours_p = 1;
6287 }
6288
6289 static void
6290 remote_console_output (char *msg)
6291 {
6292   char *p;
6293
6294   for (p = msg; p[0] && p[1]; p += 2)
6295     {
6296       char tb[2];
6297       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6298
6299       tb[0] = c;
6300       tb[1] = 0;
6301       fputs_unfiltered (tb, gdb_stdtarg);
6302     }
6303   gdb_flush (gdb_stdtarg);
6304 }
6305
6306 typedef struct cached_reg
6307 {
6308   int num;
6309   gdb_byte data[MAX_REGISTER_SIZE];
6310 } cached_reg_t;
6311
6312 DEF_VEC_O(cached_reg_t);
6313
6314 typedef struct stop_reply
6315 {
6316   struct notif_event base;
6317
6318   /* The identifier of the thread about this event  */
6319   ptid_t ptid;
6320
6321   /* The remote state this event is associated with.  When the remote
6322      connection, represented by a remote_state object, is closed,
6323      all the associated stop_reply events should be released.  */
6324   struct remote_state *rs;
6325
6326   struct target_waitstatus ws;
6327
6328   /* Expedited registers.  This makes remote debugging a bit more
6329      efficient for those targets that provide critical registers as
6330      part of their normal status mechanism (as another roundtrip to
6331      fetch them is avoided).  */
6332   VEC(cached_reg_t) *regcache;
6333
6334   enum target_stop_reason stop_reason;
6335
6336   CORE_ADDR watch_data_address;
6337
6338   int core;
6339 } *stop_reply_p;
6340
6341 DECLARE_QUEUE_P (stop_reply_p);
6342 DEFINE_QUEUE_P (stop_reply_p);
6343 /* The list of already fetched and acknowledged stop events.  This
6344    queue is used for notification Stop, and other notifications
6345    don't need queue for their events, because the notification events
6346    of Stop can't be consumed immediately, so that events should be
6347    queued first, and be consumed by remote_wait_{ns,as} one per
6348    time.  Other notifications can consume their events immediately,
6349    so queue is not needed for them.  */
6350 static QUEUE (stop_reply_p) *stop_reply_queue;
6351
6352 static void
6353 stop_reply_xfree (struct stop_reply *r)
6354 {
6355   notif_event_xfree ((struct notif_event *) r);
6356 }
6357
6358 /* Return the length of the stop reply queue.  */
6359
6360 static int
6361 stop_reply_queue_length (void)
6362 {
6363   return QUEUE_length (stop_reply_p, stop_reply_queue);
6364 }
6365
6366 static void
6367 remote_notif_stop_parse (struct notif_client *self, char *buf,
6368                          struct notif_event *event)
6369 {
6370   remote_parse_stop_reply (buf, (struct stop_reply *) event);
6371 }
6372
6373 static void
6374 remote_notif_stop_ack (struct notif_client *self, char *buf,
6375                        struct notif_event *event)
6376 {
6377   struct stop_reply *stop_reply = (struct stop_reply *) event;
6378
6379   /* acknowledge */
6380   putpkt (self->ack_command);
6381
6382   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6383       /* We got an unknown stop reply.  */
6384       error (_("Unknown stop reply"));
6385
6386   push_stop_reply (stop_reply);
6387 }
6388
6389 static int
6390 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6391 {
6392   /* We can't get pending events in remote_notif_process for
6393      notification stop, and we have to do this in remote_wait_ns
6394      instead.  If we fetch all queued events from stub, remote stub
6395      may exit and we have no chance to process them back in
6396      remote_wait_ns.  */
6397   mark_async_event_handler (remote_async_inferior_event_token);
6398   return 0;
6399 }
6400
6401 static void
6402 stop_reply_dtr (struct notif_event *event)
6403 {
6404   struct stop_reply *r = (struct stop_reply *) event;
6405
6406   VEC_free (cached_reg_t, r->regcache);
6407 }
6408
6409 static struct notif_event *
6410 remote_notif_stop_alloc_reply (void)
6411 {
6412   /* We cast to a pointer to the "base class".  */
6413   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6414
6415   r->dtr = stop_reply_dtr;
6416
6417   return r;
6418 }
6419
6420 /* A client of notification Stop.  */
6421
6422 struct notif_client notif_client_stop =
6423 {
6424   "Stop",
6425   "vStopped",
6426   remote_notif_stop_parse,
6427   remote_notif_stop_ack,
6428   remote_notif_stop_can_get_pending_events,
6429   remote_notif_stop_alloc_reply,
6430   REMOTE_NOTIF_STOP,
6431 };
6432
6433 /* A parameter to pass data in and out.  */
6434
6435 struct queue_iter_param
6436 {
6437   void *input;
6438   struct stop_reply *output;
6439 };
6440
6441 /* Determine if THREAD_PTID is a pending fork parent thread.  ARG contains
6442    the pid of the process that owns the threads we want to check, or
6443    -1 if we want to check all threads.  */
6444
6445 static int
6446 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6447                         ptid_t thread_ptid)
6448 {
6449   if (ws->kind == TARGET_WAITKIND_FORKED
6450       || ws->kind == TARGET_WAITKIND_VFORKED)
6451     {
6452       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6453         return 1;
6454     }
6455
6456   return 0;
6457 }
6458
6459 /* Return the thread's pending status used to determine whether the
6460    thread is a fork parent stopped at a fork event.  */
6461
6462 static struct target_waitstatus *
6463 thread_pending_fork_status (struct thread_info *thread)
6464 {
6465   if (thread->suspend.waitstatus_pending_p)
6466     return &thread->suspend.waitstatus;
6467   else
6468     return &thread->pending_follow;
6469 }
6470
6471 /* Determine if THREAD is a pending fork parent thread.  */
6472
6473 static int
6474 is_pending_fork_parent_thread (struct thread_info *thread)
6475 {
6476   struct target_waitstatus *ws = thread_pending_fork_status (thread);
6477   int pid = -1;
6478
6479   return is_pending_fork_parent (ws, pid, thread->ptid);
6480 }
6481
6482 /* Check whether EVENT is a fork event, and if it is, remove the
6483    fork child from the context list passed in DATA.  */
6484
6485 static int
6486 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6487                               QUEUE_ITER (stop_reply_p) *iter,
6488                               stop_reply_p event,
6489                               void *data)
6490 {
6491   struct queue_iter_param *param = (struct queue_iter_param *) data;
6492   struct threads_listing_context *context
6493     = (struct threads_listing_context *) param->input;
6494
6495   if (event->ws.kind == TARGET_WAITKIND_FORKED
6496       || event->ws.kind == TARGET_WAITKIND_VFORKED
6497       || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6498     threads_listing_context_remove (&event->ws, context);
6499
6500   return 1;
6501 }
6502
6503 /* If CONTEXT contains any fork child threads that have not been
6504    reported yet, remove them from the CONTEXT list.  If such a
6505    thread exists it is because we are stopped at a fork catchpoint
6506    and have not yet called follow_fork, which will set up the
6507    host-side data structures for the new process.  */
6508
6509 static void
6510 remove_new_fork_children (struct threads_listing_context *context)
6511 {
6512   struct thread_info * thread;
6513   int pid = -1;
6514   struct notif_client *notif = &notif_client_stop;
6515   struct queue_iter_param param;
6516
6517   /* For any threads stopped at a fork event, remove the corresponding
6518      fork child threads from the CONTEXT list.  */
6519   ALL_NON_EXITED_THREADS (thread)
6520     {
6521       struct target_waitstatus *ws = thread_pending_fork_status (thread);
6522
6523       if (is_pending_fork_parent (ws, pid, thread->ptid))
6524         {
6525           threads_listing_context_remove (ws, context);
6526         }
6527     }
6528
6529   /* Check for any pending fork events (not reported or processed yet)
6530      in process PID and remove those fork child threads from the
6531      CONTEXT list as well.  */
6532   remote_notif_get_pending_events (notif);
6533   param.input = context;
6534   param.output = NULL;
6535   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6536                  remove_child_of_pending_fork, &param);
6537 }
6538
6539 /* Check whether EVENT would prevent a global or process wildcard
6540    vCont action.  */
6541
6542 static int
6543 check_pending_event_prevents_wildcard_vcont_callback
6544   (QUEUE (stop_reply_p) *q,
6545    QUEUE_ITER (stop_reply_p) *iter,
6546    stop_reply_p event,
6547    void *data)
6548 {
6549   struct inferior *inf;
6550   int *may_global_wildcard_vcont = (int *) data;
6551
6552   if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6553       || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6554     return 1;
6555
6556   if (event->ws.kind == TARGET_WAITKIND_FORKED
6557       || event->ws.kind == TARGET_WAITKIND_VFORKED)
6558     *may_global_wildcard_vcont = 0;
6559
6560   inf = find_inferior_ptid (event->ptid);
6561
6562   /* This may be the first time we heard about this process.
6563      Regardless, we must not do a global wildcard resume, otherwise
6564      we'd resume this process too.  */
6565   *may_global_wildcard_vcont = 0;
6566   if (inf != NULL)
6567     inf->priv->may_wildcard_vcont = 0;
6568
6569   return 1;
6570 }
6571
6572 /* Check whether any event pending in the vStopped queue would prevent
6573    a global or process wildcard vCont action.  Clear
6574    *may_global_wildcard if we can't do a global wildcard (vCont;c),
6575    and clear the event inferior's may_wildcard_vcont flag if we can't
6576    do a process-wide wildcard resume (vCont;c:pPID.-1).  */
6577
6578 static void
6579 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6580 {
6581   struct notif_client *notif = &notif_client_stop;
6582
6583   remote_notif_get_pending_events (notif);
6584   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6585                  check_pending_event_prevents_wildcard_vcont_callback,
6586                  may_global_wildcard);
6587 }
6588
6589 /* Remove stop replies in the queue if its pid is equal to the given
6590    inferior's pid.  */
6591
6592 static int
6593 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6594                                 QUEUE_ITER (stop_reply_p) *iter,
6595                                 stop_reply_p event,
6596                                 void *data)
6597 {
6598   struct queue_iter_param *param = (struct queue_iter_param *) data;
6599   struct inferior *inf = (struct inferior *) param->input;
6600
6601   if (ptid_get_pid (event->ptid) == inf->pid)
6602     {
6603       stop_reply_xfree (event);
6604       QUEUE_remove_elem (stop_reply_p, q, iter);
6605     }
6606
6607   return 1;
6608 }
6609
6610 /* Discard all pending stop replies of inferior INF.  */
6611
6612 static void
6613 discard_pending_stop_replies (struct inferior *inf)
6614 {
6615   struct queue_iter_param param;
6616   struct stop_reply *reply;
6617   struct remote_state *rs = get_remote_state ();
6618   struct remote_notif_state *rns = rs->notif_state;
6619
6620   /* This function can be notified when an inferior exists.  When the
6621      target is not remote, the notification state is NULL.  */
6622   if (rs->remote_desc == NULL)
6623     return;
6624
6625   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6626
6627   /* Discard the in-flight notification.  */
6628   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6629     {
6630       stop_reply_xfree (reply);
6631       rns->pending_event[notif_client_stop.id] = NULL;
6632     }
6633
6634   param.input = inf;
6635   param.output = NULL;
6636   /* Discard the stop replies we have already pulled with
6637      vStopped.  */
6638   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6639                  remove_stop_reply_for_inferior, &param);
6640 }
6641
6642 /* If its remote state is equal to the given remote state,
6643    remove EVENT from the stop reply queue.  */
6644
6645 static int
6646 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6647                                    QUEUE_ITER (stop_reply_p) *iter,
6648                                    stop_reply_p event,
6649                                    void *data)
6650 {
6651   struct queue_iter_param *param = (struct queue_iter_param *) data;
6652   struct remote_state *rs = (struct remote_state *) param->input;
6653
6654   if (event->rs == rs)
6655     {
6656       stop_reply_xfree (event);
6657       QUEUE_remove_elem (stop_reply_p, q, iter);
6658     }
6659
6660   return 1;
6661 }
6662
6663 /* Discard the stop replies for RS in stop_reply_queue.  */
6664
6665 static void
6666 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6667 {
6668   struct queue_iter_param param;
6669
6670   param.input = rs;
6671   param.output = NULL;
6672   /* Discard the stop replies we have already pulled with
6673      vStopped.  */
6674   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6675                  remove_stop_reply_of_remote_state, &param);
6676 }
6677
6678 /* A parameter to pass data in and out.  */
6679
6680 static int
6681 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6682                                    QUEUE_ITER (stop_reply_p) *iter,
6683                                    stop_reply_p event,
6684                                    void *data)
6685 {
6686   struct queue_iter_param *param = (struct queue_iter_param *) data;
6687   ptid_t *ptid = (ptid_t *) param->input;
6688
6689   if (ptid_match (event->ptid, *ptid))
6690     {
6691       param->output = event;
6692       QUEUE_remove_elem (stop_reply_p, q, iter);
6693       return 0;
6694     }
6695
6696   return 1;
6697 }
6698
6699 /* Remove the first reply in 'stop_reply_queue' which matches
6700    PTID.  */
6701
6702 static struct stop_reply *
6703 remote_notif_remove_queued_reply (ptid_t ptid)
6704 {
6705   struct queue_iter_param param;
6706
6707   param.input = &ptid;
6708   param.output = NULL;
6709
6710   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6711                  remote_notif_remove_once_on_match, &param);
6712   if (notif_debug)
6713     fprintf_unfiltered (gdb_stdlog,
6714                         "notif: discard queued event: 'Stop' in %s\n",
6715                         target_pid_to_str (ptid));
6716
6717   return param.output;
6718 }
6719
6720 /* Look for a queued stop reply belonging to PTID.  If one is found,
6721    remove it from the queue, and return it.  Returns NULL if none is
6722    found.  If there are still queued events left to process, tell the
6723    event loop to get back to target_wait soon.  */
6724
6725 static struct stop_reply *
6726 queued_stop_reply (ptid_t ptid)
6727 {
6728   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6729
6730   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6731     /* There's still at least an event left.  */
6732     mark_async_event_handler (remote_async_inferior_event_token);
6733
6734   return r;
6735 }
6736
6737 /* Push a fully parsed stop reply in the stop reply queue.  Since we
6738    know that we now have at least one queued event left to pass to the
6739    core side, tell the event loop to get back to target_wait soon.  */
6740
6741 static void
6742 push_stop_reply (struct stop_reply *new_event)
6743 {
6744   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6745
6746   if (notif_debug)
6747     fprintf_unfiltered (gdb_stdlog,
6748                         "notif: push 'Stop' %s to queue %d\n",
6749                         target_pid_to_str (new_event->ptid),
6750                         QUEUE_length (stop_reply_p,
6751                                       stop_reply_queue));
6752
6753   mark_async_event_handler (remote_async_inferior_event_token);
6754 }
6755
6756 static int
6757 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6758                               QUEUE_ITER (stop_reply_p) *iter,
6759                               struct stop_reply *event,
6760                               void *data)
6761 {
6762   ptid_t *ptid = (ptid_t *) data;
6763
6764   return !(ptid_equal (*ptid, event->ptid)
6765            && event->ws.kind == TARGET_WAITKIND_STOPPED);
6766 }
6767
6768 /* Returns true if we have a stop reply for PTID.  */
6769
6770 static int
6771 peek_stop_reply (ptid_t ptid)
6772 {
6773   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6774                          stop_reply_match_ptid_and_ws, &ptid);
6775 }
6776
6777 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
6778    starting with P and ending with PEND matches PREFIX.  */
6779
6780 static int
6781 strprefix (const char *p, const char *pend, const char *prefix)
6782 {
6783   for ( ; p < pend; p++, prefix++)
6784     if (*p != *prefix)
6785       return 0;
6786   return *prefix == '\0';
6787 }
6788
6789 /* Parse the stop reply in BUF.  Either the function succeeds, and the
6790    result is stored in EVENT, or throws an error.  */
6791
6792 static void
6793 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6794 {
6795   struct remote_arch_state *rsa = get_remote_arch_state ();
6796   ULONGEST addr;
6797   char *p;
6798   int skipregs = 0;
6799
6800   event->ptid = null_ptid;
6801   event->rs = get_remote_state ();
6802   event->ws.kind = TARGET_WAITKIND_IGNORE;
6803   event->ws.value.integer = 0;
6804   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6805   event->regcache = NULL;
6806   event->core = -1;
6807
6808   switch (buf[0])
6809     {
6810     case 'T':           /* Status with PC, SP, FP, ...  */
6811       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
6812       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
6813             ss = signal number
6814             n... = register number
6815             r... = register contents
6816       */
6817
6818       p = &buf[3];      /* after Txx */
6819       while (*p)
6820         {
6821           char *p1;
6822           int fieldsize;
6823
6824           p1 = strchr (p, ':');
6825           if (p1 == NULL)
6826             error (_("Malformed packet(a) (missing colon): %s\n\
6827 Packet: '%s'\n"),
6828                    p, buf);
6829           if (p == p1)
6830             error (_("Malformed packet(a) (missing register number): %s\n\
6831 Packet: '%s'\n"),
6832                    p, buf);
6833
6834           /* Some "registers" are actually extended stop information.
6835              Note if you're adding a new entry here: GDB 7.9 and
6836              earlier assume that all register "numbers" that start
6837              with an hex digit are real register numbers.  Make sure
6838              the server only sends such a packet if it knows the
6839              client understands it.  */
6840
6841           if (strprefix (p, p1, "thread"))
6842             event->ptid = read_ptid (++p1, &p);
6843           else if (strprefix (p, p1, "syscall_entry"))
6844             {
6845               ULONGEST sysno;
6846
6847               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6848               p = unpack_varlen_hex (++p1, &sysno);
6849               event->ws.value.syscall_number = (int) sysno;
6850             }
6851           else if (strprefix (p, p1, "syscall_return"))
6852             {
6853               ULONGEST sysno;
6854
6855               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6856               p = unpack_varlen_hex (++p1, &sysno);
6857               event->ws.value.syscall_number = (int) sysno;
6858             }
6859           else if (strprefix (p, p1, "watch")
6860                    || strprefix (p, p1, "rwatch")
6861                    || strprefix (p, p1, "awatch"))
6862             {
6863               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6864               p = unpack_varlen_hex (++p1, &addr);
6865               event->watch_data_address = (CORE_ADDR) addr;
6866             }
6867           else if (strprefix (p, p1, "swbreak"))
6868             {
6869               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6870
6871               /* Make sure the stub doesn't forget to indicate support
6872                  with qSupported.  */
6873               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6874                 error (_("Unexpected swbreak stop reason"));
6875
6876               /* The value part is documented as "must be empty",
6877                  though we ignore it, in case we ever decide to make
6878                  use of it in a backward compatible way.  */
6879               p = strchrnul (p1 + 1, ';');
6880             }
6881           else if (strprefix (p, p1, "hwbreak"))
6882             {
6883               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6884
6885               /* Make sure the stub doesn't forget to indicate support
6886                  with qSupported.  */
6887               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6888                 error (_("Unexpected hwbreak stop reason"));
6889
6890               /* See above.  */
6891               p = strchrnul (p1 + 1, ';');
6892             }
6893           else if (strprefix (p, p1, "library"))
6894             {
6895               event->ws.kind = TARGET_WAITKIND_LOADED;
6896               p = strchrnul (p1 + 1, ';');
6897             }
6898           else if (strprefix (p, p1, "replaylog"))
6899             {
6900               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6901               /* p1 will indicate "begin" or "end", but it makes
6902                  no difference for now, so ignore it.  */
6903               p = strchrnul (p1 + 1, ';');
6904             }
6905           else if (strprefix (p, p1, "core"))
6906             {
6907               ULONGEST c;
6908
6909               p = unpack_varlen_hex (++p1, &c);
6910               event->core = c;
6911             }
6912           else if (strprefix (p, p1, "fork"))
6913             {
6914               event->ws.value.related_pid = read_ptid (++p1, &p);
6915               event->ws.kind = TARGET_WAITKIND_FORKED;
6916             }
6917           else if (strprefix (p, p1, "vfork"))
6918             {
6919               event->ws.value.related_pid = read_ptid (++p1, &p);
6920               event->ws.kind = TARGET_WAITKIND_VFORKED;
6921             }
6922           else if (strprefix (p, p1, "vforkdone"))
6923             {
6924               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6925               p = strchrnul (p1 + 1, ';');
6926             }
6927           else if (strprefix (p, p1, "exec"))
6928             {
6929               ULONGEST ignored;
6930               char pathname[PATH_MAX];
6931               int pathlen;
6932
6933               /* Determine the length of the execd pathname.  */
6934               p = unpack_varlen_hex (++p1, &ignored);
6935               pathlen = (p - p1) / 2;
6936
6937               /* Save the pathname for event reporting and for
6938                  the next run command.  */
6939               hex2bin (p1, (gdb_byte *) pathname, pathlen);
6940               pathname[pathlen] = '\0';
6941
6942               /* This is freed during event handling.  */
6943               event->ws.value.execd_pathname = xstrdup (pathname);
6944               event->ws.kind = TARGET_WAITKIND_EXECD;
6945
6946               /* Skip the registers included in this packet, since
6947                  they may be for an architecture different from the
6948                  one used by the original program.  */
6949               skipregs = 1;
6950             }
6951           else if (strprefix (p, p1, "create"))
6952             {
6953               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6954               p = strchrnul (p1 + 1, ';');
6955             }
6956           else
6957             {
6958               ULONGEST pnum;
6959               char *p_temp;
6960
6961               if (skipregs)
6962                 {
6963                   p = strchrnul (p1 + 1, ';');
6964                   p++;
6965                   continue;
6966                 }
6967
6968               /* Maybe a real ``P'' register number.  */
6969               p_temp = unpack_varlen_hex (p, &pnum);
6970               /* If the first invalid character is the colon, we got a
6971                  register number.  Otherwise, it's an unknown stop
6972                  reason.  */
6973               if (p_temp == p1)
6974                 {
6975                   struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6976                   cached_reg_t cached_reg;
6977
6978                   if (reg == NULL)
6979                     error (_("Remote sent bad register number %s: %s\n\
6980 Packet: '%s'\n"),
6981                            hex_string (pnum), p, buf);
6982
6983                   cached_reg.num = reg->regnum;
6984
6985                   p = p1 + 1;
6986                   fieldsize = hex2bin (p, cached_reg.data,
6987                                        register_size (target_gdbarch (),
6988                                                       reg->regnum));
6989                   p += 2 * fieldsize;
6990                   if (fieldsize < register_size (target_gdbarch (),
6991                                                  reg->regnum))
6992                     warning (_("Remote reply is too short: %s"), buf);
6993
6994                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6995                 }
6996               else
6997                 {
6998                   /* Not a number.  Silently skip unknown optional
6999                      info.  */
7000                   p = strchrnul (p1 + 1, ';');
7001                 }
7002             }
7003
7004           if (*p != ';')
7005             error (_("Remote register badly formatted: %s\nhere: %s"),
7006                    buf, p);
7007           ++p;
7008         }
7009
7010       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7011         break;
7012
7013       /* fall through */
7014     case 'S':           /* Old style status, just signal only.  */
7015       {
7016         int sig;
7017
7018         event->ws.kind = TARGET_WAITKIND_STOPPED;
7019         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7020         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7021           event->ws.value.sig = (enum gdb_signal) sig;
7022         else
7023           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7024       }
7025       break;
7026     case 'w':           /* Thread exited.  */
7027       {
7028         char *p;
7029         ULONGEST value;
7030
7031         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7032         p = unpack_varlen_hex (&buf[1], &value);
7033         event->ws.value.integer = value;
7034         if (*p != ';')
7035           error (_("stop reply packet badly formatted: %s"), buf);
7036         event->ptid = read_ptid (++p, NULL);
7037         break;
7038       }
7039     case 'W':           /* Target exited.  */
7040     case 'X':
7041       {
7042         char *p;
7043         int pid;
7044         ULONGEST value;
7045
7046         /* GDB used to accept only 2 hex chars here.  Stubs should
7047            only send more if they detect GDB supports multi-process
7048            support.  */
7049         p = unpack_varlen_hex (&buf[1], &value);
7050
7051         if (buf[0] == 'W')
7052           {
7053             /* The remote process exited.  */
7054             event->ws.kind = TARGET_WAITKIND_EXITED;
7055             event->ws.value.integer = value;
7056           }
7057         else
7058           {
7059             /* The remote process exited with a signal.  */
7060             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7061             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7062               event->ws.value.sig = (enum gdb_signal) value;
7063             else
7064               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7065           }
7066
7067         /* If no process is specified, assume inferior_ptid.  */
7068         pid = ptid_get_pid (inferior_ptid);
7069         if (*p == '\0')
7070           ;
7071         else if (*p == ';')
7072           {
7073             p++;
7074
7075             if (*p == '\0')
7076               ;
7077             else if (startswith (p, "process:"))
7078               {
7079                 ULONGEST upid;
7080
7081                 p += sizeof ("process:") - 1;
7082                 unpack_varlen_hex (p, &upid);
7083                 pid = upid;
7084               }
7085             else
7086               error (_("unknown stop reply packet: %s"), buf);
7087           }
7088         else
7089           error (_("unknown stop reply packet: %s"), buf);
7090         event->ptid = pid_to_ptid (pid);
7091       }
7092       break;
7093     case 'N':
7094       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7095       event->ptid = minus_one_ptid;
7096       break;
7097     }
7098
7099   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7100     error (_("No process or thread specified in stop reply: %s"), buf);
7101 }
7102
7103 /* When the stub wants to tell GDB about a new notification reply, it
7104    sends a notification (%Stop, for example).  Those can come it at
7105    any time, hence, we have to make sure that any pending
7106    putpkt/getpkt sequence we're making is finished, before querying
7107    the stub for more events with the corresponding ack command
7108    (vStopped, for example).  E.g., if we started a vStopped sequence
7109    immediately upon receiving the notification, something like this
7110    could happen:
7111
7112     1.1) --> Hg 1
7113     1.2) <-- OK
7114     1.3) --> g
7115     1.4) <-- %Stop
7116     1.5) --> vStopped
7117     1.6) <-- (registers reply to step #1.3)
7118
7119    Obviously, the reply in step #1.6 would be unexpected to a vStopped
7120    query.
7121
7122    To solve this, whenever we parse a %Stop notification successfully,
7123    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7124    doing whatever we were doing:
7125
7126     2.1) --> Hg 1
7127     2.2) <-- OK
7128     2.3) --> g
7129     2.4) <-- %Stop
7130       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7131     2.5) <-- (registers reply to step #2.3)
7132
7133    Eventualy after step #2.5, we return to the event loop, which
7134    notices there's an event on the
7135    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7136    associated callback --- the function below.  At this point, we're
7137    always safe to start a vStopped sequence. :
7138
7139     2.6) --> vStopped
7140     2.7) <-- T05 thread:2
7141     2.8) --> vStopped
7142     2.9) --> OK
7143 */
7144
7145 void
7146 remote_notif_get_pending_events (struct notif_client *nc)
7147 {
7148   struct remote_state *rs = get_remote_state ();
7149
7150   if (rs->notif_state->pending_event[nc->id] != NULL)
7151     {
7152       if (notif_debug)
7153         fprintf_unfiltered (gdb_stdlog,
7154                             "notif: process: '%s' ack pending event\n",
7155                             nc->name);
7156
7157       /* acknowledge */
7158       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7159       rs->notif_state->pending_event[nc->id] = NULL;
7160
7161       while (1)
7162         {
7163           getpkt (&rs->buf, &rs->buf_size, 0);
7164           if (strcmp (rs->buf, "OK") == 0)
7165             break;
7166           else
7167             remote_notif_ack (nc, rs->buf);
7168         }
7169     }
7170   else
7171     {
7172       if (notif_debug)
7173         fprintf_unfiltered (gdb_stdlog,
7174                             "notif: process: '%s' no pending reply\n",
7175                             nc->name);
7176     }
7177 }
7178
7179 /* Called when it is decided that STOP_REPLY holds the info of the
7180    event that is to be returned to the core.  This function always
7181    destroys STOP_REPLY.  */
7182
7183 static ptid_t
7184 process_stop_reply (struct stop_reply *stop_reply,
7185                     struct target_waitstatus *status)
7186 {
7187   ptid_t ptid;
7188
7189   *status = stop_reply->ws;
7190   ptid = stop_reply->ptid;
7191
7192   /* If no thread/process was reported by the stub, assume the current
7193      inferior.  */
7194   if (ptid_equal (ptid, null_ptid))
7195     ptid = inferior_ptid;
7196
7197   if (status->kind != TARGET_WAITKIND_EXITED
7198       && status->kind != TARGET_WAITKIND_SIGNALLED
7199       && status->kind != TARGET_WAITKIND_NO_RESUMED)
7200     {
7201       struct private_thread_info *remote_thr;
7202
7203       /* Expedited registers.  */
7204       if (stop_reply->regcache)
7205         {
7206           struct regcache *regcache
7207             = get_thread_arch_regcache (ptid, target_gdbarch ());
7208           cached_reg_t *reg;
7209           int ix;
7210
7211           for (ix = 0;
7212                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
7213                ix++)
7214             regcache_raw_supply (regcache, reg->num, reg->data);
7215           VEC_free (cached_reg_t, stop_reply->regcache);
7216         }
7217
7218       remote_notice_new_inferior (ptid, 0);
7219       remote_thr = get_private_info_ptid (ptid);
7220       remote_thr->core = stop_reply->core;
7221       remote_thr->stop_reason = stop_reply->stop_reason;
7222       remote_thr->watch_data_address = stop_reply->watch_data_address;
7223       remote_thr->vcont_resumed = 0;
7224     }
7225
7226   stop_reply_xfree (stop_reply);
7227   return ptid;
7228 }
7229
7230 /* The non-stop mode version of target_wait.  */
7231
7232 static ptid_t
7233 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7234 {
7235   struct remote_state *rs = get_remote_state ();
7236   struct stop_reply *stop_reply;
7237   int ret;
7238   int is_notif = 0;
7239
7240   /* If in non-stop mode, get out of getpkt even if a
7241      notification is received.  */
7242
7243   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7244                               0 /* forever */, &is_notif);
7245   while (1)
7246     {
7247       if (ret != -1 && !is_notif)
7248         switch (rs->buf[0])
7249           {
7250           case 'E':             /* Error of some sort.  */
7251             /* We're out of sync with the target now.  Did it continue
7252                or not?  We can't tell which thread it was in non-stop,
7253                so just ignore this.  */
7254             warning (_("Remote failure reply: %s"), rs->buf);
7255             break;
7256           case 'O':             /* Console output.  */
7257             remote_console_output (rs->buf + 1);
7258             break;
7259           default:
7260             warning (_("Invalid remote reply: %s"), rs->buf);
7261             break;
7262           }
7263
7264       /* Acknowledge a pending stop reply that may have arrived in the
7265          mean time.  */
7266       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7267         remote_notif_get_pending_events (&notif_client_stop);
7268
7269       /* If indeed we noticed a stop reply, we're done.  */
7270       stop_reply = queued_stop_reply (ptid);
7271       if (stop_reply != NULL)
7272         return process_stop_reply (stop_reply, status);
7273
7274       /* Still no event.  If we're just polling for an event, then
7275          return to the event loop.  */
7276       if (options & TARGET_WNOHANG)
7277         {
7278           status->kind = TARGET_WAITKIND_IGNORE;
7279           return minus_one_ptid;
7280         }
7281
7282       /* Otherwise do a blocking wait.  */
7283       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7284                                   1 /* forever */, &is_notif);
7285     }
7286 }
7287
7288 /* Wait until the remote machine stops, then return, storing status in
7289    STATUS just as `wait' would.  */
7290
7291 static ptid_t
7292 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7293 {
7294   struct remote_state *rs = get_remote_state ();
7295   ptid_t event_ptid = null_ptid;
7296   char *buf;
7297   struct stop_reply *stop_reply;
7298
7299  again:
7300
7301   status->kind = TARGET_WAITKIND_IGNORE;
7302   status->value.integer = 0;
7303
7304   stop_reply = queued_stop_reply (ptid);
7305   if (stop_reply != NULL)
7306     return process_stop_reply (stop_reply, status);
7307
7308   if (rs->cached_wait_status)
7309     /* Use the cached wait status, but only once.  */
7310     rs->cached_wait_status = 0;
7311   else
7312     {
7313       int ret;
7314       int is_notif;
7315       int forever = ((options & TARGET_WNOHANG) == 0
7316                      && wait_forever_enabled_p);
7317
7318       if (!rs->waiting_for_stop_reply)
7319         {
7320           status->kind = TARGET_WAITKIND_NO_RESUMED;
7321           return minus_one_ptid;
7322         }
7323
7324       /* FIXME: cagney/1999-09-27: If we're in async mode we should
7325          _never_ wait for ever -> test on target_is_async_p().
7326          However, before we do that we need to ensure that the caller
7327          knows how to take the target into/out of async mode.  */
7328       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7329                                   forever, &is_notif);
7330
7331       /* GDB gets a notification.  Return to core as this event is
7332          not interesting.  */
7333       if (ret != -1 && is_notif)
7334         return minus_one_ptid;
7335
7336       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7337         return minus_one_ptid;
7338     }
7339
7340   buf = rs->buf;
7341
7342   /* Assume that the target has acknowledged Ctrl-C unless we receive
7343      an 'F' or 'O' packet.  */
7344   if (buf[0] != 'F' && buf[0] != 'O')
7345     rs->ctrlc_pending_p = 0;
7346
7347   switch (buf[0])
7348     {
7349     case 'E':           /* Error of some sort.  */
7350       /* We're out of sync with the target now.  Did it continue or
7351          not?  Not is more likely, so report a stop.  */
7352       rs->waiting_for_stop_reply = 0;
7353
7354       warning (_("Remote failure reply: %s"), buf);
7355       status->kind = TARGET_WAITKIND_STOPPED;
7356       status->value.sig = GDB_SIGNAL_0;
7357       break;
7358     case 'F':           /* File-I/O request.  */
7359       /* GDB may access the inferior memory while handling the File-I/O
7360          request, but we don't want GDB accessing memory while waiting
7361          for a stop reply.  See the comments in putpkt_binary.  Set
7362          waiting_for_stop_reply to 0 temporarily.  */
7363       rs->waiting_for_stop_reply = 0;
7364       remote_fileio_request (buf, rs->ctrlc_pending_p);
7365       rs->ctrlc_pending_p = 0;
7366       /* GDB handled the File-I/O request, and the target is running
7367          again.  Keep waiting for events.  */
7368       rs->waiting_for_stop_reply = 1;
7369       break;
7370     case 'N': case 'T': case 'S': case 'X': case 'W':
7371       {
7372         struct stop_reply *stop_reply;
7373
7374         /* There is a stop reply to handle.  */
7375         rs->waiting_for_stop_reply = 0;
7376
7377         stop_reply
7378           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7379                                                       rs->buf);
7380
7381         event_ptid = process_stop_reply (stop_reply, status);
7382         break;
7383       }
7384     case 'O':           /* Console output.  */
7385       remote_console_output (buf + 1);
7386       break;
7387     case '\0':
7388       if (rs->last_sent_signal != GDB_SIGNAL_0)
7389         {
7390           /* Zero length reply means that we tried 'S' or 'C' and the
7391              remote system doesn't support it.  */
7392           target_terminal_ours_for_output ();
7393           printf_filtered
7394             ("Can't send signals to this remote system.  %s not sent.\n",
7395              gdb_signal_to_name (rs->last_sent_signal));
7396           rs->last_sent_signal = GDB_SIGNAL_0;
7397           target_terminal_inferior ();
7398
7399           strcpy (buf, rs->last_sent_step ? "s" : "c");
7400           putpkt (buf);
7401           break;
7402         }
7403       /* else fallthrough */
7404     default:
7405       warning (_("Invalid remote reply: %s"), buf);
7406       break;
7407     }
7408
7409   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7410     return minus_one_ptid;
7411   else if (status->kind == TARGET_WAITKIND_IGNORE)
7412     {
7413       /* Nothing interesting happened.  If we're doing a non-blocking
7414          poll, we're done.  Otherwise, go back to waiting.  */
7415       if (options & TARGET_WNOHANG)
7416         return minus_one_ptid;
7417       else
7418         goto again;
7419     }
7420   else if (status->kind != TARGET_WAITKIND_EXITED
7421            && status->kind != TARGET_WAITKIND_SIGNALLED)
7422     {
7423       if (!ptid_equal (event_ptid, null_ptid))
7424         record_currthread (rs, event_ptid);
7425       else
7426         event_ptid = inferior_ptid;
7427     }
7428   else
7429     /* A process exit.  Invalidate our notion of current thread.  */
7430     record_currthread (rs, minus_one_ptid);
7431
7432   return event_ptid;
7433 }
7434
7435 /* Wait until the remote machine stops, then return, storing status in
7436    STATUS just as `wait' would.  */
7437
7438 static ptid_t
7439 remote_wait (struct target_ops *ops,
7440              ptid_t ptid, struct target_waitstatus *status, int options)
7441 {
7442   ptid_t event_ptid;
7443
7444   if (target_is_non_stop_p ())
7445     event_ptid = remote_wait_ns (ptid, status, options);
7446   else
7447     event_ptid = remote_wait_as (ptid, status, options);
7448
7449   if (target_is_async_p ())
7450     {
7451       /* If there are are events left in the queue tell the event loop
7452          to return here.  */
7453       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7454         mark_async_event_handler (remote_async_inferior_event_token);
7455     }
7456
7457   return event_ptid;
7458 }
7459
7460 /* Fetch a single register using a 'p' packet.  */
7461
7462 static int
7463 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7464 {
7465   struct remote_state *rs = get_remote_state ();
7466   char *buf, *p;
7467   char regp[MAX_REGISTER_SIZE];
7468   int i;
7469
7470   if (packet_support (PACKET_p) == PACKET_DISABLE)
7471     return 0;
7472
7473   if (reg->pnum == -1)
7474     return 0;
7475
7476   p = rs->buf;
7477   *p++ = 'p';
7478   p += hexnumstr (p, reg->pnum);
7479   *p++ = '\0';
7480   putpkt (rs->buf);
7481   getpkt (&rs->buf, &rs->buf_size, 0);
7482
7483   buf = rs->buf;
7484
7485   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7486     {
7487     case PACKET_OK:
7488       break;
7489     case PACKET_UNKNOWN:
7490       return 0;
7491     case PACKET_ERROR:
7492       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7493              gdbarch_register_name (get_regcache_arch (regcache), 
7494                                     reg->regnum), 
7495              buf);
7496     }
7497
7498   /* If this register is unfetchable, tell the regcache.  */
7499   if (buf[0] == 'x')
7500     {
7501       regcache_raw_supply (regcache, reg->regnum, NULL);
7502       return 1;
7503     }
7504
7505   /* Otherwise, parse and supply the value.  */
7506   p = buf;
7507   i = 0;
7508   while (p[0] != 0)
7509     {
7510       if (p[1] == 0)
7511         error (_("fetch_register_using_p: early buf termination"));
7512
7513       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7514       p += 2;
7515     }
7516   regcache_raw_supply (regcache, reg->regnum, regp);
7517   return 1;
7518 }
7519
7520 /* Fetch the registers included in the target's 'g' packet.  */
7521
7522 static int
7523 send_g_packet (void)
7524 {
7525   struct remote_state *rs = get_remote_state ();
7526   int buf_len;
7527
7528   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7529   remote_send (&rs->buf, &rs->buf_size);
7530
7531   /* We can get out of synch in various cases.  If the first character
7532      in the buffer is not a hex character, assume that has happened
7533      and try to fetch another packet to read.  */
7534   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7535          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7536          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7537          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
7538     {
7539       if (remote_debug)
7540         fprintf_unfiltered (gdb_stdlog,
7541                             "Bad register packet; fetching a new packet\n");
7542       getpkt (&rs->buf, &rs->buf_size, 0);
7543     }
7544
7545   buf_len = strlen (rs->buf);
7546
7547   /* Sanity check the received packet.  */
7548   if (buf_len % 2 != 0)
7549     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7550
7551   return buf_len / 2;
7552 }
7553
7554 static void
7555 process_g_packet (struct regcache *regcache)
7556 {
7557   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7558   struct remote_state *rs = get_remote_state ();
7559   struct remote_arch_state *rsa = get_remote_arch_state ();
7560   int i, buf_len;
7561   char *p;
7562   char *regs;
7563
7564   buf_len = strlen (rs->buf);
7565
7566   /* Further sanity checks, with knowledge of the architecture.  */
7567   if (buf_len > 2 * rsa->sizeof_g_packet)
7568     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7569
7570   /* Save the size of the packet sent to us by the target.  It is used
7571      as a heuristic when determining the max size of packets that the
7572      target can safely receive.  */
7573   if (rsa->actual_register_packet_size == 0)
7574     rsa->actual_register_packet_size = buf_len;
7575
7576   /* If this is smaller than we guessed the 'g' packet would be,
7577      update our records.  A 'g' reply that doesn't include a register's
7578      value implies either that the register is not available, or that
7579      the 'p' packet must be used.  */
7580   if (buf_len < 2 * rsa->sizeof_g_packet)
7581     {
7582       long sizeof_g_packet = buf_len / 2;
7583
7584       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7585         {
7586           long offset = rsa->regs[i].offset;
7587           long reg_size = register_size (gdbarch, i);
7588
7589           if (rsa->regs[i].pnum == -1)
7590             continue;
7591
7592           if (offset >= sizeof_g_packet)
7593             rsa->regs[i].in_g_packet = 0;
7594           else if (offset + reg_size > sizeof_g_packet)
7595             error (_("Truncated register %d in remote 'g' packet"), i);
7596           else
7597             rsa->regs[i].in_g_packet = 1;
7598         }
7599
7600       /* Looks valid enough, we can assume this is the correct length
7601          for a 'g' packet.  It's important not to adjust
7602          rsa->sizeof_g_packet if we have truncated registers otherwise
7603          this "if" won't be run the next time the method is called
7604          with a packet of the same size and one of the internal errors
7605          below will trigger instead.  */
7606       rsa->sizeof_g_packet = sizeof_g_packet;
7607     }
7608
7609   regs = (char *) alloca (rsa->sizeof_g_packet);
7610
7611   /* Unimplemented registers read as all bits zero.  */
7612   memset (regs, 0, rsa->sizeof_g_packet);
7613
7614   /* Reply describes registers byte by byte, each byte encoded as two
7615      hex characters.  Suck them all up, then supply them to the
7616      register cacheing/storage mechanism.  */
7617
7618   p = rs->buf;
7619   for (i = 0; i < rsa->sizeof_g_packet; i++)
7620     {
7621       if (p[0] == 0 || p[1] == 0)
7622         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
7623         internal_error (__FILE__, __LINE__,
7624                         _("unexpected end of 'g' packet reply"));
7625
7626       if (p[0] == 'x' && p[1] == 'x')
7627         regs[i] = 0;            /* 'x' */
7628       else
7629         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7630       p += 2;
7631     }
7632
7633   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7634     {
7635       struct packet_reg *r = &rsa->regs[i];
7636       long reg_size = register_size (gdbarch, i);
7637
7638       if (r->in_g_packet)
7639         {
7640           if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7641             /* This shouldn't happen - we adjusted in_g_packet above.  */
7642             internal_error (__FILE__, __LINE__,
7643                             _("unexpected end of 'g' packet reply"));
7644           else if (rs->buf[r->offset * 2] == 'x')
7645             {
7646               gdb_assert (r->offset * 2 < strlen (rs->buf));
7647               /* The register isn't available, mark it as such (at
7648                  the same time setting the value to zero).  */
7649               regcache_raw_supply (regcache, r->regnum, NULL);
7650             }
7651           else
7652             regcache_raw_supply (regcache, r->regnum,
7653                                  regs + r->offset);
7654         }
7655     }
7656 }
7657
7658 static void
7659 fetch_registers_using_g (struct regcache *regcache)
7660 {
7661   send_g_packet ();
7662   process_g_packet (regcache);
7663 }
7664
7665 /* Make the remote selected traceframe match GDB's selected
7666    traceframe.  */
7667
7668 static void
7669 set_remote_traceframe (void)
7670 {
7671   int newnum;
7672   struct remote_state *rs = get_remote_state ();
7673
7674   if (rs->remote_traceframe_number == get_traceframe_number ())
7675     return;
7676
7677   /* Avoid recursion, remote_trace_find calls us again.  */
7678   rs->remote_traceframe_number = get_traceframe_number ();
7679
7680   newnum = target_trace_find (tfind_number,
7681                               get_traceframe_number (), 0, 0, NULL);
7682
7683   /* Should not happen.  If it does, all bets are off.  */
7684   if (newnum != get_traceframe_number ())
7685     warning (_("could not set remote traceframe"));
7686 }
7687
7688 static void
7689 remote_fetch_registers (struct target_ops *ops,
7690                         struct regcache *regcache, int regnum)
7691 {
7692   struct remote_arch_state *rsa = get_remote_arch_state ();
7693   int i;
7694
7695   set_remote_traceframe ();
7696   set_general_thread (inferior_ptid);
7697
7698   if (regnum >= 0)
7699     {
7700       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7701
7702       gdb_assert (reg != NULL);
7703
7704       /* If this register might be in the 'g' packet, try that first -
7705          we are likely to read more than one register.  If this is the
7706          first 'g' packet, we might be overly optimistic about its
7707          contents, so fall back to 'p'.  */
7708       if (reg->in_g_packet)
7709         {
7710           fetch_registers_using_g (regcache);
7711           if (reg->in_g_packet)
7712             return;
7713         }
7714
7715       if (fetch_register_using_p (regcache, reg))
7716         return;
7717
7718       /* This register is not available.  */
7719       regcache_raw_supply (regcache, reg->regnum, NULL);
7720
7721       return;
7722     }
7723
7724   fetch_registers_using_g (regcache);
7725
7726   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7727     if (!rsa->regs[i].in_g_packet)
7728       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7729         {
7730           /* This register is not available.  */
7731           regcache_raw_supply (regcache, i, NULL);
7732         }
7733 }
7734
7735 /* Prepare to store registers.  Since we may send them all (using a
7736    'G' request), we have to read out the ones we don't want to change
7737    first.  */
7738
7739 static void
7740 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7741 {
7742   struct remote_arch_state *rsa = get_remote_arch_state ();
7743   int i;
7744   gdb_byte buf[MAX_REGISTER_SIZE];
7745
7746   /* Make sure the entire registers array is valid.  */
7747   switch (packet_support (PACKET_P))
7748     {
7749     case PACKET_DISABLE:
7750     case PACKET_SUPPORT_UNKNOWN:
7751       /* Make sure all the necessary registers are cached.  */
7752       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7753         if (rsa->regs[i].in_g_packet)
7754           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7755       break;
7756     case PACKET_ENABLE:
7757       break;
7758     }
7759 }
7760
7761 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
7762    packet was not recognized.  */
7763
7764 static int
7765 store_register_using_P (const struct regcache *regcache, 
7766                         struct packet_reg *reg)
7767 {
7768   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7769   struct remote_state *rs = get_remote_state ();
7770   /* Try storing a single register.  */
7771   char *buf = rs->buf;
7772   gdb_byte regp[MAX_REGISTER_SIZE];
7773   char *p;
7774
7775   if (packet_support (PACKET_P) == PACKET_DISABLE)
7776     return 0;
7777
7778   if (reg->pnum == -1)
7779     return 0;
7780
7781   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7782   p = buf + strlen (buf);
7783   regcache_raw_collect (regcache, reg->regnum, regp);
7784   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7785   putpkt (rs->buf);
7786   getpkt (&rs->buf, &rs->buf_size, 0);
7787
7788   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7789     {
7790     case PACKET_OK:
7791       return 1;
7792     case PACKET_ERROR:
7793       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7794              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7795     case PACKET_UNKNOWN:
7796       return 0;
7797     default:
7798       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7799     }
7800 }
7801
7802 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7803    contents of the register cache buffer.  FIXME: ignores errors.  */
7804
7805 static void
7806 store_registers_using_G (const struct regcache *regcache)
7807 {
7808   struct remote_state *rs = get_remote_state ();
7809   struct remote_arch_state *rsa = get_remote_arch_state ();
7810   gdb_byte *regs;
7811   char *p;
7812
7813   /* Extract all the registers in the regcache copying them into a
7814      local buffer.  */
7815   {
7816     int i;
7817
7818     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7819     memset (regs, 0, rsa->sizeof_g_packet);
7820     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7821       {
7822         struct packet_reg *r = &rsa->regs[i];
7823
7824         if (r->in_g_packet)
7825           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7826       }
7827   }
7828
7829   /* Command describes registers byte by byte,
7830      each byte encoded as two hex characters.  */
7831   p = rs->buf;
7832   *p++ = 'G';
7833   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7834      updated.  */
7835   bin2hex (regs, p, rsa->sizeof_g_packet);
7836   putpkt (rs->buf);
7837   getpkt (&rs->buf, &rs->buf_size, 0);
7838   if (packet_check_result (rs->buf) == PACKET_ERROR)
7839     error (_("Could not write registers; remote failure reply '%s'"), 
7840            rs->buf);
7841 }
7842
7843 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7844    of the register cache buffer.  FIXME: ignores errors.  */
7845
7846 static void
7847 remote_store_registers (struct target_ops *ops,
7848                         struct regcache *regcache, int regnum)
7849 {
7850   struct remote_arch_state *rsa = get_remote_arch_state ();
7851   int i;
7852
7853   set_remote_traceframe ();
7854   set_general_thread (inferior_ptid);
7855
7856   if (regnum >= 0)
7857     {
7858       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7859
7860       gdb_assert (reg != NULL);
7861
7862       /* Always prefer to store registers using the 'P' packet if
7863          possible; we often change only a small number of registers.
7864          Sometimes we change a larger number; we'd need help from a
7865          higher layer to know to use 'G'.  */
7866       if (store_register_using_P (regcache, reg))
7867         return;
7868
7869       /* For now, don't complain if we have no way to write the
7870          register.  GDB loses track of unavailable registers too
7871          easily.  Some day, this may be an error.  We don't have
7872          any way to read the register, either...  */
7873       if (!reg->in_g_packet)
7874         return;
7875
7876       store_registers_using_G (regcache);
7877       return;
7878     }
7879
7880   store_registers_using_G (regcache);
7881
7882   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7883     if (!rsa->regs[i].in_g_packet)
7884       if (!store_register_using_P (regcache, &rsa->regs[i]))
7885         /* See above for why we do not issue an error here.  */
7886         continue;
7887 }
7888 \f
7889
7890 /* Return the number of hex digits in num.  */
7891
7892 static int
7893 hexnumlen (ULONGEST num)
7894 {
7895   int i;
7896
7897   for (i = 0; num != 0; i++)
7898     num >>= 4;
7899
7900   return std::max (i, 1);
7901 }
7902
7903 /* Set BUF to the minimum number of hex digits representing NUM.  */
7904
7905 static int
7906 hexnumstr (char *buf, ULONGEST num)
7907 {
7908   int len = hexnumlen (num);
7909
7910   return hexnumnstr (buf, num, len);
7911 }
7912
7913
7914 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
7915
7916 static int
7917 hexnumnstr (char *buf, ULONGEST num, int width)
7918 {
7919   int i;
7920
7921   buf[width] = '\0';
7922
7923   for (i = width - 1; i >= 0; i--)
7924     {
7925       buf[i] = "0123456789abcdef"[(num & 0xf)];
7926       num >>= 4;
7927     }
7928
7929   return width;
7930 }
7931
7932 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
7933
7934 static CORE_ADDR
7935 remote_address_masked (CORE_ADDR addr)
7936 {
7937   unsigned int address_size = remote_address_size;
7938
7939   /* If "remoteaddresssize" was not set, default to target address size.  */
7940   if (!address_size)
7941     address_size = gdbarch_addr_bit (target_gdbarch ());
7942
7943   if (address_size > 0
7944       && address_size < (sizeof (ULONGEST) * 8))
7945     {
7946       /* Only create a mask when that mask can safely be constructed
7947          in a ULONGEST variable.  */
7948       ULONGEST mask = 1;
7949
7950       mask = (mask << address_size) - 1;
7951       addr &= mask;
7952     }
7953   return addr;
7954 }
7955
7956 /* Determine whether the remote target supports binary downloading.
7957    This is accomplished by sending a no-op memory write of zero length
7958    to the target at the specified address. It does not suffice to send
7959    the whole packet, since many stubs strip the eighth bit and
7960    subsequently compute a wrong checksum, which causes real havoc with
7961    remote_write_bytes.
7962
7963    NOTE: This can still lose if the serial line is not eight-bit
7964    clean.  In cases like this, the user should clear "remote
7965    X-packet".  */
7966
7967 static void
7968 check_binary_download (CORE_ADDR addr)
7969 {
7970   struct remote_state *rs = get_remote_state ();
7971
7972   switch (packet_support (PACKET_X))
7973     {
7974     case PACKET_DISABLE:
7975       break;
7976     case PACKET_ENABLE:
7977       break;
7978     case PACKET_SUPPORT_UNKNOWN:
7979       {
7980         char *p;
7981
7982         p = rs->buf;
7983         *p++ = 'X';
7984         p += hexnumstr (p, (ULONGEST) addr);
7985         *p++ = ',';
7986         p += hexnumstr (p, (ULONGEST) 0);
7987         *p++ = ':';
7988         *p = '\0';
7989
7990         putpkt_binary (rs->buf, (int) (p - rs->buf));
7991         getpkt (&rs->buf, &rs->buf_size, 0);
7992
7993         if (rs->buf[0] == '\0')
7994           {
7995             if (remote_debug)
7996               fprintf_unfiltered (gdb_stdlog,
7997                                   "binary downloading NOT "
7998                                   "supported by target\n");
7999             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8000           }
8001         else
8002           {
8003             if (remote_debug)
8004               fprintf_unfiltered (gdb_stdlog,
8005                                   "binary downloading supported by target\n");
8006             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8007           }
8008         break;
8009       }
8010     }
8011 }
8012
8013 /* Helper function to resize the payload in order to try to get a good
8014    alignment.  We try to write an amount of data such that the next write will
8015    start on an address aligned on REMOTE_ALIGN_WRITES.  */
8016
8017 static int
8018 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8019 {
8020   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8021 }
8022
8023 /* Write memory data directly to the remote machine.
8024    This does not inform the data cache; the data cache uses this.
8025    HEADER is the starting part of the packet.
8026    MEMADDR is the address in the remote memory space.
8027    MYADDR is the address of the buffer in our space.
8028    LEN_UNITS is the number of addressable units to write.
8029    UNIT_SIZE is the length in bytes of an addressable unit.
8030    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8031    should send data as binary ('X'), or hex-encoded ('M').
8032
8033    The function creates packet of the form
8034        <HEADER><ADDRESS>,<LENGTH>:<DATA>
8035
8036    where encoding of <DATA> is terminated by PACKET_FORMAT.
8037
8038    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8039    are omitted.
8040
8041    Return the transferred status, error or OK (an
8042    'enum target_xfer_status' value).  Save the number of addressable units
8043    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
8044
8045    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8046    exchange between gdb and the stub could look like (?? in place of the
8047    checksum):
8048
8049    -> $m1000,4#??
8050    <- aaaabbbbccccdddd
8051
8052    -> $M1000,3:eeeeffffeeee#??
8053    <- OK
8054
8055    -> $m1000,4#??
8056    <- eeeeffffeeeedddd  */
8057
8058 static enum target_xfer_status
8059 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8060                         const gdb_byte *myaddr, ULONGEST len_units,
8061                         int unit_size, ULONGEST *xfered_len_units,
8062                         char packet_format, int use_length)
8063 {
8064   struct remote_state *rs = get_remote_state ();
8065   char *p;
8066   char *plen = NULL;
8067   int plenlen = 0;
8068   int todo_units;
8069   int units_written;
8070   int payload_capacity_bytes;
8071   int payload_length_bytes;
8072
8073   if (packet_format != 'X' && packet_format != 'M')
8074     internal_error (__FILE__, __LINE__,
8075                     _("remote_write_bytes_aux: bad packet format"));
8076
8077   if (len_units == 0)
8078     return TARGET_XFER_EOF;
8079
8080   payload_capacity_bytes = get_memory_write_packet_size ();
8081
8082   /* The packet buffer will be large enough for the payload;
8083      get_memory_packet_size ensures this.  */
8084   rs->buf[0] = '\0';
8085
8086   /* Compute the size of the actual payload by subtracting out the
8087      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
8088
8089   payload_capacity_bytes -= strlen ("$,:#NN");
8090   if (!use_length)
8091     /* The comma won't be used.  */
8092     payload_capacity_bytes += 1;
8093   payload_capacity_bytes -= strlen (header);
8094   payload_capacity_bytes -= hexnumlen (memaddr);
8095
8096   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
8097
8098   strcat (rs->buf, header);
8099   p = rs->buf + strlen (header);
8100
8101   /* Compute a best guess of the number of bytes actually transfered.  */
8102   if (packet_format == 'X')
8103     {
8104       /* Best guess at number of bytes that will fit.  */
8105       todo_units = std::min (len_units,
8106                              (ULONGEST) payload_capacity_bytes / unit_size);
8107       if (use_length)
8108         payload_capacity_bytes -= hexnumlen (todo_units);
8109       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8110     }
8111   else
8112     {
8113       /* Number of bytes that will fit.  */
8114       todo_units
8115         = std::min (len_units,
8116                     (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8117       if (use_length)
8118         payload_capacity_bytes -= hexnumlen (todo_units);
8119       todo_units = std::min (todo_units,
8120                              (payload_capacity_bytes / unit_size) / 2);
8121     }
8122
8123   if (todo_units <= 0)
8124     internal_error (__FILE__, __LINE__,
8125                     _("minimum packet size too small to write data"));
8126
8127   /* If we already need another packet, then try to align the end
8128      of this packet to a useful boundary.  */
8129   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8130     todo_units = align_for_efficient_write (todo_units, memaddr);
8131
8132   /* Append "<memaddr>".  */
8133   memaddr = remote_address_masked (memaddr);
8134   p += hexnumstr (p, (ULONGEST) memaddr);
8135
8136   if (use_length)
8137     {
8138       /* Append ",".  */
8139       *p++ = ',';
8140
8141       /* Append the length and retain its location and size.  It may need to be
8142          adjusted once the packet body has been created.  */
8143       plen = p;
8144       plenlen = hexnumstr (p, (ULONGEST) todo_units);
8145       p += plenlen;
8146     }
8147
8148   /* Append ":".  */
8149   *p++ = ':';
8150   *p = '\0';
8151
8152   /* Append the packet body.  */
8153   if (packet_format == 'X')
8154     {
8155       /* Binary mode.  Send target system values byte by byte, in
8156          increasing byte addresses.  Only escape certain critical
8157          characters.  */
8158       payload_length_bytes =
8159           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8160                                 &units_written, payload_capacity_bytes);
8161
8162       /* If not all TODO units fit, then we'll need another packet.  Make
8163          a second try to keep the end of the packet aligned.  Don't do
8164          this if the packet is tiny.  */
8165       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8166         {
8167           int new_todo_units;
8168
8169           new_todo_units = align_for_efficient_write (units_written, memaddr);
8170
8171           if (new_todo_units != units_written)
8172             payload_length_bytes =
8173                 remote_escape_output (myaddr, new_todo_units, unit_size,
8174                                       (gdb_byte *) p, &units_written,
8175                                       payload_capacity_bytes);
8176         }
8177
8178       p += payload_length_bytes;
8179       if (use_length && units_written < todo_units)
8180         {
8181           /* Escape chars have filled up the buffer prematurely,
8182              and we have actually sent fewer units than planned.
8183              Fix-up the length field of the packet.  Use the same
8184              number of characters as before.  */
8185           plen += hexnumnstr (plen, (ULONGEST) units_written,
8186                               plenlen);
8187           *plen = ':';  /* overwrite \0 from hexnumnstr() */
8188         }
8189     }
8190   else
8191     {
8192       /* Normal mode: Send target system values byte by byte, in
8193          increasing byte addresses.  Each byte is encoded as a two hex
8194          value.  */
8195       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8196       units_written = todo_units;
8197     }
8198
8199   putpkt_binary (rs->buf, (int) (p - rs->buf));
8200   getpkt (&rs->buf, &rs->buf_size, 0);
8201
8202   if (rs->buf[0] == 'E')
8203     return TARGET_XFER_E_IO;
8204
8205   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8206      send fewer units than we'd planned.  */
8207   *xfered_len_units = (ULONGEST) units_written;
8208   return TARGET_XFER_OK;
8209 }
8210
8211 /* Write memory data directly to the remote machine.
8212    This does not inform the data cache; the data cache uses this.
8213    MEMADDR is the address in the remote memory space.
8214    MYADDR is the address of the buffer in our space.
8215    LEN is the number of bytes.
8216
8217    Return the transferred status, error or OK (an
8218    'enum target_xfer_status' value).  Save the number of bytes
8219    transferred in *XFERED_LEN.  Only transfer a single packet.  */
8220
8221 static enum target_xfer_status
8222 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8223                     int unit_size, ULONGEST *xfered_len)
8224 {
8225   char *packet_format = 0;
8226
8227   /* Check whether the target supports binary download.  */
8228   check_binary_download (memaddr);
8229
8230   switch (packet_support (PACKET_X))
8231     {
8232     case PACKET_ENABLE:
8233       packet_format = "X";
8234       break;
8235     case PACKET_DISABLE:
8236       packet_format = "M";
8237       break;
8238     case PACKET_SUPPORT_UNKNOWN:
8239       internal_error (__FILE__, __LINE__,
8240                       _("remote_write_bytes: bad internal state"));
8241     default:
8242       internal_error (__FILE__, __LINE__, _("bad switch"));
8243     }
8244
8245   return remote_write_bytes_aux (packet_format,
8246                                  memaddr, myaddr, len, unit_size, xfered_len,
8247                                  packet_format[0], 1);
8248 }
8249
8250 /* Read memory data directly from the remote machine.
8251    This does not use the data cache; the data cache uses this.
8252    MEMADDR is the address in the remote memory space.
8253    MYADDR is the address of the buffer in our space.
8254    LEN_UNITS is the number of addressable memory units to read..
8255    UNIT_SIZE is the length in bytes of an addressable unit.
8256
8257    Return the transferred status, error or OK (an
8258    'enum target_xfer_status' value).  Save the number of bytes
8259    transferred in *XFERED_LEN_UNITS.
8260
8261    See the comment of remote_write_bytes_aux for an example of
8262    memory read/write exchange between gdb and the stub.  */
8263
8264 static enum target_xfer_status
8265 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8266                      int unit_size, ULONGEST *xfered_len_units)
8267 {
8268   struct remote_state *rs = get_remote_state ();
8269   int buf_size_bytes;           /* Max size of packet output buffer.  */
8270   char *p;
8271   int todo_units;
8272   int decoded_bytes;
8273
8274   buf_size_bytes = get_memory_read_packet_size ();
8275   /* The packet buffer will be large enough for the payload;
8276      get_memory_packet_size ensures this.  */
8277
8278   /* Number of units that will fit.  */
8279   todo_units = std::min (len_units,
8280                          (ULONGEST) (buf_size_bytes / unit_size) / 2);
8281
8282   /* Construct "m"<memaddr>","<len>".  */
8283   memaddr = remote_address_masked (memaddr);
8284   p = rs->buf;
8285   *p++ = 'm';
8286   p += hexnumstr (p, (ULONGEST) memaddr);
8287   *p++ = ',';
8288   p += hexnumstr (p, (ULONGEST) todo_units);
8289   *p = '\0';
8290   putpkt (rs->buf);
8291   getpkt (&rs->buf, &rs->buf_size, 0);
8292   if (rs->buf[0] == 'E'
8293       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8294       && rs->buf[3] == '\0')
8295     return TARGET_XFER_E_IO;
8296   /* Reply describes memory byte by byte, each byte encoded as two hex
8297      characters.  */
8298   p = rs->buf;
8299   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8300   /* Return what we have.  Let higher layers handle partial reads.  */
8301   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8302   return TARGET_XFER_OK;
8303 }
8304
8305 /* Using the set of read-only target sections of remote, read live
8306    read-only memory.
8307
8308    For interface/parameters/return description see target.h,
8309    to_xfer_partial.  */
8310
8311 static enum target_xfer_status
8312 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8313                                    ULONGEST memaddr, ULONGEST len,
8314                                    int unit_size, ULONGEST *xfered_len)
8315 {
8316   struct target_section *secp;
8317   struct target_section_table *table;
8318
8319   secp = target_section_by_addr (ops, memaddr);
8320   if (secp != NULL
8321       && (bfd_get_section_flags (secp->the_bfd_section->owner,
8322                                  secp->the_bfd_section)
8323           & SEC_READONLY))
8324     {
8325       struct target_section *p;
8326       ULONGEST memend = memaddr + len;
8327
8328       table = target_get_section_table (ops);
8329
8330       for (p = table->sections; p < table->sections_end; p++)
8331         {
8332           if (memaddr >= p->addr)
8333             {
8334               if (memend <= p->endaddr)
8335                 {
8336                   /* Entire transfer is within this section.  */
8337                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8338                                               xfered_len);
8339                 }
8340               else if (memaddr >= p->endaddr)
8341                 {
8342                   /* This section ends before the transfer starts.  */
8343                   continue;
8344                 }
8345               else
8346                 {
8347                   /* This section overlaps the transfer.  Just do half.  */
8348                   len = p->endaddr - memaddr;
8349                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8350                                               xfered_len);
8351                 }
8352             }
8353         }
8354     }
8355
8356   return TARGET_XFER_EOF;
8357 }
8358
8359 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8360    first if the requested memory is unavailable in traceframe.
8361    Otherwise, fall back to remote_read_bytes_1.  */
8362
8363 static enum target_xfer_status
8364 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8365                    gdb_byte *myaddr, ULONGEST len, int unit_size,
8366                    ULONGEST *xfered_len)
8367 {
8368   if (len == 0)
8369     return TARGET_XFER_EOF;
8370
8371   if (get_traceframe_number () != -1)
8372     {
8373       VEC(mem_range_s) *available;
8374
8375       /* If we fail to get the set of available memory, then the
8376          target does not support querying traceframe info, and so we
8377          attempt reading from the traceframe anyway (assuming the
8378          target implements the old QTro packet then).  */
8379       if (traceframe_available_memory (&available, memaddr, len))
8380         {
8381           struct cleanup *old_chain;
8382
8383           old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
8384
8385           if (VEC_empty (mem_range_s, available)
8386               || VEC_index (mem_range_s, available, 0)->start != memaddr)
8387             {
8388               enum target_xfer_status res;
8389
8390               /* Don't read into the traceframe's available
8391                  memory.  */
8392               if (!VEC_empty (mem_range_s, available))
8393                 {
8394                   LONGEST oldlen = len;
8395
8396                   len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8397                   gdb_assert (len <= oldlen);
8398                 }
8399
8400               do_cleanups (old_chain);
8401
8402               /* This goes through the topmost target again.  */
8403               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8404                                                        len, unit_size, xfered_len);
8405               if (res == TARGET_XFER_OK)
8406                 return TARGET_XFER_OK;
8407               else
8408                 {
8409                   /* No use trying further, we know some memory starting
8410                      at MEMADDR isn't available.  */
8411                   *xfered_len = len;
8412                   return TARGET_XFER_UNAVAILABLE;
8413                 }
8414             }
8415
8416           /* Don't try to read more than how much is available, in
8417              case the target implements the deprecated QTro packet to
8418              cater for older GDBs (the target's knowledge of read-only
8419              sections may be outdated by now).  */
8420           len = VEC_index (mem_range_s, available, 0)->length;
8421
8422           do_cleanups (old_chain);
8423         }
8424     }
8425
8426   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8427 }
8428
8429 \f
8430
8431 /* Sends a packet with content determined by the printf format string
8432    FORMAT and the remaining arguments, then gets the reply.  Returns
8433    whether the packet was a success, a failure, or unknown.  */
8434
8435 static enum packet_result remote_send_printf (const char *format, ...)
8436   ATTRIBUTE_PRINTF (1, 2);
8437
8438 static enum packet_result
8439 remote_send_printf (const char *format, ...)
8440 {
8441   struct remote_state *rs = get_remote_state ();
8442   int max_size = get_remote_packet_size ();
8443   va_list ap;
8444
8445   va_start (ap, format);
8446
8447   rs->buf[0] = '\0';
8448   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8449     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8450
8451   if (putpkt (rs->buf) < 0)
8452     error (_("Communication problem with target."));
8453
8454   rs->buf[0] = '\0';
8455   getpkt (&rs->buf, &rs->buf_size, 0);
8456
8457   return packet_check_result (rs->buf);
8458 }
8459
8460 static void
8461 restore_remote_timeout (void *p)
8462 {
8463   int value = *(int *)p;
8464
8465   remote_timeout = value;
8466 }
8467
8468 /* Flash writing can take quite some time.  We'll set
8469    effectively infinite timeout for flash operations.
8470    In future, we'll need to decide on a better approach.  */
8471 static const int remote_flash_timeout = 1000;
8472
8473 static void
8474 remote_flash_erase (struct target_ops *ops,
8475                     ULONGEST address, LONGEST length)
8476 {
8477   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8478   int saved_remote_timeout = remote_timeout;
8479   enum packet_result ret;
8480   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8481                                           &saved_remote_timeout);
8482
8483   remote_timeout = remote_flash_timeout;
8484
8485   ret = remote_send_printf ("vFlashErase:%s,%s",
8486                             phex (address, addr_size),
8487                             phex (length, 4));
8488   switch (ret)
8489     {
8490     case PACKET_UNKNOWN:
8491       error (_("Remote target does not support flash erase"));
8492     case PACKET_ERROR:
8493       error (_("Error erasing flash with vFlashErase packet"));
8494     default:
8495       break;
8496     }
8497
8498   do_cleanups (back_to);
8499 }
8500
8501 static enum target_xfer_status
8502 remote_flash_write (struct target_ops *ops, ULONGEST address,
8503                     ULONGEST length, ULONGEST *xfered_len,
8504                     const gdb_byte *data)
8505 {
8506   int saved_remote_timeout = remote_timeout;
8507   enum target_xfer_status ret;
8508   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8509                                           &saved_remote_timeout);
8510
8511   remote_timeout = remote_flash_timeout;
8512   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8513                                 xfered_len,'X', 0);
8514   do_cleanups (back_to);
8515
8516   return ret;
8517 }
8518
8519 static void
8520 remote_flash_done (struct target_ops *ops)
8521 {
8522   int saved_remote_timeout = remote_timeout;
8523   int ret;
8524   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8525                                           &saved_remote_timeout);
8526
8527   remote_timeout = remote_flash_timeout;
8528   ret = remote_send_printf ("vFlashDone");
8529   do_cleanups (back_to);
8530
8531   switch (ret)
8532     {
8533     case PACKET_UNKNOWN:
8534       error (_("Remote target does not support vFlashDone"));
8535     case PACKET_ERROR:
8536       error (_("Error finishing flash operation"));
8537     default:
8538       break;
8539     }
8540 }
8541
8542 static void
8543 remote_files_info (struct target_ops *ignore)
8544 {
8545   puts_filtered ("Debugging a target over a serial line.\n");
8546 }
8547 \f
8548 /* Stuff for dealing with the packets which are part of this protocol.
8549    See comment at top of file for details.  */
8550
8551 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8552    error to higher layers.  Called when a serial error is detected.
8553    The exception message is STRING, followed by a colon and a blank,
8554    the system error message for errno at function entry and final dot
8555    for output compatibility with throw_perror_with_name.  */
8556
8557 static void
8558 unpush_and_perror (const char *string)
8559 {
8560   int saved_errno = errno;
8561
8562   remote_unpush_target ();
8563   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8564                safe_strerror (saved_errno));
8565 }
8566
8567 /* Read a single character from the remote end.  The current quit
8568    handler is overridden to avoid quitting in the middle of packet
8569    sequence, as that would break communication with the remote server.
8570    See remote_serial_quit_handler for more detail.  */
8571
8572 static int
8573 readchar (int timeout)
8574 {
8575   int ch;
8576   struct remote_state *rs = get_remote_state ();
8577   struct cleanup *old_chain;
8578
8579   old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8580
8581   rs->got_ctrlc_during_io = 0;
8582
8583   ch = serial_readchar (rs->remote_desc, timeout);
8584
8585   if (rs->got_ctrlc_during_io)
8586     set_quit_flag ();
8587
8588   do_cleanups (old_chain);
8589
8590   if (ch >= 0)
8591     return ch;
8592
8593   switch ((enum serial_rc) ch)
8594     {
8595     case SERIAL_EOF:
8596       remote_unpush_target ();
8597       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8598       /* no return */
8599     case SERIAL_ERROR:
8600       unpush_and_perror (_("Remote communication error.  "
8601                            "Target disconnected."));
8602       /* no return */
8603     case SERIAL_TIMEOUT:
8604       break;
8605     }
8606   return ch;
8607 }
8608
8609 /* Wrapper for serial_write that closes the target and throws if
8610    writing fails.  The current quit handler is overridden to avoid
8611    quitting in the middle of packet sequence, as that would break
8612    communication with the remote server.  See
8613    remote_serial_quit_handler for more detail.  */
8614
8615 static void
8616 remote_serial_write (const char *str, int len)
8617 {
8618   struct remote_state *rs = get_remote_state ();
8619   struct cleanup *old_chain;
8620
8621   old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8622
8623   rs->got_ctrlc_during_io = 0;
8624
8625   if (serial_write (rs->remote_desc, str, len))
8626     {
8627       unpush_and_perror (_("Remote communication error.  "
8628                            "Target disconnected."));
8629     }
8630
8631   if (rs->got_ctrlc_during_io)
8632     set_quit_flag ();
8633
8634   do_cleanups (old_chain);
8635 }
8636
8637 /* Send the command in *BUF to the remote machine, and read the reply
8638    into *BUF.  Report an error if we get an error reply.  Resize
8639    *BUF using xrealloc if necessary to hold the result, and update
8640    *SIZEOF_BUF.  */
8641
8642 static void
8643 remote_send (char **buf,
8644              long *sizeof_buf)
8645 {
8646   putpkt (*buf);
8647   getpkt (buf, sizeof_buf, 0);
8648
8649   if ((*buf)[0] == 'E')
8650     error (_("Remote failure reply: %s"), *buf);
8651 }
8652
8653 /* Return a pointer to an xmalloc'ed string representing an escaped
8654    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
8655    etc.  The caller is responsible for releasing the returned
8656    memory.  */
8657
8658 static char *
8659 escape_buffer (const char *buf, int n)
8660 {
8661   struct cleanup *old_chain;
8662   struct ui_file *stb;
8663   char *str;
8664
8665   stb = mem_fileopen ();
8666   old_chain = make_cleanup_ui_file_delete (stb);
8667
8668   fputstrn_unfiltered (buf, n, '\\', stb);
8669   str = ui_file_xstrdup (stb, NULL);
8670   do_cleanups (old_chain);
8671   return str;
8672 }
8673
8674 /* Display a null-terminated packet on stdout, for debugging, using C
8675    string notation.  */
8676
8677 static void
8678 print_packet (const char *buf)
8679 {
8680   puts_filtered ("\"");
8681   fputstr_filtered (buf, '"', gdb_stdout);
8682   puts_filtered ("\"");
8683 }
8684
8685 int
8686 putpkt (const char *buf)
8687 {
8688   return putpkt_binary (buf, strlen (buf));
8689 }
8690
8691 /* Send a packet to the remote machine, with error checking.  The data
8692    of the packet is in BUF.  The string in BUF can be at most
8693    get_remote_packet_size () - 5 to account for the $, # and checksum,
8694    and for a possible /0 if we are debugging (remote_debug) and want
8695    to print the sent packet as a string.  */
8696
8697 static int
8698 putpkt_binary (const char *buf, int cnt)
8699 {
8700   struct remote_state *rs = get_remote_state ();
8701   int i;
8702   unsigned char csum = 0;
8703   char *buf2 = (char *) xmalloc (cnt + 6);
8704   struct cleanup *old_chain = make_cleanup (xfree, buf2);
8705
8706   int ch;
8707   int tcount = 0;
8708   char *p;
8709
8710   /* Catch cases like trying to read memory or listing threads while
8711      we're waiting for a stop reply.  The remote server wouldn't be
8712      ready to handle this request, so we'd hang and timeout.  We don't
8713      have to worry about this in synchronous mode, because in that
8714      case it's not possible to issue a command while the target is
8715      running.  This is not a problem in non-stop mode, because in that
8716      case, the stub is always ready to process serial input.  */
8717   if (!target_is_non_stop_p ()
8718       && target_is_async_p ()
8719       && rs->waiting_for_stop_reply)
8720     {
8721       error (_("Cannot execute this command while the target is running.\n"
8722                "Use the \"interrupt\" command to stop the target\n"
8723                "and then try again."));
8724     }
8725
8726   /* We're sending out a new packet.  Make sure we don't look at a
8727      stale cached response.  */
8728   rs->cached_wait_status = 0;
8729
8730   /* Copy the packet into buffer BUF2, encapsulating it
8731      and giving it a checksum.  */
8732
8733   p = buf2;
8734   *p++ = '$';
8735
8736   for (i = 0; i < cnt; i++)
8737     {
8738       csum += buf[i];
8739       *p++ = buf[i];
8740     }
8741   *p++ = '#';
8742   *p++ = tohex ((csum >> 4) & 0xf);
8743   *p++ = tohex (csum & 0xf);
8744
8745   /* Send it over and over until we get a positive ack.  */
8746
8747   while (1)
8748     {
8749       int started_error_output = 0;
8750
8751       if (remote_debug)
8752         {
8753           struct cleanup *old_chain;
8754           char *str;
8755
8756           *p = '\0';
8757           str = escape_buffer (buf2, p - buf2);
8758           old_chain = make_cleanup (xfree, str);
8759           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8760           gdb_flush (gdb_stdlog);
8761           do_cleanups (old_chain);
8762         }
8763       remote_serial_write (buf2, p - buf2);
8764
8765       /* If this is a no acks version of the remote protocol, send the
8766          packet and move on.  */
8767       if (rs->noack_mode)
8768         break;
8769
8770       /* Read until either a timeout occurs (-2) or '+' is read.
8771          Handle any notification that arrives in the mean time.  */
8772       while (1)
8773         {
8774           ch = readchar (remote_timeout);
8775
8776           if (remote_debug)
8777             {
8778               switch (ch)
8779                 {
8780                 case '+':
8781                 case '-':
8782                 case SERIAL_TIMEOUT:
8783                 case '$':
8784                 case '%':
8785                   if (started_error_output)
8786                     {
8787                       putchar_unfiltered ('\n');
8788                       started_error_output = 0;
8789                     }
8790                 }
8791             }
8792
8793           switch (ch)
8794             {
8795             case '+':
8796               if (remote_debug)
8797                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8798               do_cleanups (old_chain);
8799               return 1;
8800             case '-':
8801               if (remote_debug)
8802                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8803               /* FALLTHROUGH */
8804             case SERIAL_TIMEOUT:
8805               tcount++;
8806               if (tcount > 3)
8807                 {
8808                   do_cleanups (old_chain);
8809                   return 0;
8810                 }
8811               break;            /* Retransmit buffer.  */
8812             case '$':
8813               {
8814                 if (remote_debug)
8815                   fprintf_unfiltered (gdb_stdlog,
8816                                       "Packet instead of Ack, ignoring it\n");
8817                 /* It's probably an old response sent because an ACK
8818                    was lost.  Gobble up the packet and ack it so it
8819                    doesn't get retransmitted when we resend this
8820                    packet.  */
8821                 skip_frame ();
8822                 remote_serial_write ("+", 1);
8823                 continue;       /* Now, go look for +.  */
8824               }
8825
8826             case '%':
8827               {
8828                 int val;
8829
8830                 /* If we got a notification, handle it, and go back to looking
8831                    for an ack.  */
8832                 /* We've found the start of a notification.  Now
8833                    collect the data.  */
8834                 val = read_frame (&rs->buf, &rs->buf_size);
8835                 if (val >= 0)
8836                   {
8837                     if (remote_debug)
8838                       {
8839                         struct cleanup *old_chain;
8840                         char *str;
8841
8842                         str = escape_buffer (rs->buf, val);
8843                         old_chain = make_cleanup (xfree, str);
8844                         fprintf_unfiltered (gdb_stdlog,
8845                                             "  Notification received: %s\n",
8846                                             str);
8847                         do_cleanups (old_chain);
8848                       }
8849                     handle_notification (rs->notif_state, rs->buf);
8850                     /* We're in sync now, rewait for the ack.  */
8851                     tcount = 0;
8852                   }
8853                 else
8854                   {
8855                     if (remote_debug)
8856                       {
8857                         if (!started_error_output)
8858                           {
8859                             started_error_output = 1;
8860                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8861                           }
8862                         fputc_unfiltered (ch & 0177, gdb_stdlog);
8863                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8864                       }
8865                   }
8866                 continue;
8867               }
8868               /* fall-through */
8869             default:
8870               if (remote_debug)
8871                 {
8872                   if (!started_error_output)
8873                     {
8874                       started_error_output = 1;
8875                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8876                     }
8877                   fputc_unfiltered (ch & 0177, gdb_stdlog);
8878                 }
8879               continue;
8880             }
8881           break;                /* Here to retransmit.  */
8882         }
8883
8884 #if 0
8885       /* This is wrong.  If doing a long backtrace, the user should be
8886          able to get out next time we call QUIT, without anything as
8887          violent as interrupt_query.  If we want to provide a way out of
8888          here without getting to the next QUIT, it should be based on
8889          hitting ^C twice as in remote_wait.  */
8890       if (quit_flag)
8891         {
8892           quit_flag = 0;
8893           interrupt_query ();
8894         }
8895 #endif
8896     }
8897
8898   do_cleanups (old_chain);
8899   return 0;
8900 }
8901
8902 /* Come here after finding the start of a frame when we expected an
8903    ack.  Do our best to discard the rest of this packet.  */
8904
8905 static void
8906 skip_frame (void)
8907 {
8908   int c;
8909
8910   while (1)
8911     {
8912       c = readchar (remote_timeout);
8913       switch (c)
8914         {
8915         case SERIAL_TIMEOUT:
8916           /* Nothing we can do.  */
8917           return;
8918         case '#':
8919           /* Discard the two bytes of checksum and stop.  */
8920           c = readchar (remote_timeout);
8921           if (c >= 0)
8922             c = readchar (remote_timeout);
8923
8924           return;
8925         case '*':               /* Run length encoding.  */
8926           /* Discard the repeat count.  */
8927           c = readchar (remote_timeout);
8928           if (c < 0)
8929             return;
8930           break;
8931         default:
8932           /* A regular character.  */
8933           break;
8934         }
8935     }
8936 }
8937
8938 /* Come here after finding the start of the frame.  Collect the rest
8939    into *BUF, verifying the checksum, length, and handling run-length
8940    compression.  NUL terminate the buffer.  If there is not enough room,
8941    expand *BUF using xrealloc.
8942
8943    Returns -1 on error, number of characters in buffer (ignoring the
8944    trailing NULL) on success. (could be extended to return one of the
8945    SERIAL status indications).  */
8946
8947 static long
8948 read_frame (char **buf_p,
8949             long *sizeof_buf)
8950 {
8951   unsigned char csum;
8952   long bc;
8953   int c;
8954   char *buf = *buf_p;
8955   struct remote_state *rs = get_remote_state ();
8956
8957   csum = 0;
8958   bc = 0;
8959
8960   while (1)
8961     {
8962       c = readchar (remote_timeout);
8963       switch (c)
8964         {
8965         case SERIAL_TIMEOUT:
8966           if (remote_debug)
8967             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8968           return -1;
8969         case '$':
8970           if (remote_debug)
8971             fputs_filtered ("Saw new packet start in middle of old one\n",
8972                             gdb_stdlog);
8973           return -1;            /* Start a new packet, count retries.  */
8974         case '#':
8975           {
8976             unsigned char pktcsum;
8977             int check_0 = 0;
8978             int check_1 = 0;
8979
8980             buf[bc] = '\0';
8981
8982             check_0 = readchar (remote_timeout);
8983             if (check_0 >= 0)
8984               check_1 = readchar (remote_timeout);
8985
8986             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8987               {
8988                 if (remote_debug)
8989                   fputs_filtered ("Timeout in checksum, retrying\n",
8990                                   gdb_stdlog);
8991                 return -1;
8992               }
8993             else if (check_0 < 0 || check_1 < 0)
8994               {
8995                 if (remote_debug)
8996                   fputs_filtered ("Communication error in checksum\n",
8997                                   gdb_stdlog);
8998                 return -1;
8999               }
9000
9001             /* Don't recompute the checksum; with no ack packets we
9002                don't have any way to indicate a packet retransmission
9003                is necessary.  */
9004             if (rs->noack_mode)
9005               return bc;
9006
9007             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9008             if (csum == pktcsum)
9009               return bc;
9010
9011             if (remote_debug)
9012               {
9013                 struct cleanup *old_chain;
9014                 char *str;
9015
9016                 str = escape_buffer (buf, bc);
9017                 old_chain = make_cleanup (xfree, str);
9018                 fprintf_unfiltered (gdb_stdlog,
9019                                     "Bad checksum, sentsum=0x%x, "
9020                                     "csum=0x%x, buf=%s\n",
9021                                     pktcsum, csum, str);
9022                 do_cleanups (old_chain);
9023               }
9024             /* Number of characters in buffer ignoring trailing
9025                NULL.  */
9026             return -1;
9027           }
9028         case '*':               /* Run length encoding.  */
9029           {
9030             int repeat;
9031
9032             csum += c;
9033             c = readchar (remote_timeout);
9034             csum += c;
9035             repeat = c - ' ' + 3;       /* Compute repeat count.  */
9036
9037             /* The character before ``*'' is repeated.  */
9038
9039             if (repeat > 0 && repeat <= 255 && bc > 0)
9040               {
9041                 if (bc + repeat - 1 >= *sizeof_buf - 1)
9042                   {
9043                     /* Make some more room in the buffer.  */
9044                     *sizeof_buf += repeat;
9045                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9046                     buf = *buf_p;
9047                   }
9048
9049                 memset (&buf[bc], buf[bc - 1], repeat);
9050                 bc += repeat;
9051                 continue;
9052               }
9053
9054             buf[bc] = '\0';
9055             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9056             return -1;
9057           }
9058         default:
9059           if (bc >= *sizeof_buf - 1)
9060             {
9061               /* Make some more room in the buffer.  */
9062               *sizeof_buf *= 2;
9063               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9064               buf = *buf_p;
9065             }
9066
9067           buf[bc++] = c;
9068           csum += c;
9069           continue;
9070         }
9071     }
9072 }
9073
9074 /* Read a packet from the remote machine, with error checking, and
9075    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9076    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9077    rather than timing out; this is used (in synchronous mode) to wait
9078    for a target that is is executing user code to stop.  */
9079 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9080    don't have to change all the calls to getpkt to deal with the
9081    return value, because at the moment I don't know what the right
9082    thing to do it for those.  */
9083 void
9084 getpkt (char **buf,
9085         long *sizeof_buf,
9086         int forever)
9087 {
9088   getpkt_sane (buf, sizeof_buf, forever);
9089 }
9090
9091
9092 /* Read a packet from the remote machine, with error checking, and
9093    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9094    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9095    rather than timing out; this is used (in synchronous mode) to wait
9096    for a target that is is executing user code to stop.  If FOREVER ==
9097    0, this function is allowed to time out gracefully and return an
9098    indication of this to the caller.  Otherwise return the number of
9099    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
9100    enough reason to return to the caller.  *IS_NOTIF is an output
9101    boolean that indicates whether *BUF holds a notification or not
9102    (a regular packet).  */
9103
9104 static int
9105 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9106                         int expecting_notif, int *is_notif)
9107 {
9108   struct remote_state *rs = get_remote_state ();
9109   int c;
9110   int tries;
9111   int timeout;
9112   int val = -1;
9113
9114   /* We're reading a new response.  Make sure we don't look at a
9115      previously cached response.  */
9116   rs->cached_wait_status = 0;
9117
9118   strcpy (*buf, "timeout");
9119
9120   if (forever)
9121     timeout = watchdog > 0 ? watchdog : -1;
9122   else if (expecting_notif)
9123     timeout = 0; /* There should already be a char in the buffer.  If
9124                     not, bail out.  */
9125   else
9126     timeout = remote_timeout;
9127
9128 #define MAX_TRIES 3
9129
9130   /* Process any number of notifications, and then return when
9131      we get a packet.  */
9132   for (;;)
9133     {
9134       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9135          times.  */
9136       for (tries = 1; tries <= MAX_TRIES; tries++)
9137         {
9138           /* This can loop forever if the remote side sends us
9139              characters continuously, but if it pauses, we'll get
9140              SERIAL_TIMEOUT from readchar because of timeout.  Then
9141              we'll count that as a retry.
9142
9143              Note that even when forever is set, we will only wait
9144              forever prior to the start of a packet.  After that, we
9145              expect characters to arrive at a brisk pace.  They should
9146              show up within remote_timeout intervals.  */
9147           do
9148             c = readchar (timeout);
9149           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9150
9151           if (c == SERIAL_TIMEOUT)
9152             {
9153               if (expecting_notif)
9154                 return -1; /* Don't complain, it's normal to not get
9155                               anything in this case.  */
9156
9157               if (forever)      /* Watchdog went off?  Kill the target.  */
9158                 {
9159                   remote_unpush_target ();
9160                   throw_error (TARGET_CLOSE_ERROR,
9161                                _("Watchdog timeout has expired.  "
9162                                  "Target detached."));
9163                 }
9164               if (remote_debug)
9165                 fputs_filtered ("Timed out.\n", gdb_stdlog);
9166             }
9167           else
9168             {
9169               /* We've found the start of a packet or notification.
9170                  Now collect the data.  */
9171               val = read_frame (buf, sizeof_buf);
9172               if (val >= 0)
9173                 break;
9174             }
9175
9176           remote_serial_write ("-", 1);
9177         }
9178
9179       if (tries > MAX_TRIES)
9180         {
9181           /* We have tried hard enough, and just can't receive the
9182              packet/notification.  Give up.  */
9183           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9184
9185           /* Skip the ack char if we're in no-ack mode.  */
9186           if (!rs->noack_mode)
9187             remote_serial_write ("+", 1);
9188           return -1;
9189         }
9190
9191       /* If we got an ordinary packet, return that to our caller.  */
9192       if (c == '$')
9193         {
9194           if (remote_debug)
9195             {
9196              struct cleanup *old_chain;
9197              char *str;
9198
9199              str = escape_buffer (*buf, val);
9200              old_chain = make_cleanup (xfree, str);
9201              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
9202              do_cleanups (old_chain);
9203             }
9204
9205           /* Skip the ack char if we're in no-ack mode.  */
9206           if (!rs->noack_mode)
9207             remote_serial_write ("+", 1);
9208           if (is_notif != NULL)
9209             *is_notif = 0;
9210           return val;
9211         }
9212
9213        /* If we got a notification, handle it, and go back to looking
9214          for a packet.  */
9215       else
9216         {
9217           gdb_assert (c == '%');
9218
9219           if (remote_debug)
9220             {
9221               struct cleanup *old_chain;
9222               char *str;
9223
9224               str = escape_buffer (*buf, val);
9225               old_chain = make_cleanup (xfree, str);
9226               fprintf_unfiltered (gdb_stdlog,
9227                                   "  Notification received: %s\n",
9228                                   str);
9229               do_cleanups (old_chain);
9230             }
9231           if (is_notif != NULL)
9232             *is_notif = 1;
9233
9234           handle_notification (rs->notif_state, *buf);
9235
9236           /* Notifications require no acknowledgement.  */
9237
9238           if (expecting_notif)
9239             return val;
9240         }
9241     }
9242 }
9243
9244 static int
9245 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9246 {
9247   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9248 }
9249
9250 static int
9251 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9252                       int *is_notif)
9253 {
9254   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9255                                  is_notif);
9256 }
9257
9258 /* Check whether EVENT is a fork event for the process specified
9259    by the pid passed in DATA, and if it is, kill the fork child.  */
9260
9261 static int
9262 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9263                             QUEUE_ITER (stop_reply_p) *iter,
9264                             stop_reply_p event,
9265                             void *data)
9266 {
9267   struct queue_iter_param *param = (struct queue_iter_param *) data;
9268   int parent_pid = *(int *) param->input;
9269
9270   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9271     {
9272       struct remote_state *rs = get_remote_state ();
9273       int child_pid = ptid_get_pid (event->ws.value.related_pid);
9274       int res;
9275
9276       res = remote_vkill (child_pid, rs);
9277       if (res != 0)
9278         error (_("Can't kill fork child process %d"), child_pid);
9279     }
9280
9281   return 1;
9282 }
9283
9284 /* Kill any new fork children of process PID that haven't been
9285    processed by follow_fork.  */
9286
9287 static void
9288 kill_new_fork_children (int pid, struct remote_state *rs)
9289 {
9290   struct thread_info *thread;
9291   struct notif_client *notif = &notif_client_stop;
9292   struct queue_iter_param param;
9293
9294   /* Kill the fork child threads of any threads in process PID
9295      that are stopped at a fork event.  */
9296   ALL_NON_EXITED_THREADS (thread)
9297     {
9298       struct target_waitstatus *ws = &thread->pending_follow;
9299
9300       if (is_pending_fork_parent (ws, pid, thread->ptid))
9301         {
9302           struct remote_state *rs = get_remote_state ();
9303           int child_pid = ptid_get_pid (ws->value.related_pid);
9304           int res;
9305
9306           res = remote_vkill (child_pid, rs);
9307           if (res != 0)
9308             error (_("Can't kill fork child process %d"), child_pid);
9309         }
9310     }
9311
9312   /* Check for any pending fork events (not reported or processed yet)
9313      in process PID and kill those fork child threads as well.  */
9314   remote_notif_get_pending_events (notif);
9315   param.input = &pid;
9316   param.output = NULL;
9317   QUEUE_iterate (stop_reply_p, stop_reply_queue,
9318                  kill_child_of_pending_fork, &param);
9319 }
9320
9321 \f
9322 /* Target hook to kill the current inferior.  */
9323
9324 static void
9325 remote_kill (struct target_ops *ops)
9326 {
9327   int res = -1;
9328   int pid = ptid_get_pid (inferior_ptid);
9329   struct remote_state *rs = get_remote_state ();
9330
9331   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9332     {
9333       /* If we're stopped while forking and we haven't followed yet,
9334          kill the child task.  We need to do this before killing the
9335          parent task because if this is a vfork then the parent will
9336          be sleeping.  */
9337       kill_new_fork_children (pid, rs);
9338
9339       res = remote_vkill (pid, rs);
9340       if (res == 0)
9341         {
9342           target_mourn_inferior (inferior_ptid);
9343           return;
9344         }
9345     }
9346
9347   /* If we are in 'target remote' mode and we are killing the only
9348      inferior, then we will tell gdbserver to exit and unpush the
9349      target.  */
9350   if (res == -1 && !remote_multi_process_p (rs)
9351       && number_of_live_inferiors () == 1)
9352     {
9353       remote_kill_k ();
9354
9355       /* We've killed the remote end, we get to mourn it.  If we are
9356          not in extended mode, mourning the inferior also unpushes
9357          remote_ops from the target stack, which closes the remote
9358          connection.  */
9359       target_mourn_inferior (inferior_ptid);
9360
9361       return;
9362     }
9363
9364   error (_("Can't kill process"));
9365 }
9366
9367 /* Send a kill request to the target using the 'vKill' packet.  */
9368
9369 static int
9370 remote_vkill (int pid, struct remote_state *rs)
9371 {
9372   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9373     return -1;
9374
9375   /* Tell the remote target to detach.  */
9376   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9377   putpkt (rs->buf);
9378   getpkt (&rs->buf, &rs->buf_size, 0);
9379
9380   switch (packet_ok (rs->buf,
9381                      &remote_protocol_packets[PACKET_vKill]))
9382     {
9383     case PACKET_OK:
9384       return 0;
9385     case PACKET_ERROR:
9386       return 1;
9387     case PACKET_UNKNOWN:
9388       return -1;
9389     default:
9390       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9391     }
9392 }
9393
9394 /* Send a kill request to the target using the 'k' packet.  */
9395
9396 static void
9397 remote_kill_k (void)
9398 {
9399   /* Catch errors so the user can quit from gdb even when we
9400      aren't on speaking terms with the remote system.  */
9401   TRY
9402     {
9403       putpkt ("k");
9404     }
9405   CATCH (ex, RETURN_MASK_ERROR)
9406     {
9407       if (ex.error == TARGET_CLOSE_ERROR)
9408         {
9409           /* If we got an (EOF) error that caused the target
9410              to go away, then we're done, that's what we wanted.
9411              "k" is susceptible to cause a premature EOF, given
9412              that the remote server isn't actually required to
9413              reply to "k", and it can happen that it doesn't
9414              even get to reply ACK to the "k".  */
9415           return;
9416         }
9417
9418       /* Otherwise, something went wrong.  We didn't actually kill
9419          the target.  Just propagate the exception, and let the
9420          user or higher layers decide what to do.  */
9421       throw_exception (ex);
9422     }
9423   END_CATCH
9424 }
9425
9426 static void
9427 remote_mourn (struct target_ops *target)
9428 {
9429   struct remote_state *rs = get_remote_state ();
9430
9431   /* In 'target remote' mode with one inferior, we close the connection.  */
9432   if (!rs->extended && number_of_live_inferiors () <= 1)
9433     {
9434       unpush_target (target);
9435
9436       /* remote_close takes care of doing most of the clean up.  */
9437       generic_mourn_inferior ();
9438       return;
9439     }
9440
9441   /* In case we got here due to an error, but we're going to stay
9442      connected.  */
9443   rs->waiting_for_stop_reply = 0;
9444
9445   /* If the current general thread belonged to the process we just
9446      detached from or has exited, the remote side current general
9447      thread becomes undefined.  Considering a case like this:
9448
9449      - We just got here due to a detach.
9450      - The process that we're detaching from happens to immediately
9451        report a global breakpoint being hit in non-stop mode, in the
9452        same thread we had selected before.
9453      - GDB attaches to this process again.
9454      - This event happens to be the next event we handle.
9455
9456      GDB would consider that the current general thread didn't need to
9457      be set on the stub side (with Hg), since for all it knew,
9458      GENERAL_THREAD hadn't changed.
9459
9460      Notice that although in all-stop mode, the remote server always
9461      sets the current thread to the thread reporting the stop event,
9462      that doesn't happen in non-stop mode; in non-stop, the stub *must
9463      not* change the current thread when reporting a breakpoint hit,
9464      due to the decoupling of event reporting and event handling.
9465
9466      To keep things simple, we always invalidate our notion of the
9467      current thread.  */
9468   record_currthread (rs, minus_one_ptid);
9469
9470   /* Call common code to mark the inferior as not running.  */
9471   generic_mourn_inferior ();
9472
9473   if (!have_inferiors ())
9474     {
9475       if (!remote_multi_process_p (rs))
9476         {
9477           /* Check whether the target is running now - some remote stubs
9478              automatically restart after kill.  */
9479           putpkt ("?");
9480           getpkt (&rs->buf, &rs->buf_size, 0);
9481
9482           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9483             {
9484               /* Assume that the target has been restarted.  Set
9485                  inferior_ptid so that bits of core GDB realizes
9486                  there's something here, e.g., so that the user can
9487                  say "kill" again.  */
9488               inferior_ptid = magic_null_ptid;
9489             }
9490         }
9491     }
9492 }
9493
9494 static int
9495 extended_remote_supports_disable_randomization (struct target_ops *self)
9496 {
9497   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9498 }
9499
9500 static void
9501 extended_remote_disable_randomization (int val)
9502 {
9503   struct remote_state *rs = get_remote_state ();
9504   char *reply;
9505
9506   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9507              val);
9508   putpkt (rs->buf);
9509   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9510   if (*reply == '\0')
9511     error (_("Target does not support QDisableRandomization."));
9512   if (strcmp (reply, "OK") != 0)
9513     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9514 }
9515
9516 static int
9517 extended_remote_run (char *args)
9518 {
9519   struct remote_state *rs = get_remote_state ();
9520   int len;
9521   const char *remote_exec_file = get_remote_exec_file ();
9522
9523   /* If the user has disabled vRun support, or we have detected that
9524      support is not available, do not try it.  */
9525   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9526     return -1;
9527
9528   strcpy (rs->buf, "vRun;");
9529   len = strlen (rs->buf);
9530
9531   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9532     error (_("Remote file name too long for run packet"));
9533   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9534                       strlen (remote_exec_file));
9535
9536   gdb_assert (args != NULL);
9537   if (*args)
9538     {
9539       struct cleanup *back_to;
9540       int i;
9541       char **argv;
9542
9543       argv = gdb_buildargv (args);
9544       back_to = make_cleanup_freeargv (argv);
9545       for (i = 0; argv[i] != NULL; i++)
9546         {
9547           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9548             error (_("Argument list too long for run packet"));
9549           rs->buf[len++] = ';';
9550           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9551                               strlen (argv[i]));
9552         }
9553       do_cleanups (back_to);
9554     }
9555
9556   rs->buf[len++] = '\0';
9557
9558   putpkt (rs->buf);
9559   getpkt (&rs->buf, &rs->buf_size, 0);
9560
9561   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9562     {
9563     case PACKET_OK:
9564       /* We have a wait response.  All is well.  */
9565       return 0;
9566     case PACKET_UNKNOWN:
9567       return -1;
9568     case PACKET_ERROR:
9569       if (remote_exec_file[0] == '\0')
9570         error (_("Running the default executable on the remote target failed; "
9571                  "try \"set remote exec-file\"?"));
9572       else
9573         error (_("Running \"%s\" on the remote target failed"),
9574                remote_exec_file);
9575     default:
9576       gdb_assert_not_reached (_("bad switch"));
9577     }
9578 }
9579
9580 /* In the extended protocol we want to be able to do things like
9581    "run" and have them basically work as expected.  So we need
9582    a special create_inferior function.  We support changing the
9583    executable file and the command line arguments, but not the
9584    environment.  */
9585
9586 static void
9587 extended_remote_create_inferior (struct target_ops *ops,
9588                                  char *exec_file, char *args,
9589                                  char **env, int from_tty)
9590 {
9591   int run_worked;
9592   char *stop_reply;
9593   struct remote_state *rs = get_remote_state ();
9594   const char *remote_exec_file = get_remote_exec_file ();
9595
9596   /* If running asynchronously, register the target file descriptor
9597      with the event loop.  */
9598   if (target_can_async_p ())
9599     target_async (1);
9600
9601   /* Disable address space randomization if requested (and supported).  */
9602   if (extended_remote_supports_disable_randomization (ops))
9603     extended_remote_disable_randomization (disable_randomization);
9604
9605   /* Now restart the remote server.  */
9606   run_worked = extended_remote_run (args) != -1;
9607   if (!run_worked)
9608     {
9609       /* vRun was not supported.  Fail if we need it to do what the
9610          user requested.  */
9611       if (remote_exec_file[0])
9612         error (_("Remote target does not support \"set remote exec-file\""));
9613       if (args[0])
9614         error (_("Remote target does not support \"set args\" or run <ARGS>"));
9615
9616       /* Fall back to "R".  */
9617       extended_remote_restart ();
9618     }
9619
9620   if (!have_inferiors ())
9621     {
9622       /* Clean up from the last time we ran, before we mark the target
9623          running again.  This will mark breakpoints uninserted, and
9624          get_offsets may insert breakpoints.  */
9625       init_thread_list ();
9626       init_wait_for_inferior ();
9627     }
9628
9629   /* vRun's success return is a stop reply.  */
9630   stop_reply = run_worked ? rs->buf : NULL;
9631   add_current_inferior_and_thread (stop_reply);
9632
9633   /* Get updated offsets, if the stub uses qOffsets.  */
9634   get_offsets ();
9635 }
9636 \f
9637
9638 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
9639    the list of conditions (in agent expression bytecode format), if any, the
9640    target needs to evaluate.  The output is placed into the packet buffer
9641    started from BUF and ended at BUF_END.  */
9642
9643 static int
9644 remote_add_target_side_condition (struct gdbarch *gdbarch,
9645                                   struct bp_target_info *bp_tgt, char *buf,
9646                                   char *buf_end)
9647 {
9648   struct agent_expr *aexpr = NULL;
9649   int i, ix;
9650
9651   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9652     return 0;
9653
9654   buf += strlen (buf);
9655   xsnprintf (buf, buf_end - buf, "%s", ";");
9656   buf++;
9657
9658   /* Send conditions to the target and free the vector.  */
9659   for (ix = 0;
9660        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9661        ix++)
9662     {
9663       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9664       buf += strlen (buf);
9665       for (i = 0; i < aexpr->len; ++i)
9666         buf = pack_hex_byte (buf, aexpr->buf[i]);
9667       *buf = '\0';
9668     }
9669   return 0;
9670 }
9671
9672 static void
9673 remote_add_target_side_commands (struct gdbarch *gdbarch,
9674                                  struct bp_target_info *bp_tgt, char *buf)
9675 {
9676   struct agent_expr *aexpr = NULL;
9677   int i, ix;
9678
9679   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9680     return;
9681
9682   buf += strlen (buf);
9683
9684   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9685   buf += strlen (buf);
9686
9687   /* Concatenate all the agent expressions that are commands into the
9688      cmds parameter.  */
9689   for (ix = 0;
9690        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9691        ix++)
9692     {
9693       sprintf (buf, "X%x,", aexpr->len);
9694       buf += strlen (buf);
9695       for (i = 0; i < aexpr->len; ++i)
9696         buf = pack_hex_byte (buf, aexpr->buf[i]);
9697       *buf = '\0';
9698     }
9699 }
9700
9701 /* Insert a breakpoint.  On targets that have software breakpoint
9702    support, we ask the remote target to do the work; on targets
9703    which don't, we insert a traditional memory breakpoint.  */
9704
9705 static int
9706 remote_insert_breakpoint (struct target_ops *ops,
9707                           struct gdbarch *gdbarch,
9708                           struct bp_target_info *bp_tgt)
9709 {
9710   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9711      If it succeeds, then set the support to PACKET_ENABLE.  If it
9712      fails, and the user has explicitly requested the Z support then
9713      report an error, otherwise, mark it disabled and go on.  */
9714
9715   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9716     {
9717       CORE_ADDR addr = bp_tgt->reqstd_address;
9718       struct remote_state *rs;
9719       char *p, *endbuf;
9720       int bpsize;
9721
9722       /* Make sure the remote is pointing at the right process, if
9723          necessary.  */
9724       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9725         set_general_process ();
9726
9727       rs = get_remote_state ();
9728       p = rs->buf;
9729       endbuf = rs->buf + get_remote_packet_size ();
9730
9731       *(p++) = 'Z';
9732       *(p++) = '0';
9733       *(p++) = ',';
9734       addr = (ULONGEST) remote_address_masked (addr);
9735       p += hexnumstr (p, addr);
9736       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9737
9738       if (remote_supports_cond_breakpoints (ops))
9739         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9740
9741       if (remote_can_run_breakpoint_commands (ops))
9742         remote_add_target_side_commands (gdbarch, bp_tgt, p);
9743
9744       putpkt (rs->buf);
9745       getpkt (&rs->buf, &rs->buf_size, 0);
9746
9747       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9748         {
9749         case PACKET_ERROR:
9750           return -1;
9751         case PACKET_OK:
9752           return 0;
9753         case PACKET_UNKNOWN:
9754           break;
9755         }
9756     }
9757
9758   /* If this breakpoint has target-side commands but this stub doesn't
9759      support Z0 packets, throw error.  */
9760   if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9761     throw_error (NOT_SUPPORTED_ERROR, _("\
9762 Target doesn't support breakpoints that have target side commands."));
9763
9764   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9765 }
9766
9767 static int
9768 remote_remove_breakpoint (struct target_ops *ops,
9769                           struct gdbarch *gdbarch,
9770                           struct bp_target_info *bp_tgt,
9771                           enum remove_bp_reason reason)
9772 {
9773   CORE_ADDR addr = bp_tgt->placed_address;
9774   struct remote_state *rs = get_remote_state ();
9775
9776   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9777     {
9778       char *p = rs->buf;
9779       char *endbuf = rs->buf + get_remote_packet_size ();
9780
9781       /* Make sure the remote is pointing at the right process, if
9782          necessary.  */
9783       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9784         set_general_process ();
9785
9786       *(p++) = 'z';
9787       *(p++) = '0';
9788       *(p++) = ',';
9789
9790       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9791       p += hexnumstr (p, addr);
9792       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9793
9794       putpkt (rs->buf);
9795       getpkt (&rs->buf, &rs->buf_size, 0);
9796
9797       return (rs->buf[0] == 'E');
9798     }
9799
9800   return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
9801 }
9802
9803 static enum Z_packet_type
9804 watchpoint_to_Z_packet (int type)
9805 {
9806   switch (type)
9807     {
9808     case hw_write:
9809       return Z_PACKET_WRITE_WP;
9810       break;
9811     case hw_read:
9812       return Z_PACKET_READ_WP;
9813       break;
9814     case hw_access:
9815       return Z_PACKET_ACCESS_WP;
9816       break;
9817     default:
9818       internal_error (__FILE__, __LINE__,
9819                       _("hw_bp_to_z: bad watchpoint type %d"), type);
9820     }
9821 }
9822
9823 static int
9824 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9825                           enum target_hw_bp_type type, struct expression *cond)
9826 {
9827   struct remote_state *rs = get_remote_state ();
9828   char *endbuf = rs->buf + get_remote_packet_size ();
9829   char *p;
9830   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9831
9832   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9833     return 1;
9834
9835   /* Make sure the remote is pointing at the right process, if
9836      necessary.  */
9837   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9838     set_general_process ();
9839
9840   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9841   p = strchr (rs->buf, '\0');
9842   addr = remote_address_masked (addr);
9843   p += hexnumstr (p, (ULONGEST) addr);
9844   xsnprintf (p, endbuf - p, ",%x", len);
9845
9846   putpkt (rs->buf);
9847   getpkt (&rs->buf, &rs->buf_size, 0);
9848
9849   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9850     {
9851     case PACKET_ERROR:
9852       return -1;
9853     case PACKET_UNKNOWN:
9854       return 1;
9855     case PACKET_OK:
9856       return 0;
9857     }
9858   internal_error (__FILE__, __LINE__,
9859                   _("remote_insert_watchpoint: reached end of function"));
9860 }
9861
9862 static int
9863 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9864                                      CORE_ADDR start, int length)
9865 {
9866   CORE_ADDR diff = remote_address_masked (addr - start);
9867
9868   return diff < length;
9869 }
9870
9871
9872 static int
9873 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9874                           enum target_hw_bp_type type, struct expression *cond)
9875 {
9876   struct remote_state *rs = get_remote_state ();
9877   char *endbuf = rs->buf + get_remote_packet_size ();
9878   char *p;
9879   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9880
9881   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9882     return -1;
9883
9884   /* Make sure the remote is pointing at the right process, if
9885      necessary.  */
9886   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9887     set_general_process ();
9888
9889   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9890   p = strchr (rs->buf, '\0');
9891   addr = remote_address_masked (addr);
9892   p += hexnumstr (p, (ULONGEST) addr);
9893   xsnprintf (p, endbuf - p, ",%x", len);
9894   putpkt (rs->buf);
9895   getpkt (&rs->buf, &rs->buf_size, 0);
9896
9897   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9898     {
9899     case PACKET_ERROR:
9900     case PACKET_UNKNOWN:
9901       return -1;
9902     case PACKET_OK:
9903       return 0;
9904     }
9905   internal_error (__FILE__, __LINE__,
9906                   _("remote_remove_watchpoint: reached end of function"));
9907 }
9908
9909
9910 int remote_hw_watchpoint_limit = -1;
9911 int remote_hw_watchpoint_length_limit = -1;
9912 int remote_hw_breakpoint_limit = -1;
9913
9914 static int
9915 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9916                                     CORE_ADDR addr, int len)
9917 {
9918   if (remote_hw_watchpoint_length_limit == 0)
9919     return 0;
9920   else if (remote_hw_watchpoint_length_limit < 0)
9921     return 1;
9922   else if (len <= remote_hw_watchpoint_length_limit)
9923     return 1;
9924   else
9925     return 0;
9926 }
9927
9928 static int
9929 remote_check_watch_resources (struct target_ops *self,
9930                               enum bptype type, int cnt, int ot)
9931 {
9932   if (type == bp_hardware_breakpoint)
9933     {
9934       if (remote_hw_breakpoint_limit == 0)
9935         return 0;
9936       else if (remote_hw_breakpoint_limit < 0)
9937         return 1;
9938       else if (cnt <= remote_hw_breakpoint_limit)
9939         return 1;
9940     }
9941   else
9942     {
9943       if (remote_hw_watchpoint_limit == 0)
9944         return 0;
9945       else if (remote_hw_watchpoint_limit < 0)
9946         return 1;
9947       else if (ot)
9948         return -1;
9949       else if (cnt <= remote_hw_watchpoint_limit)
9950         return 1;
9951     }
9952   return -1;
9953 }
9954
9955 /* The to_stopped_by_sw_breakpoint method of target remote.  */
9956
9957 static int
9958 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9959 {
9960   struct thread_info *thread = inferior_thread ();
9961
9962   return (thread->priv != NULL
9963           && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9964 }
9965
9966 /* The to_supports_stopped_by_sw_breakpoint method of target
9967    remote.  */
9968
9969 static int
9970 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9971 {
9972   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9973 }
9974
9975 /* The to_stopped_by_hw_breakpoint method of target remote.  */
9976
9977 static int
9978 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9979 {
9980   struct thread_info *thread = inferior_thread ();
9981
9982   return (thread->priv != NULL
9983           && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9984 }
9985
9986 /* The to_supports_stopped_by_hw_breakpoint method of target
9987    remote.  */
9988
9989 static int
9990 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9991 {
9992   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9993 }
9994
9995 static int
9996 remote_stopped_by_watchpoint (struct target_ops *ops)
9997 {
9998   struct thread_info *thread = inferior_thread ();
9999
10000   return (thread->priv != NULL
10001           && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
10002 }
10003
10004 static int
10005 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
10006 {
10007   struct thread_info *thread = inferior_thread ();
10008
10009   if (thread->priv != NULL
10010       && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
10011     {
10012       *addr_p = thread->priv->watch_data_address;
10013       return 1;
10014     }
10015
10016   return 0;
10017 }
10018
10019
10020 static int
10021 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10022                              struct bp_target_info *bp_tgt)
10023 {
10024   CORE_ADDR addr = bp_tgt->reqstd_address;
10025   struct remote_state *rs;
10026   char *p, *endbuf;
10027   char *message;
10028
10029   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10030     return -1;
10031
10032   /* Make sure the remote is pointing at the right process, if
10033      necessary.  */
10034   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10035     set_general_process ();
10036
10037   rs = get_remote_state ();
10038   p = rs->buf;
10039   endbuf = rs->buf + get_remote_packet_size ();
10040
10041   *(p++) = 'Z';
10042   *(p++) = '1';
10043   *(p++) = ',';
10044
10045   addr = remote_address_masked (addr);
10046   p += hexnumstr (p, (ULONGEST) addr);
10047   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10048
10049   if (remote_supports_cond_breakpoints (self))
10050     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10051
10052   if (remote_can_run_breakpoint_commands (self))
10053     remote_add_target_side_commands (gdbarch, bp_tgt, p);
10054
10055   putpkt (rs->buf);
10056   getpkt (&rs->buf, &rs->buf_size, 0);
10057
10058   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10059     {
10060     case PACKET_ERROR:
10061       if (rs->buf[1] == '.')
10062         {
10063           message = strchr (rs->buf + 2, '.');
10064           if (message)
10065             error (_("Remote failure reply: %s"), message + 1);
10066         }
10067       return -1;
10068     case PACKET_UNKNOWN:
10069       return -1;
10070     case PACKET_OK:
10071       return 0;
10072     }
10073   internal_error (__FILE__, __LINE__,
10074                   _("remote_insert_hw_breakpoint: reached end of function"));
10075 }
10076
10077
10078 static int
10079 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10080                              struct bp_target_info *bp_tgt)
10081 {
10082   CORE_ADDR addr;
10083   struct remote_state *rs = get_remote_state ();
10084   char *p = rs->buf;
10085   char *endbuf = rs->buf + get_remote_packet_size ();
10086
10087   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10088     return -1;
10089
10090   /* Make sure the remote is pointing at the right process, if
10091      necessary.  */
10092   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10093     set_general_process ();
10094
10095   *(p++) = 'z';
10096   *(p++) = '1';
10097   *(p++) = ',';
10098
10099   addr = remote_address_masked (bp_tgt->placed_address);
10100   p += hexnumstr (p, (ULONGEST) addr);
10101   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
10102
10103   putpkt (rs->buf);
10104   getpkt (&rs->buf, &rs->buf_size, 0);
10105
10106   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10107     {
10108     case PACKET_ERROR:
10109     case PACKET_UNKNOWN:
10110       return -1;
10111     case PACKET_OK:
10112       return 0;
10113     }
10114   internal_error (__FILE__, __LINE__,
10115                   _("remote_remove_hw_breakpoint: reached end of function"));
10116 }
10117
10118 /* Verify memory using the "qCRC:" request.  */
10119
10120 static int
10121 remote_verify_memory (struct target_ops *ops,
10122                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10123 {
10124   struct remote_state *rs = get_remote_state ();
10125   unsigned long host_crc, target_crc;
10126   char *tmp;
10127
10128   /* It doesn't make sense to use qCRC if the remote target is
10129      connected but not running.  */
10130   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10131     {
10132       enum packet_result result;
10133
10134       /* Make sure the remote is pointing at the right process.  */
10135       set_general_process ();
10136
10137       /* FIXME: assumes lma can fit into long.  */
10138       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10139                  (long) lma, (long) size);
10140       putpkt (rs->buf);
10141
10142       /* Be clever; compute the host_crc before waiting for target
10143          reply.  */
10144       host_crc = xcrc32 (data, size, 0xffffffff);
10145
10146       getpkt (&rs->buf, &rs->buf_size, 0);
10147
10148       result = packet_ok (rs->buf,
10149                           &remote_protocol_packets[PACKET_qCRC]);
10150       if (result == PACKET_ERROR)
10151         return -1;
10152       else if (result == PACKET_OK)
10153         {
10154           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10155             target_crc = target_crc * 16 + fromhex (*tmp);
10156
10157           return (host_crc == target_crc);
10158         }
10159     }
10160
10161   return simple_verify_memory (ops, data, lma, size);
10162 }
10163
10164 /* compare-sections command
10165
10166    With no arguments, compares each loadable section in the exec bfd
10167    with the same memory range on the target, and reports mismatches.
10168    Useful for verifying the image on the target against the exec file.  */
10169
10170 static void
10171 compare_sections_command (char *args, int from_tty)
10172 {
10173   asection *s;
10174   struct cleanup *old_chain;
10175   gdb_byte *sectdata;
10176   const char *sectname;
10177   bfd_size_type size;
10178   bfd_vma lma;
10179   int matched = 0;
10180   int mismatched = 0;
10181   int res;
10182   int read_only = 0;
10183
10184   if (!exec_bfd)
10185     error (_("command cannot be used without an exec file"));
10186
10187   /* Make sure the remote is pointing at the right process.  */
10188   set_general_process ();
10189
10190   if (args != NULL && strcmp (args, "-r") == 0)
10191     {
10192       read_only = 1;
10193       args = NULL;
10194     }
10195
10196   for (s = exec_bfd->sections; s; s = s->next)
10197     {
10198       if (!(s->flags & SEC_LOAD))
10199         continue;               /* Skip non-loadable section.  */
10200
10201       if (read_only && (s->flags & SEC_READONLY) == 0)
10202         continue;               /* Skip writeable sections */
10203
10204       size = bfd_get_section_size (s);
10205       if (size == 0)
10206         continue;               /* Skip zero-length section.  */
10207
10208       sectname = bfd_get_section_name (exec_bfd, s);
10209       if (args && strcmp (args, sectname) != 0)
10210         continue;               /* Not the section selected by user.  */
10211
10212       matched = 1;              /* Do this section.  */
10213       lma = s->lma;
10214
10215       sectdata = (gdb_byte *) xmalloc (size);
10216       old_chain = make_cleanup (xfree, sectdata);
10217       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
10218
10219       res = target_verify_memory (sectdata, lma, size);
10220
10221       if (res == -1)
10222         error (_("target memory fault, section %s, range %s -- %s"), sectname,
10223                paddress (target_gdbarch (), lma),
10224                paddress (target_gdbarch (), lma + size));
10225
10226       printf_filtered ("Section %s, range %s -- %s: ", sectname,
10227                        paddress (target_gdbarch (), lma),
10228                        paddress (target_gdbarch (), lma + size));
10229       if (res)
10230         printf_filtered ("matched.\n");
10231       else
10232         {
10233           printf_filtered ("MIS-MATCHED!\n");
10234           mismatched++;
10235         }
10236
10237       do_cleanups (old_chain);
10238     }
10239   if (mismatched > 0)
10240     warning (_("One or more sections of the target image does not match\n\
10241 the loaded file\n"));
10242   if (args && !matched)
10243     printf_filtered (_("No loaded section named '%s'.\n"), args);
10244 }
10245
10246 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10247    into remote target.  The number of bytes written to the remote
10248    target is returned, or -1 for error.  */
10249
10250 static enum target_xfer_status
10251 remote_write_qxfer (struct target_ops *ops, const char *object_name,
10252                     const char *annex, const gdb_byte *writebuf, 
10253                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10254                     struct packet_config *packet)
10255 {
10256   int i, buf_len;
10257   ULONGEST n;
10258   struct remote_state *rs = get_remote_state ();
10259   int max_size = get_memory_write_packet_size (); 
10260
10261   if (packet->support == PACKET_DISABLE)
10262     return TARGET_XFER_E_IO;
10263
10264   /* Insert header.  */
10265   i = snprintf (rs->buf, max_size, 
10266                 "qXfer:%s:write:%s:%s:",
10267                 object_name, annex ? annex : "",
10268                 phex_nz (offset, sizeof offset));
10269   max_size -= (i + 1);
10270
10271   /* Escape as much data as fits into rs->buf.  */
10272   buf_len = remote_escape_output 
10273     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10274
10275   if (putpkt_binary (rs->buf, i + buf_len) < 0
10276       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10277       || packet_ok (rs->buf, packet) != PACKET_OK)
10278     return TARGET_XFER_E_IO;
10279
10280   unpack_varlen_hex (rs->buf, &n);
10281
10282   *xfered_len = n;
10283   return TARGET_XFER_OK;
10284 }
10285
10286 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10287    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10288    number of bytes read is returned, or 0 for EOF, or -1 for error.
10289    The number of bytes read may be less than LEN without indicating an
10290    EOF.  PACKET is checked and updated to indicate whether the remote
10291    target supports this object.  */
10292
10293 static enum target_xfer_status
10294 remote_read_qxfer (struct target_ops *ops, const char *object_name,
10295                    const char *annex,
10296                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10297                    ULONGEST *xfered_len,
10298                    struct packet_config *packet)
10299 {
10300   struct remote_state *rs = get_remote_state ();
10301   LONGEST i, n, packet_len;
10302
10303   if (packet->support == PACKET_DISABLE)
10304     return TARGET_XFER_E_IO;
10305
10306   /* Check whether we've cached an end-of-object packet that matches
10307      this request.  */
10308   if (rs->finished_object)
10309     {
10310       if (strcmp (object_name, rs->finished_object) == 0
10311           && strcmp (annex ? annex : "", rs->finished_annex) == 0
10312           && offset == rs->finished_offset)
10313         return TARGET_XFER_EOF;
10314
10315
10316       /* Otherwise, we're now reading something different.  Discard
10317          the cache.  */
10318       xfree (rs->finished_object);
10319       xfree (rs->finished_annex);
10320       rs->finished_object = NULL;
10321       rs->finished_annex = NULL;
10322     }
10323
10324   /* Request only enough to fit in a single packet.  The actual data
10325      may not, since we don't know how much of it will need to be escaped;
10326      the target is free to respond with slightly less data.  We subtract
10327      five to account for the response type and the protocol frame.  */
10328   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10329   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10330             object_name, annex ? annex : "",
10331             phex_nz (offset, sizeof offset),
10332             phex_nz (n, sizeof n));
10333   i = putpkt (rs->buf);
10334   if (i < 0)
10335     return TARGET_XFER_E_IO;
10336
10337   rs->buf[0] = '\0';
10338   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10339   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10340     return TARGET_XFER_E_IO;
10341
10342   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10343     error (_("Unknown remote qXfer reply: %s"), rs->buf);
10344
10345   /* 'm' means there is (or at least might be) more data after this
10346      batch.  That does not make sense unless there's at least one byte
10347      of data in this reply.  */
10348   if (rs->buf[0] == 'm' && packet_len == 1)
10349     error (_("Remote qXfer reply contained no data."));
10350
10351   /* Got some data.  */
10352   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10353                              packet_len - 1, readbuf, n);
10354
10355   /* 'l' is an EOF marker, possibly including a final block of data,
10356      or possibly empty.  If we have the final block of a non-empty
10357      object, record this fact to bypass a subsequent partial read.  */
10358   if (rs->buf[0] == 'l' && offset + i > 0)
10359     {
10360       rs->finished_object = xstrdup (object_name);
10361       rs->finished_annex = xstrdup (annex ? annex : "");
10362       rs->finished_offset = offset + i;
10363     }
10364
10365   if (i == 0)
10366     return TARGET_XFER_EOF;
10367   else
10368     {
10369       *xfered_len = i;
10370       return TARGET_XFER_OK;
10371     }
10372 }
10373
10374 static enum target_xfer_status
10375 remote_xfer_partial (struct target_ops *ops, enum target_object object,
10376                      const char *annex, gdb_byte *readbuf,
10377                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10378                      ULONGEST *xfered_len)
10379 {
10380   struct remote_state *rs;
10381   int i;
10382   char *p2;
10383   char query_type;
10384   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10385
10386   set_remote_traceframe ();
10387   set_general_thread (inferior_ptid);
10388
10389   rs = get_remote_state ();
10390
10391   /* Handle memory using the standard memory routines.  */
10392   if (object == TARGET_OBJECT_MEMORY)
10393     {
10394       /* If the remote target is connected but not running, we should
10395          pass this request down to a lower stratum (e.g. the executable
10396          file).  */
10397       if (!target_has_execution)
10398         return TARGET_XFER_EOF;
10399
10400       if (writebuf != NULL)
10401         return remote_write_bytes (offset, writebuf, len, unit_size,
10402                                    xfered_len);
10403       else
10404         return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10405                                   xfered_len);
10406     }
10407
10408   /* Handle SPU memory using qxfer packets.  */
10409   if (object == TARGET_OBJECT_SPU)
10410     {
10411       if (readbuf)
10412         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
10413                                   xfered_len, &remote_protocol_packets
10414                                   [PACKET_qXfer_spu_read]);
10415       else
10416         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
10417                                    xfered_len, &remote_protocol_packets
10418                                    [PACKET_qXfer_spu_write]);
10419     }
10420
10421   /* Handle extra signal info using qxfer packets.  */
10422   if (object == TARGET_OBJECT_SIGNAL_INFO)
10423     {
10424       if (readbuf)
10425         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10426                                   xfered_len, &remote_protocol_packets
10427                                   [PACKET_qXfer_siginfo_read]);
10428       else
10429         return remote_write_qxfer (ops, "siginfo", annex,
10430                                    writebuf, offset, len, xfered_len,
10431                                    &remote_protocol_packets
10432                                    [PACKET_qXfer_siginfo_write]);
10433     }
10434
10435   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10436     {
10437       if (readbuf)
10438         return remote_read_qxfer (ops, "statictrace", annex,
10439                                   readbuf, offset, len, xfered_len,
10440                                   &remote_protocol_packets
10441                                   [PACKET_qXfer_statictrace_read]);
10442       else
10443         return TARGET_XFER_E_IO;
10444     }
10445
10446   /* Only handle flash writes.  */
10447   if (writebuf != NULL)
10448     {
10449       switch (object)
10450         {
10451         case TARGET_OBJECT_FLASH:
10452           return remote_flash_write (ops, offset, len, xfered_len,
10453                                      writebuf);
10454
10455         default:
10456           return TARGET_XFER_E_IO;
10457         }
10458     }
10459
10460   /* Map pre-existing objects onto letters.  DO NOT do this for new
10461      objects!!!  Instead specify new query packets.  */
10462   switch (object)
10463     {
10464     case TARGET_OBJECT_AVR:
10465       query_type = 'R';
10466       break;
10467
10468     case TARGET_OBJECT_AUXV:
10469       gdb_assert (annex == NULL);
10470       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10471                                 xfered_len,
10472                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10473
10474     case TARGET_OBJECT_AVAILABLE_FEATURES:
10475       return remote_read_qxfer
10476         (ops, "features", annex, readbuf, offset, len, xfered_len,
10477          &remote_protocol_packets[PACKET_qXfer_features]);
10478
10479     case TARGET_OBJECT_LIBRARIES:
10480       return remote_read_qxfer
10481         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10482          &remote_protocol_packets[PACKET_qXfer_libraries]);
10483
10484     case TARGET_OBJECT_LIBRARIES_SVR4:
10485       return remote_read_qxfer
10486         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10487          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10488
10489     case TARGET_OBJECT_MEMORY_MAP:
10490       gdb_assert (annex == NULL);
10491       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10492                                  xfered_len,
10493                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10494
10495     case TARGET_OBJECT_OSDATA:
10496       /* Should only get here if we're connected.  */
10497       gdb_assert (rs->remote_desc);
10498       return remote_read_qxfer
10499         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10500         &remote_protocol_packets[PACKET_qXfer_osdata]);
10501
10502     case TARGET_OBJECT_THREADS:
10503       gdb_assert (annex == NULL);
10504       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10505                                 xfered_len,
10506                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10507
10508     case TARGET_OBJECT_TRACEFRAME_INFO:
10509       gdb_assert (annex == NULL);
10510       return remote_read_qxfer
10511         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10512          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10513
10514     case TARGET_OBJECT_FDPIC:
10515       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10516                                 xfered_len,
10517                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10518
10519     case TARGET_OBJECT_OPENVMS_UIB:
10520       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10521                                 xfered_len,
10522                                 &remote_protocol_packets[PACKET_qXfer_uib]);
10523
10524     case TARGET_OBJECT_BTRACE:
10525       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10526                                 xfered_len,
10527         &remote_protocol_packets[PACKET_qXfer_btrace]);
10528
10529     case TARGET_OBJECT_BTRACE_CONF:
10530       return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10531                                 len, xfered_len,
10532         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10533
10534     case TARGET_OBJECT_EXEC_FILE:
10535       return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10536                                 len, xfered_len,
10537         &remote_protocol_packets[PACKET_qXfer_exec_file]);
10538
10539     default:
10540       return TARGET_XFER_E_IO;
10541     }
10542
10543   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
10544      large enough let the caller deal with it.  */
10545   if (len < get_remote_packet_size ())
10546     return TARGET_XFER_E_IO;
10547   len = get_remote_packet_size ();
10548
10549   /* Except for querying the minimum buffer size, target must be open.  */
10550   if (!rs->remote_desc)
10551     error (_("remote query is only available after target open"));
10552
10553   gdb_assert (annex != NULL);
10554   gdb_assert (readbuf != NULL);
10555
10556   p2 = rs->buf;
10557   *p2++ = 'q';
10558   *p2++ = query_type;
10559
10560   /* We used one buffer char for the remote protocol q command and
10561      another for the query type.  As the remote protocol encapsulation
10562      uses 4 chars plus one extra in case we are debugging
10563      (remote_debug), we have PBUFZIZ - 7 left to pack the query
10564      string.  */
10565   i = 0;
10566   while (annex[i] && (i < (get_remote_packet_size () - 8)))
10567     {
10568       /* Bad caller may have sent forbidden characters.  */
10569       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10570       *p2++ = annex[i];
10571       i++;
10572     }
10573   *p2 = '\0';
10574   gdb_assert (annex[i] == '\0');
10575
10576   i = putpkt (rs->buf);
10577   if (i < 0)
10578     return TARGET_XFER_E_IO;
10579
10580   getpkt (&rs->buf, &rs->buf_size, 0);
10581   strcpy ((char *) readbuf, rs->buf);
10582
10583   *xfered_len = strlen ((char *) readbuf);
10584   return TARGET_XFER_OK;
10585 }
10586
10587 /* Implementation of to_get_memory_xfer_limit.  */
10588
10589 static ULONGEST
10590 remote_get_memory_xfer_limit (struct target_ops *ops)
10591 {
10592   return get_memory_write_packet_size ();
10593 }
10594
10595 static int
10596 remote_search_memory (struct target_ops* ops,
10597                       CORE_ADDR start_addr, ULONGEST search_space_len,
10598                       const gdb_byte *pattern, ULONGEST pattern_len,
10599                       CORE_ADDR *found_addrp)
10600 {
10601   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10602   struct remote_state *rs = get_remote_state ();
10603   int max_size = get_memory_write_packet_size ();
10604   struct packet_config *packet =
10605     &remote_protocol_packets[PACKET_qSearch_memory];
10606   /* Number of packet bytes used to encode the pattern;
10607      this could be more than PATTERN_LEN due to escape characters.  */
10608   int escaped_pattern_len;
10609   /* Amount of pattern that was encodable in the packet.  */
10610   int used_pattern_len;
10611   int i;
10612   int found;
10613   ULONGEST found_addr;
10614
10615   /* Don't go to the target if we don't have to.
10616      This is done before checking packet->support to avoid the possibility that
10617      a success for this edge case means the facility works in general.  */
10618   if (pattern_len > search_space_len)
10619     return 0;
10620   if (pattern_len == 0)
10621     {
10622       *found_addrp = start_addr;
10623       return 1;
10624     }
10625
10626   /* If we already know the packet isn't supported, fall back to the simple
10627      way of searching memory.  */
10628
10629   if (packet_config_support (packet) == PACKET_DISABLE)
10630     {
10631       /* Target doesn't provided special support, fall back and use the
10632          standard support (copy memory and do the search here).  */
10633       return simple_search_memory (ops, start_addr, search_space_len,
10634                                    pattern, pattern_len, found_addrp);
10635     }
10636
10637   /* Make sure the remote is pointing at the right process.  */
10638   set_general_process ();
10639
10640   /* Insert header.  */
10641   i = snprintf (rs->buf, max_size, 
10642                 "qSearch:memory:%s;%s;",
10643                 phex_nz (start_addr, addr_size),
10644                 phex_nz (search_space_len, sizeof (search_space_len)));
10645   max_size -= (i + 1);
10646
10647   /* Escape as much data as fits into rs->buf.  */
10648   escaped_pattern_len =
10649     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10650                           &used_pattern_len, max_size);
10651
10652   /* Bail if the pattern is too large.  */
10653   if (used_pattern_len != pattern_len)
10654     error (_("Pattern is too large to transmit to remote target."));
10655
10656   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10657       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10658       || packet_ok (rs->buf, packet) != PACKET_OK)
10659     {
10660       /* The request may not have worked because the command is not
10661          supported.  If so, fall back to the simple way.  */
10662       if (packet->support == PACKET_DISABLE)
10663         {
10664           return simple_search_memory (ops, start_addr, search_space_len,
10665                                        pattern, pattern_len, found_addrp);
10666         }
10667       return -1;
10668     }
10669
10670   if (rs->buf[0] == '0')
10671     found = 0;
10672   else if (rs->buf[0] == '1')
10673     {
10674       found = 1;
10675       if (rs->buf[1] != ',')
10676         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10677       unpack_varlen_hex (rs->buf + 2, &found_addr);
10678       *found_addrp = found_addr;
10679     }
10680   else
10681     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10682
10683   return found;
10684 }
10685
10686 static void
10687 remote_rcmd (struct target_ops *self, const char *command,
10688              struct ui_file *outbuf)
10689 {
10690   struct remote_state *rs = get_remote_state ();
10691   char *p = rs->buf;
10692
10693   if (!rs->remote_desc)
10694     error (_("remote rcmd is only available after target open"));
10695
10696   /* Send a NULL command across as an empty command.  */
10697   if (command == NULL)
10698     command = "";
10699
10700   /* The query prefix.  */
10701   strcpy (rs->buf, "qRcmd,");
10702   p = strchr (rs->buf, '\0');
10703
10704   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10705       > get_remote_packet_size ())
10706     error (_("\"monitor\" command ``%s'' is too long."), command);
10707
10708   /* Encode the actual command.  */
10709   bin2hex ((const gdb_byte *) command, p, strlen (command));
10710
10711   if (putpkt (rs->buf) < 0)
10712     error (_("Communication problem with target."));
10713
10714   /* get/display the response */
10715   while (1)
10716     {
10717       char *buf;
10718
10719       /* XXX - see also remote_get_noisy_reply().  */
10720       QUIT;                     /* Allow user to bail out with ^C.  */
10721       rs->buf[0] = '\0';
10722       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10723         { 
10724           /* Timeout.  Continue to (try to) read responses.
10725              This is better than stopping with an error, assuming the stub
10726              is still executing the (long) monitor command.
10727              If needed, the user can interrupt gdb using C-c, obtaining
10728              an effect similar to stop on timeout.  */
10729           continue;
10730         }
10731       buf = rs->buf;
10732       if (buf[0] == '\0')
10733         error (_("Target does not support this command."));
10734       if (buf[0] == 'O' && buf[1] != 'K')
10735         {
10736           remote_console_output (buf + 1); /* 'O' message from stub.  */
10737           continue;
10738         }
10739       if (strcmp (buf, "OK") == 0)
10740         break;
10741       if (strlen (buf) == 3 && buf[0] == 'E'
10742           && isdigit (buf[1]) && isdigit (buf[2]))
10743         {
10744           error (_("Protocol error with Rcmd"));
10745         }
10746       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10747         {
10748           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10749
10750           fputc_unfiltered (c, outbuf);
10751         }
10752       break;
10753     }
10754 }
10755
10756 static VEC(mem_region_s) *
10757 remote_memory_map (struct target_ops *ops)
10758 {
10759   VEC(mem_region_s) *result = NULL;
10760   char *text = target_read_stralloc (&current_target,
10761                                      TARGET_OBJECT_MEMORY_MAP, NULL);
10762
10763   if (text)
10764     {
10765       struct cleanup *back_to = make_cleanup (xfree, text);
10766
10767       result = parse_memory_map (text);
10768       do_cleanups (back_to);
10769     }
10770
10771   return result;
10772 }
10773
10774 static void
10775 packet_command (char *args, int from_tty)
10776 {
10777   struct remote_state *rs = get_remote_state ();
10778
10779   if (!rs->remote_desc)
10780     error (_("command can only be used with remote target"));
10781
10782   if (!args)
10783     error (_("remote-packet command requires packet text as argument"));
10784
10785   puts_filtered ("sending: ");
10786   print_packet (args);
10787   puts_filtered ("\n");
10788   putpkt (args);
10789
10790   getpkt (&rs->buf, &rs->buf_size, 0);
10791   puts_filtered ("received: ");
10792   print_packet (rs->buf);
10793   puts_filtered ("\n");
10794 }
10795
10796 #if 0
10797 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10798
10799 static void display_thread_info (struct gdb_ext_thread_info *info);
10800
10801 static void threadset_test_cmd (char *cmd, int tty);
10802
10803 static void threadalive_test (char *cmd, int tty);
10804
10805 static void threadlist_test_cmd (char *cmd, int tty);
10806
10807 int get_and_display_threadinfo (threadref *ref);
10808
10809 static void threadinfo_test_cmd (char *cmd, int tty);
10810
10811 static int thread_display_step (threadref *ref, void *context);
10812
10813 static void threadlist_update_test_cmd (char *cmd, int tty);
10814
10815 static void init_remote_threadtests (void);
10816
10817 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
10818
10819 static void
10820 threadset_test_cmd (char *cmd, int tty)
10821 {
10822   int sample_thread = SAMPLE_THREAD;
10823
10824   printf_filtered (_("Remote threadset test\n"));
10825   set_general_thread (sample_thread);
10826 }
10827
10828
10829 static void
10830 threadalive_test (char *cmd, int tty)
10831 {
10832   int sample_thread = SAMPLE_THREAD;
10833   int pid = ptid_get_pid (inferior_ptid);
10834   ptid_t ptid = ptid_build (pid, sample_thread, 0);
10835
10836   if (remote_thread_alive (ptid))
10837     printf_filtered ("PASS: Thread alive test\n");
10838   else
10839     printf_filtered ("FAIL: Thread alive test\n");
10840 }
10841
10842 void output_threadid (char *title, threadref *ref);
10843
10844 void
10845 output_threadid (char *title, threadref *ref)
10846 {
10847   char hexid[20];
10848
10849   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
10850   hexid[16] = 0;
10851   printf_filtered ("%s  %s\n", title, (&hexid[0]));
10852 }
10853
10854 static void
10855 threadlist_test_cmd (char *cmd, int tty)
10856 {
10857   int startflag = 1;
10858   threadref nextthread;
10859   int done, result_count;
10860   threadref threadlist[3];
10861
10862   printf_filtered ("Remote Threadlist test\n");
10863   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10864                               &result_count, &threadlist[0]))
10865     printf_filtered ("FAIL: threadlist test\n");
10866   else
10867     {
10868       threadref *scan = threadlist;
10869       threadref *limit = scan + result_count;
10870
10871       while (scan < limit)
10872         output_threadid (" thread ", scan++);
10873     }
10874 }
10875
10876 void
10877 display_thread_info (struct gdb_ext_thread_info *info)
10878 {
10879   output_threadid ("Threadid: ", &info->threadid);
10880   printf_filtered ("Name: %s\n ", info->shortname);
10881   printf_filtered ("State: %s\n", info->display);
10882   printf_filtered ("other: %s\n\n", info->more_display);
10883 }
10884
10885 int
10886 get_and_display_threadinfo (threadref *ref)
10887 {
10888   int result;
10889   int set;
10890   struct gdb_ext_thread_info threadinfo;
10891
10892   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10893     | TAG_MOREDISPLAY | TAG_DISPLAY;
10894   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10895     display_thread_info (&threadinfo);
10896   return result;
10897 }
10898
10899 static void
10900 threadinfo_test_cmd (char *cmd, int tty)
10901 {
10902   int athread = SAMPLE_THREAD;
10903   threadref thread;
10904   int set;
10905
10906   int_to_threadref (&thread, athread);
10907   printf_filtered ("Remote Threadinfo test\n");
10908   if (!get_and_display_threadinfo (&thread))
10909     printf_filtered ("FAIL cannot get thread info\n");
10910 }
10911
10912 static int
10913 thread_display_step (threadref *ref, void *context)
10914 {
10915   /* output_threadid(" threadstep ",ref); *//* simple test */
10916   return get_and_display_threadinfo (ref);
10917 }
10918
10919 static void
10920 threadlist_update_test_cmd (char *cmd, int tty)
10921 {
10922   printf_filtered ("Remote Threadlist update test\n");
10923   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10924 }
10925
10926 static void
10927 init_remote_threadtests (void)
10928 {
10929   add_com ("tlist", class_obscure, threadlist_test_cmd,
10930            _("Fetch and print the remote list of "
10931              "thread identifiers, one pkt only"));
10932   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10933            _("Fetch and display info about one thread"));
10934   add_com ("tset", class_obscure, threadset_test_cmd,
10935            _("Test setting to a different thread"));
10936   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10937            _("Iterate through updating all remote thread info"));
10938   add_com ("talive", class_obscure, threadalive_test,
10939            _(" Remote thread alive test "));
10940 }
10941
10942 #endif /* 0 */
10943
10944 /* Convert a thread ID to a string.  Returns the string in a static
10945    buffer.  */
10946
10947 static char *
10948 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10949 {
10950   static char buf[64];
10951   struct remote_state *rs = get_remote_state ();
10952
10953   if (ptid_equal (ptid, null_ptid))
10954     return normal_pid_to_str (ptid);
10955   else if (ptid_is_pid (ptid))
10956     {
10957       /* Printing an inferior target id.  */
10958
10959       /* When multi-process extensions are off, there's no way in the
10960          remote protocol to know the remote process id, if there's any
10961          at all.  There's one exception --- when we're connected with
10962          target extended-remote, and we manually attached to a process
10963          with "attach PID".  We don't record anywhere a flag that
10964          allows us to distinguish that case from the case of
10965          connecting with extended-remote and the stub already being
10966          attached to a process, and reporting yes to qAttached, hence
10967          no smart special casing here.  */
10968       if (!remote_multi_process_p (rs))
10969         {
10970           xsnprintf (buf, sizeof buf, "Remote target");
10971           return buf;
10972         }
10973
10974       return normal_pid_to_str (ptid);
10975     }
10976   else
10977     {
10978       if (ptid_equal (magic_null_ptid, ptid))
10979         xsnprintf (buf, sizeof buf, "Thread <main>");
10980       else if (remote_multi_process_p (rs))
10981         if (ptid_get_lwp (ptid) == 0)
10982           return normal_pid_to_str (ptid);
10983         else
10984           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10985                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
10986       else
10987         xsnprintf (buf, sizeof buf, "Thread %ld",
10988                    ptid_get_lwp (ptid));
10989       return buf;
10990     }
10991 }
10992
10993 /* Get the address of the thread local variable in OBJFILE which is
10994    stored at OFFSET within the thread local storage for thread PTID.  */
10995
10996 static CORE_ADDR
10997 remote_get_thread_local_address (struct target_ops *ops,
10998                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10999 {
11000   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11001     {
11002       struct remote_state *rs = get_remote_state ();
11003       char *p = rs->buf;
11004       char *endp = rs->buf + get_remote_packet_size ();
11005       enum packet_result result;
11006
11007       strcpy (p, "qGetTLSAddr:");
11008       p += strlen (p);
11009       p = write_ptid (p, endp, ptid);
11010       *p++ = ',';
11011       p += hexnumstr (p, offset);
11012       *p++ = ',';
11013       p += hexnumstr (p, lm);
11014       *p++ = '\0';
11015
11016       putpkt (rs->buf);
11017       getpkt (&rs->buf, &rs->buf_size, 0);
11018       result = packet_ok (rs->buf,
11019                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
11020       if (result == PACKET_OK)
11021         {
11022           ULONGEST result;
11023
11024           unpack_varlen_hex (rs->buf, &result);
11025           return result;
11026         }
11027       else if (result == PACKET_UNKNOWN)
11028         throw_error (TLS_GENERIC_ERROR,
11029                      _("Remote target doesn't support qGetTLSAddr packet"));
11030       else
11031         throw_error (TLS_GENERIC_ERROR,
11032                      _("Remote target failed to process qGetTLSAddr request"));
11033     }
11034   else
11035     throw_error (TLS_GENERIC_ERROR,
11036                  _("TLS not supported or disabled on this target"));
11037   /* Not reached.  */
11038   return 0;
11039 }
11040
11041 /* Provide thread local base, i.e. Thread Information Block address.
11042    Returns 1 if ptid is found and thread_local_base is non zero.  */
11043
11044 static int
11045 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
11046 {
11047   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11048     {
11049       struct remote_state *rs = get_remote_state ();
11050       char *p = rs->buf;
11051       char *endp = rs->buf + get_remote_packet_size ();
11052       enum packet_result result;
11053
11054       strcpy (p, "qGetTIBAddr:");
11055       p += strlen (p);
11056       p = write_ptid (p, endp, ptid);
11057       *p++ = '\0';
11058
11059       putpkt (rs->buf);
11060       getpkt (&rs->buf, &rs->buf_size, 0);
11061       result = packet_ok (rs->buf,
11062                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
11063       if (result == PACKET_OK)
11064         {
11065           ULONGEST result;
11066
11067           unpack_varlen_hex (rs->buf, &result);
11068           if (addr)
11069             *addr = (CORE_ADDR) result;
11070           return 1;
11071         }
11072       else if (result == PACKET_UNKNOWN)
11073         error (_("Remote target doesn't support qGetTIBAddr packet"));
11074       else
11075         error (_("Remote target failed to process qGetTIBAddr request"));
11076     }
11077   else
11078     error (_("qGetTIBAddr not supported or disabled on this target"));
11079   /* Not reached.  */
11080   return 0;
11081 }
11082
11083 /* Support for inferring a target description based on the current
11084    architecture and the size of a 'g' packet.  While the 'g' packet
11085    can have any size (since optional registers can be left off the
11086    end), some sizes are easily recognizable given knowledge of the
11087    approximate architecture.  */
11088
11089 struct remote_g_packet_guess
11090 {
11091   int bytes;
11092   const struct target_desc *tdesc;
11093 };
11094 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11095 DEF_VEC_O(remote_g_packet_guess_s);
11096
11097 struct remote_g_packet_data
11098 {
11099   VEC(remote_g_packet_guess_s) *guesses;
11100 };
11101
11102 static struct gdbarch_data *remote_g_packet_data_handle;
11103
11104 static void *
11105 remote_g_packet_data_init (struct obstack *obstack)
11106 {
11107   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11108 }
11109
11110 void
11111 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11112                                 const struct target_desc *tdesc)
11113 {
11114   struct remote_g_packet_data *data
11115     = ((struct remote_g_packet_data *)
11116        gdbarch_data (gdbarch, remote_g_packet_data_handle));
11117   struct remote_g_packet_guess new_guess, *guess;
11118   int ix;
11119
11120   gdb_assert (tdesc != NULL);
11121
11122   for (ix = 0;
11123        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11124        ix++)
11125     if (guess->bytes == bytes)
11126       internal_error (__FILE__, __LINE__,
11127                       _("Duplicate g packet description added for size %d"),
11128                       bytes);
11129
11130   new_guess.bytes = bytes;
11131   new_guess.tdesc = tdesc;
11132   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11133 }
11134
11135 /* Return 1 if remote_read_description would do anything on this target
11136    and architecture, 0 otherwise.  */
11137
11138 static int
11139 remote_read_description_p (struct target_ops *target)
11140 {
11141   struct remote_g_packet_data *data
11142     = ((struct remote_g_packet_data *)
11143        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11144
11145   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11146     return 1;
11147
11148   return 0;
11149 }
11150
11151 static const struct target_desc *
11152 remote_read_description (struct target_ops *target)
11153 {
11154   struct remote_g_packet_data *data
11155     = ((struct remote_g_packet_data *)
11156        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11157
11158   /* Do not try this during initial connection, when we do not know
11159      whether there is a running but stopped thread.  */
11160   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11161     return target->beneath->to_read_description (target->beneath);
11162
11163   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11164     {
11165       struct remote_g_packet_guess *guess;
11166       int ix;
11167       int bytes = send_g_packet ();
11168
11169       for (ix = 0;
11170            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11171            ix++)
11172         if (guess->bytes == bytes)
11173           return guess->tdesc;
11174
11175       /* We discard the g packet.  A minor optimization would be to
11176          hold on to it, and fill the register cache once we have selected
11177          an architecture, but it's too tricky to do safely.  */
11178     }
11179
11180   return target->beneath->to_read_description (target->beneath);
11181 }
11182
11183 /* Remote file transfer support.  This is host-initiated I/O, not
11184    target-initiated; for target-initiated, see remote-fileio.c.  */
11185
11186 /* If *LEFT is at least the length of STRING, copy STRING to
11187    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11188    decrease *LEFT.  Otherwise raise an error.  */
11189
11190 static void
11191 remote_buffer_add_string (char **buffer, int *left, char *string)
11192 {
11193   int len = strlen (string);
11194
11195   if (len > *left)
11196     error (_("Packet too long for target."));
11197
11198   memcpy (*buffer, string, len);
11199   *buffer += len;
11200   *left -= len;
11201
11202   /* NUL-terminate the buffer as a convenience, if there is
11203      room.  */
11204   if (*left)
11205     **buffer = '\0';
11206 }
11207
11208 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11209    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11210    decrease *LEFT.  Otherwise raise an error.  */
11211
11212 static void
11213 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11214                          int len)
11215 {
11216   if (2 * len > *left)
11217     error (_("Packet too long for target."));
11218
11219   bin2hex (bytes, *buffer, len);
11220   *buffer += 2 * len;
11221   *left -= 2 * len;
11222
11223   /* NUL-terminate the buffer as a convenience, if there is
11224      room.  */
11225   if (*left)
11226     **buffer = '\0';
11227 }
11228
11229 /* If *LEFT is large enough, convert VALUE to hex and add it to
11230    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11231    decrease *LEFT.  Otherwise raise an error.  */
11232
11233 static void
11234 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11235 {
11236   int len = hexnumlen (value);
11237
11238   if (len > *left)
11239     error (_("Packet too long for target."));
11240
11241   hexnumstr (*buffer, value);
11242   *buffer += len;
11243   *left -= len;
11244
11245   /* NUL-terminate the buffer as a convenience, if there is
11246      room.  */
11247   if (*left)
11248     **buffer = '\0';
11249 }
11250
11251 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
11252    value, *REMOTE_ERRNO to the remote error number or zero if none
11253    was included, and *ATTACHMENT to point to the start of the annex
11254    if any.  The length of the packet isn't needed here; there may
11255    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11256
11257    Return 0 if the packet could be parsed, -1 if it could not.  If
11258    -1 is returned, the other variables may not be initialized.  */
11259
11260 static int
11261 remote_hostio_parse_result (char *buffer, int *retcode,
11262                             int *remote_errno, char **attachment)
11263 {
11264   char *p, *p2;
11265
11266   *remote_errno = 0;
11267   *attachment = NULL;
11268
11269   if (buffer[0] != 'F')
11270     return -1;
11271
11272   errno = 0;
11273   *retcode = strtol (&buffer[1], &p, 16);
11274   if (errno != 0 || p == &buffer[1])
11275     return -1;
11276
11277   /* Check for ",errno".  */
11278   if (*p == ',')
11279     {
11280       errno = 0;
11281       *remote_errno = strtol (p + 1, &p2, 16);
11282       if (errno != 0 || p + 1 == p2)
11283         return -1;
11284       p = p2;
11285     }
11286
11287   /* Check for ";attachment".  If there is no attachment, the
11288      packet should end here.  */
11289   if (*p == ';')
11290     {
11291       *attachment = p + 1;
11292       return 0;
11293     }
11294   else if (*p == '\0')
11295     return 0;
11296   else
11297     return -1;
11298 }
11299
11300 /* Send a prepared I/O packet to the target and read its response.
11301    The prepared packet is in the global RS->BUF before this function
11302    is called, and the answer is there when we return.
11303
11304    COMMAND_BYTES is the length of the request to send, which may include
11305    binary data.  WHICH_PACKET is the packet configuration to check
11306    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
11307    is set to the error number and -1 is returned.  Otherwise the value
11308    returned by the function is returned.
11309
11310    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11311    attachment is expected; an error will be reported if there's a
11312    mismatch.  If one is found, *ATTACHMENT will be set to point into
11313    the packet buffer and *ATTACHMENT_LEN will be set to the
11314    attachment's length.  */
11315
11316 static int
11317 remote_hostio_send_command (int command_bytes, int which_packet,
11318                             int *remote_errno, char **attachment,
11319                             int *attachment_len)
11320 {
11321   struct remote_state *rs = get_remote_state ();
11322   int ret, bytes_read;
11323   char *attachment_tmp;
11324
11325   if (!rs->remote_desc
11326       || packet_support (which_packet) == PACKET_DISABLE)
11327     {
11328       *remote_errno = FILEIO_ENOSYS;
11329       return -1;
11330     }
11331
11332   putpkt_binary (rs->buf, command_bytes);
11333   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11334
11335   /* If it timed out, something is wrong.  Don't try to parse the
11336      buffer.  */
11337   if (bytes_read < 0)
11338     {
11339       *remote_errno = FILEIO_EINVAL;
11340       return -1;
11341     }
11342
11343   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11344     {
11345     case PACKET_ERROR:
11346       *remote_errno = FILEIO_EINVAL;
11347       return -1;
11348     case PACKET_UNKNOWN:
11349       *remote_errno = FILEIO_ENOSYS;
11350       return -1;
11351     case PACKET_OK:
11352       break;
11353     }
11354
11355   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11356                                   &attachment_tmp))
11357     {
11358       *remote_errno = FILEIO_EINVAL;
11359       return -1;
11360     }
11361
11362   /* Make sure we saw an attachment if and only if we expected one.  */
11363   if ((attachment_tmp == NULL && attachment != NULL)
11364       || (attachment_tmp != NULL && attachment == NULL))
11365     {
11366       *remote_errno = FILEIO_EINVAL;
11367       return -1;
11368     }
11369
11370   /* If an attachment was found, it must point into the packet buffer;
11371      work out how many bytes there were.  */
11372   if (attachment_tmp != NULL)
11373     {
11374       *attachment = attachment_tmp;
11375       *attachment_len = bytes_read - (*attachment - rs->buf);
11376     }
11377
11378   return ret;
11379 }
11380
11381 /* Invalidate the readahead cache.  */
11382
11383 static void
11384 readahead_cache_invalidate (void)
11385 {
11386   struct remote_state *rs = get_remote_state ();
11387
11388   rs->readahead_cache.fd = -1;
11389 }
11390
11391 /* Invalidate the readahead cache if it is holding data for FD.  */
11392
11393 static void
11394 readahead_cache_invalidate_fd (int fd)
11395 {
11396   struct remote_state *rs = get_remote_state ();
11397
11398   if (rs->readahead_cache.fd == fd)
11399     rs->readahead_cache.fd = -1;
11400 }
11401
11402 /* Set the filesystem remote_hostio functions that take FILENAME
11403    arguments will use.  Return 0 on success, or -1 if an error
11404    occurs (and set *REMOTE_ERRNO).  */
11405
11406 static int
11407 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11408 {
11409   struct remote_state *rs = get_remote_state ();
11410   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11411   char *p = rs->buf;
11412   int left = get_remote_packet_size () - 1;
11413   char arg[9];
11414   int ret;
11415
11416   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11417     return 0;
11418
11419   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11420     return 0;
11421
11422   remote_buffer_add_string (&p, &left, "vFile:setfs:");
11423
11424   xsnprintf (arg, sizeof (arg), "%x", required_pid);
11425   remote_buffer_add_string (&p, &left, arg);
11426
11427   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11428                                     remote_errno, NULL, NULL);
11429
11430   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11431     return 0;
11432
11433   if (ret == 0)
11434     rs->fs_pid = required_pid;
11435
11436   return ret;
11437 }
11438
11439 /* Implementation of to_fileio_open.  */
11440
11441 static int
11442 remote_hostio_open (struct target_ops *self,
11443                     struct inferior *inf, const char *filename,
11444                     int flags, int mode, int warn_if_slow,
11445                     int *remote_errno)
11446 {
11447   struct remote_state *rs = get_remote_state ();
11448   char *p = rs->buf;
11449   int left = get_remote_packet_size () - 1;
11450
11451   if (warn_if_slow)
11452     {
11453       static int warning_issued = 0;
11454
11455       printf_unfiltered (_("Reading %s from remote target...\n"),
11456                          filename);
11457
11458       if (!warning_issued)
11459         {
11460           warning (_("File transfers from remote targets can be slow."
11461                      " Use \"set sysroot\" to access files locally"
11462                      " instead."));
11463           warning_issued = 1;
11464         }
11465     }
11466
11467   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11468     return -1;
11469
11470   remote_buffer_add_string (&p, &left, "vFile:open:");
11471
11472   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11473                            strlen (filename));
11474   remote_buffer_add_string (&p, &left, ",");
11475
11476   remote_buffer_add_int (&p, &left, flags);
11477   remote_buffer_add_string (&p, &left, ",");
11478
11479   remote_buffer_add_int (&p, &left, mode);
11480
11481   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11482                                      remote_errno, NULL, NULL);
11483 }
11484
11485 /* Implementation of to_fileio_pwrite.  */
11486
11487 static int
11488 remote_hostio_pwrite (struct target_ops *self,
11489                       int fd, const gdb_byte *write_buf, int len,
11490                       ULONGEST offset, int *remote_errno)
11491 {
11492   struct remote_state *rs = get_remote_state ();
11493   char *p = rs->buf;
11494   int left = get_remote_packet_size ();
11495   int out_len;
11496
11497   readahead_cache_invalidate_fd (fd);
11498
11499   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11500
11501   remote_buffer_add_int (&p, &left, fd);
11502   remote_buffer_add_string (&p, &left, ",");
11503
11504   remote_buffer_add_int (&p, &left, offset);
11505   remote_buffer_add_string (&p, &left, ",");
11506
11507   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11508                              get_remote_packet_size () - (p - rs->buf));
11509
11510   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11511                                      remote_errno, NULL, NULL);
11512 }
11513
11514 /* Helper for the implementation of to_fileio_pread.  Read the file
11515    from the remote side with vFile:pread.  */
11516
11517 static int
11518 remote_hostio_pread_vFile (struct target_ops *self,
11519                            int fd, gdb_byte *read_buf, int len,
11520                            ULONGEST offset, int *remote_errno)
11521 {
11522   struct remote_state *rs = get_remote_state ();
11523   char *p = rs->buf;
11524   char *attachment;
11525   int left = get_remote_packet_size ();
11526   int ret, attachment_len;
11527   int read_len;
11528
11529   remote_buffer_add_string (&p, &left, "vFile:pread:");
11530
11531   remote_buffer_add_int (&p, &left, fd);
11532   remote_buffer_add_string (&p, &left, ",");
11533
11534   remote_buffer_add_int (&p, &left, len);
11535   remote_buffer_add_string (&p, &left, ",");
11536
11537   remote_buffer_add_int (&p, &left, offset);
11538
11539   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11540                                     remote_errno, &attachment,
11541                                     &attachment_len);
11542
11543   if (ret < 0)
11544     return ret;
11545
11546   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11547                                     read_buf, len);
11548   if (read_len != ret)
11549     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11550
11551   return ret;
11552 }
11553
11554 /* Serve pread from the readahead cache.  Returns number of bytes
11555    read, or 0 if the request can't be served from the cache.  */
11556
11557 static int
11558 remote_hostio_pread_from_cache (struct remote_state *rs,
11559                                 int fd, gdb_byte *read_buf, size_t len,
11560                                 ULONGEST offset)
11561 {
11562   struct readahead_cache *cache = &rs->readahead_cache;
11563
11564   if (cache->fd == fd
11565       && cache->offset <= offset
11566       && offset < cache->offset + cache->bufsize)
11567     {
11568       ULONGEST max = cache->offset + cache->bufsize;
11569
11570       if (offset + len > max)
11571         len = max - offset;
11572
11573       memcpy (read_buf, cache->buf + offset - cache->offset, len);
11574       return len;
11575     }
11576
11577   return 0;
11578 }
11579
11580 /* Implementation of to_fileio_pread.  */
11581
11582 static int
11583 remote_hostio_pread (struct target_ops *self,
11584                      int fd, gdb_byte *read_buf, int len,
11585                      ULONGEST offset, int *remote_errno)
11586 {
11587   int ret;
11588   struct remote_state *rs = get_remote_state ();
11589   struct readahead_cache *cache = &rs->readahead_cache;
11590
11591   ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11592   if (ret > 0)
11593     {
11594       cache->hit_count++;
11595
11596       if (remote_debug)
11597         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11598                             pulongest (cache->hit_count));
11599       return ret;
11600     }
11601
11602   cache->miss_count++;
11603   if (remote_debug)
11604     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11605                         pulongest (cache->miss_count));
11606
11607   cache->fd = fd;
11608   cache->offset = offset;
11609   cache->bufsize = get_remote_packet_size ();
11610   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11611
11612   ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11613                                    cache->offset, remote_errno);
11614   if (ret <= 0)
11615     {
11616       readahead_cache_invalidate_fd (fd);
11617       return ret;
11618     }
11619
11620   cache->bufsize = ret;
11621   return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11622 }
11623
11624 /* Implementation of to_fileio_close.  */
11625
11626 static int
11627 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11628 {
11629   struct remote_state *rs = get_remote_state ();
11630   char *p = rs->buf;
11631   int left = get_remote_packet_size () - 1;
11632
11633   readahead_cache_invalidate_fd (fd);
11634
11635   remote_buffer_add_string (&p, &left, "vFile:close:");
11636
11637   remote_buffer_add_int (&p, &left, fd);
11638
11639   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11640                                      remote_errno, NULL, NULL);
11641 }
11642
11643 /* Implementation of to_fileio_unlink.  */
11644
11645 static int
11646 remote_hostio_unlink (struct target_ops *self,
11647                       struct inferior *inf, const char *filename,
11648                       int *remote_errno)
11649 {
11650   struct remote_state *rs = get_remote_state ();
11651   char *p = rs->buf;
11652   int left = get_remote_packet_size () - 1;
11653
11654   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11655     return -1;
11656
11657   remote_buffer_add_string (&p, &left, "vFile:unlink:");
11658
11659   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11660                            strlen (filename));
11661
11662   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11663                                      remote_errno, NULL, NULL);
11664 }
11665
11666 /* Implementation of to_fileio_readlink.  */
11667
11668 static char *
11669 remote_hostio_readlink (struct target_ops *self,
11670                         struct inferior *inf, const char *filename,
11671                         int *remote_errno)
11672 {
11673   struct remote_state *rs = get_remote_state ();
11674   char *p = rs->buf;
11675   char *attachment;
11676   int left = get_remote_packet_size ();
11677   int len, attachment_len;
11678   int read_len;
11679   char *ret;
11680
11681   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11682     return NULL;
11683
11684   remote_buffer_add_string (&p, &left, "vFile:readlink:");
11685
11686   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11687                            strlen (filename));
11688
11689   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11690                                     remote_errno, &attachment,
11691                                     &attachment_len);
11692
11693   if (len < 0)
11694     return NULL;
11695
11696   ret = (char *) xmalloc (len + 1);
11697
11698   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11699                                     (gdb_byte *) ret, len);
11700   if (read_len != len)
11701     error (_("Readlink returned %d, but %d bytes."), len, read_len);
11702
11703   ret[len] = '\0';
11704   return ret;
11705 }
11706
11707 /* Implementation of to_fileio_fstat.  */
11708
11709 static int
11710 remote_hostio_fstat (struct target_ops *self,
11711                      int fd, struct stat *st,
11712                      int *remote_errno)
11713 {
11714   struct remote_state *rs = get_remote_state ();
11715   char *p = rs->buf;
11716   int left = get_remote_packet_size ();
11717   int attachment_len, ret;
11718   char *attachment;
11719   struct fio_stat fst;
11720   int read_len;
11721
11722   remote_buffer_add_string (&p, &left, "vFile:fstat:");
11723
11724   remote_buffer_add_int (&p, &left, fd);
11725
11726   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11727                                     remote_errno, &attachment,
11728                                     &attachment_len);
11729   if (ret < 0)
11730     {
11731       if (*remote_errno != FILEIO_ENOSYS)
11732         return ret;
11733
11734       /* Strictly we should return -1, ENOSYS here, but when
11735          "set sysroot remote:" was implemented in August 2008
11736          BFD's need for a stat function was sidestepped with
11737          this hack.  This was not remedied until March 2015
11738          so we retain the previous behavior to avoid breaking
11739          compatibility.
11740
11741          Note that the memset is a March 2015 addition; older
11742          GDBs set st_size *and nothing else* so the structure
11743          would have garbage in all other fields.  This might
11744          break something but retaining the previous behavior
11745          here would be just too wrong.  */
11746
11747       memset (st, 0, sizeof (struct stat));
11748       st->st_size = INT_MAX;
11749       return 0;
11750     }
11751
11752   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11753                                     (gdb_byte *) &fst, sizeof (fst));
11754
11755   if (read_len != ret)
11756     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11757
11758   if (read_len != sizeof (fst))
11759     error (_("vFile:fstat returned %d bytes, but expecting %d."),
11760            read_len, (int) sizeof (fst));
11761
11762   remote_fileio_to_host_stat (&fst, st);
11763
11764   return 0;
11765 }
11766
11767 /* Implementation of to_filesystem_is_local.  */
11768
11769 static int
11770 remote_filesystem_is_local (struct target_ops *self)
11771 {
11772   /* Valgrind GDB presents itself as a remote target but works
11773      on the local filesystem: it does not implement remote get
11774      and users are not expected to set a sysroot.  To handle
11775      this case we treat the remote filesystem as local if the
11776      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11777      does not support vFile:open.  */
11778   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11779     {
11780       enum packet_support ps = packet_support (PACKET_vFile_open);
11781
11782       if (ps == PACKET_SUPPORT_UNKNOWN)
11783         {
11784           int fd, remote_errno;
11785
11786           /* Try opening a file to probe support.  The supplied
11787              filename is irrelevant, we only care about whether
11788              the stub recognizes the packet or not.  */
11789           fd = remote_hostio_open (self, NULL, "just probing",
11790                                    FILEIO_O_RDONLY, 0700, 0,
11791                                    &remote_errno);
11792
11793           if (fd >= 0)
11794             remote_hostio_close (self, fd, &remote_errno);
11795
11796           ps = packet_support (PACKET_vFile_open);
11797         }
11798
11799       if (ps == PACKET_DISABLE)
11800         {
11801           static int warning_issued = 0;
11802
11803           if (!warning_issued)
11804             {
11805               warning (_("remote target does not support file"
11806                          " transfer, attempting to access files"
11807                          " from local filesystem."));
11808               warning_issued = 1;
11809             }
11810
11811           return 1;
11812         }
11813     }
11814
11815   return 0;
11816 }
11817
11818 static int
11819 remote_fileio_errno_to_host (int errnum)
11820 {
11821   switch (errnum)
11822     {
11823       case FILEIO_EPERM:
11824         return EPERM;
11825       case FILEIO_ENOENT:
11826         return ENOENT;
11827       case FILEIO_EINTR:
11828         return EINTR;
11829       case FILEIO_EIO:
11830         return EIO;
11831       case FILEIO_EBADF:
11832         return EBADF;
11833       case FILEIO_EACCES:
11834         return EACCES;
11835       case FILEIO_EFAULT:
11836         return EFAULT;
11837       case FILEIO_EBUSY:
11838         return EBUSY;
11839       case FILEIO_EEXIST:
11840         return EEXIST;
11841       case FILEIO_ENODEV:
11842         return ENODEV;
11843       case FILEIO_ENOTDIR:
11844         return ENOTDIR;
11845       case FILEIO_EISDIR:
11846         return EISDIR;
11847       case FILEIO_EINVAL:
11848         return EINVAL;
11849       case FILEIO_ENFILE:
11850         return ENFILE;
11851       case FILEIO_EMFILE:
11852         return EMFILE;
11853       case FILEIO_EFBIG:
11854         return EFBIG;
11855       case FILEIO_ENOSPC:
11856         return ENOSPC;
11857       case FILEIO_ESPIPE:
11858         return ESPIPE;
11859       case FILEIO_EROFS:
11860         return EROFS;
11861       case FILEIO_ENOSYS:
11862         return ENOSYS;
11863       case FILEIO_ENAMETOOLONG:
11864         return ENAMETOOLONG;
11865     }
11866   return -1;
11867 }
11868
11869 static char *
11870 remote_hostio_error (int errnum)
11871 {
11872   int host_error = remote_fileio_errno_to_host (errnum);
11873
11874   if (host_error == -1)
11875     error (_("Unknown remote I/O error %d"), errnum);
11876   else
11877     error (_("Remote I/O error: %s"), safe_strerror (host_error));
11878 }
11879
11880 static void
11881 remote_hostio_close_cleanup (void *opaque)
11882 {
11883   int fd = *(int *) opaque;
11884   int remote_errno;
11885
11886   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11887 }
11888
11889 void
11890 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11891 {
11892   struct cleanup *back_to, *close_cleanup;
11893   int retcode, fd, remote_errno, bytes, io_size;
11894   FILE *file;
11895   gdb_byte *buffer;
11896   int bytes_in_buffer;
11897   int saw_eof;
11898   ULONGEST offset;
11899   struct remote_state *rs = get_remote_state ();
11900
11901   if (!rs->remote_desc)
11902     error (_("command can only be used with remote target"));
11903
11904   file = gdb_fopen_cloexec (local_file, "rb");
11905   if (file == NULL)
11906     perror_with_name (local_file);
11907   back_to = make_cleanup_fclose (file);
11908
11909   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11910                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11911                                          | FILEIO_O_TRUNC),
11912                            0700, 0, &remote_errno);
11913   if (fd == -1)
11914     remote_hostio_error (remote_errno);
11915
11916   /* Send up to this many bytes at once.  They won't all fit in the
11917      remote packet limit, so we'll transfer slightly fewer.  */
11918   io_size = get_remote_packet_size ();
11919   buffer = (gdb_byte *) xmalloc (io_size);
11920   make_cleanup (xfree, buffer);
11921
11922   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11923
11924   bytes_in_buffer = 0;
11925   saw_eof = 0;
11926   offset = 0;
11927   while (bytes_in_buffer || !saw_eof)
11928     {
11929       if (!saw_eof)
11930         {
11931           bytes = fread (buffer + bytes_in_buffer, 1,
11932                          io_size - bytes_in_buffer,
11933                          file);
11934           if (bytes == 0)
11935             {
11936               if (ferror (file))
11937                 error (_("Error reading %s."), local_file);
11938               else
11939                 {
11940                   /* EOF.  Unless there is something still in the
11941                      buffer from the last iteration, we are done.  */
11942                   saw_eof = 1;
11943                   if (bytes_in_buffer == 0)
11944                     break;
11945                 }
11946             }
11947         }
11948       else
11949         bytes = 0;
11950
11951       bytes += bytes_in_buffer;
11952       bytes_in_buffer = 0;
11953
11954       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11955                                       fd, buffer, bytes,
11956                                       offset, &remote_errno);
11957
11958       if (retcode < 0)
11959         remote_hostio_error (remote_errno);
11960       else if (retcode == 0)
11961         error (_("Remote write of %d bytes returned 0!"), bytes);
11962       else if (retcode < bytes)
11963         {
11964           /* Short write.  Save the rest of the read data for the next
11965              write.  */
11966           bytes_in_buffer = bytes - retcode;
11967           memmove (buffer, buffer + retcode, bytes_in_buffer);
11968         }
11969
11970       offset += retcode;
11971     }
11972
11973   discard_cleanups (close_cleanup);
11974   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11975     remote_hostio_error (remote_errno);
11976
11977   if (from_tty)
11978     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11979   do_cleanups (back_to);
11980 }
11981
11982 void
11983 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11984 {
11985   struct cleanup *back_to, *close_cleanup;
11986   int fd, remote_errno, bytes, io_size;
11987   FILE *file;
11988   gdb_byte *buffer;
11989   ULONGEST offset;
11990   struct remote_state *rs = get_remote_state ();
11991
11992   if (!rs->remote_desc)
11993     error (_("command can only be used with remote target"));
11994
11995   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11996                            remote_file, FILEIO_O_RDONLY, 0, 0,
11997                            &remote_errno);
11998   if (fd == -1)
11999     remote_hostio_error (remote_errno);
12000
12001   file = gdb_fopen_cloexec (local_file, "wb");
12002   if (file == NULL)
12003     perror_with_name (local_file);
12004   back_to = make_cleanup_fclose (file);
12005
12006   /* Send up to this many bytes at once.  They won't all fit in the
12007      remote packet limit, so we'll transfer slightly fewer.  */
12008   io_size = get_remote_packet_size ();
12009   buffer = (gdb_byte *) xmalloc (io_size);
12010   make_cleanup (xfree, buffer);
12011
12012   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12013
12014   offset = 0;
12015   while (1)
12016     {
12017       bytes = remote_hostio_pread (find_target_at (process_stratum),
12018                                    fd, buffer, io_size, offset, &remote_errno);
12019       if (bytes == 0)
12020         /* Success, but no bytes, means end-of-file.  */
12021         break;
12022       if (bytes == -1)
12023         remote_hostio_error (remote_errno);
12024
12025       offset += bytes;
12026
12027       bytes = fwrite (buffer, 1, bytes, file);
12028       if (bytes == 0)
12029         perror_with_name (local_file);
12030     }
12031
12032   discard_cleanups (close_cleanup);
12033   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12034     remote_hostio_error (remote_errno);
12035
12036   if (from_tty)
12037     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12038   do_cleanups (back_to);
12039 }
12040
12041 void
12042 remote_file_delete (const char *remote_file, int from_tty)
12043 {
12044   int retcode, remote_errno;
12045   struct remote_state *rs = get_remote_state ();
12046
12047   if (!rs->remote_desc)
12048     error (_("command can only be used with remote target"));
12049
12050   retcode = remote_hostio_unlink (find_target_at (process_stratum),
12051                                   NULL, remote_file, &remote_errno);
12052   if (retcode == -1)
12053     remote_hostio_error (remote_errno);
12054
12055   if (from_tty)
12056     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12057 }
12058
12059 static void
12060 remote_put_command (char *args, int from_tty)
12061 {
12062   struct cleanup *back_to;
12063   char **argv;
12064
12065   if (args == NULL)
12066     error_no_arg (_("file to put"));
12067
12068   argv = gdb_buildargv (args);
12069   back_to = make_cleanup_freeargv (argv);
12070   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12071     error (_("Invalid parameters to remote put"));
12072
12073   remote_file_put (argv[0], argv[1], from_tty);
12074
12075   do_cleanups (back_to);
12076 }
12077
12078 static void
12079 remote_get_command (char *args, int from_tty)
12080 {
12081   struct cleanup *back_to;
12082   char **argv;
12083
12084   if (args == NULL)
12085     error_no_arg (_("file to get"));
12086
12087   argv = gdb_buildargv (args);
12088   back_to = make_cleanup_freeargv (argv);
12089   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12090     error (_("Invalid parameters to remote get"));
12091
12092   remote_file_get (argv[0], argv[1], from_tty);
12093
12094   do_cleanups (back_to);
12095 }
12096
12097 static void
12098 remote_delete_command (char *args, int from_tty)
12099 {
12100   struct cleanup *back_to;
12101   char **argv;
12102
12103   if (args == NULL)
12104     error_no_arg (_("file to delete"));
12105
12106   argv = gdb_buildargv (args);
12107   back_to = make_cleanup_freeargv (argv);
12108   if (argv[0] == NULL || argv[1] != NULL)
12109     error (_("Invalid parameters to remote delete"));
12110
12111   remote_file_delete (argv[0], from_tty);
12112
12113   do_cleanups (back_to);
12114 }
12115
12116 static void
12117 remote_command (char *args, int from_tty)
12118 {
12119   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12120 }
12121
12122 static int
12123 remote_can_execute_reverse (struct target_ops *self)
12124 {
12125   if (packet_support (PACKET_bs) == PACKET_ENABLE
12126       || packet_support (PACKET_bc) == PACKET_ENABLE)
12127     return 1;
12128   else
12129     return 0;
12130 }
12131
12132 static int
12133 remote_supports_non_stop (struct target_ops *self)
12134 {
12135   return 1;
12136 }
12137
12138 static int
12139 remote_supports_disable_randomization (struct target_ops *self)
12140 {
12141   /* Only supported in extended mode.  */
12142   return 0;
12143 }
12144
12145 static int
12146 remote_supports_multi_process (struct target_ops *self)
12147 {
12148   struct remote_state *rs = get_remote_state ();
12149
12150   return remote_multi_process_p (rs);
12151 }
12152
12153 static int
12154 remote_supports_cond_tracepoints (void)
12155 {
12156   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12157 }
12158
12159 static int
12160 remote_supports_cond_breakpoints (struct target_ops *self)
12161 {
12162   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12163 }
12164
12165 static int
12166 remote_supports_fast_tracepoints (void)
12167 {
12168   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12169 }
12170
12171 static int
12172 remote_supports_static_tracepoints (void)
12173 {
12174   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12175 }
12176
12177 static int
12178 remote_supports_install_in_trace (void)
12179 {
12180   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12181 }
12182
12183 static int
12184 remote_supports_enable_disable_tracepoint (struct target_ops *self)
12185 {
12186   return (packet_support (PACKET_EnableDisableTracepoints_feature)
12187           == PACKET_ENABLE);
12188 }
12189
12190 static int
12191 remote_supports_string_tracing (struct target_ops *self)
12192 {
12193   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12194 }
12195
12196 static int
12197 remote_can_run_breakpoint_commands (struct target_ops *self)
12198 {
12199   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12200 }
12201
12202 static void
12203 remote_trace_init (struct target_ops *self)
12204 {
12205   putpkt ("QTinit");
12206   remote_get_noisy_reply (&target_buf, &target_buf_size);
12207   if (strcmp (target_buf, "OK") != 0)
12208     error (_("Target does not support this command."));
12209 }
12210
12211 static void free_actions_list (char **actions_list);
12212 static void free_actions_list_cleanup_wrapper (void *);
12213 static void
12214 free_actions_list_cleanup_wrapper (void *al)
12215 {
12216   free_actions_list ((char **) al);
12217 }
12218
12219 static void
12220 free_actions_list (char **actions_list)
12221 {
12222   int ndx;
12223
12224   if (actions_list == 0)
12225     return;
12226
12227   for (ndx = 0; actions_list[ndx]; ndx++)
12228     xfree (actions_list[ndx]);
12229
12230   xfree (actions_list);
12231 }
12232
12233 /* Recursive routine to walk through command list including loops, and
12234    download packets for each command.  */
12235
12236 static void
12237 remote_download_command_source (int num, ULONGEST addr,
12238                                 struct command_line *cmds)
12239 {
12240   struct remote_state *rs = get_remote_state ();
12241   struct command_line *cmd;
12242
12243   for (cmd = cmds; cmd; cmd = cmd->next)
12244     {
12245       QUIT;     /* Allow user to bail out with ^C.  */
12246       strcpy (rs->buf, "QTDPsrc:");
12247       encode_source_string (num, addr, "cmd", cmd->line,
12248                             rs->buf + strlen (rs->buf),
12249                             rs->buf_size - strlen (rs->buf));
12250       putpkt (rs->buf);
12251       remote_get_noisy_reply (&target_buf, &target_buf_size);
12252       if (strcmp (target_buf, "OK"))
12253         warning (_("Target does not support source download."));
12254
12255       if (cmd->control_type == while_control
12256           || cmd->control_type == while_stepping_control)
12257         {
12258           remote_download_command_source (num, addr, *cmd->body_list);
12259
12260           QUIT; /* Allow user to bail out with ^C.  */
12261           strcpy (rs->buf, "QTDPsrc:");
12262           encode_source_string (num, addr, "cmd", "end",
12263                                 rs->buf + strlen (rs->buf),
12264                                 rs->buf_size - strlen (rs->buf));
12265           putpkt (rs->buf);
12266           remote_get_noisy_reply (&target_buf, &target_buf_size);
12267           if (strcmp (target_buf, "OK"))
12268             warning (_("Target does not support source download."));
12269         }
12270     }
12271 }
12272
12273 static void
12274 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
12275 {
12276 #define BUF_SIZE 2048
12277
12278   CORE_ADDR tpaddr;
12279   char addrbuf[40];
12280   char buf[BUF_SIZE];
12281   char **tdp_actions;
12282   char **stepping_actions;
12283   int ndx;
12284   struct cleanup *old_chain = NULL;
12285   struct agent_expr *aexpr;
12286   struct cleanup *aexpr_chain = NULL;
12287   char *pkt;
12288   struct breakpoint *b = loc->owner;
12289   struct tracepoint *t = (struct tracepoint *) b;
12290
12291   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12292   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
12293                             tdp_actions);
12294   (void) make_cleanup (free_actions_list_cleanup_wrapper,
12295                        stepping_actions);
12296
12297   tpaddr = loc->address;
12298   sprintf_vma (addrbuf, tpaddr);
12299   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12300              addrbuf, /* address */
12301              (b->enable_state == bp_enabled ? 'E' : 'D'),
12302              t->step_count, t->pass_count);
12303   /* Fast tracepoints are mostly handled by the target, but we can
12304      tell the target how big of an instruction block should be moved
12305      around.  */
12306   if (b->type == bp_fast_tracepoint)
12307     {
12308       /* Only test for support at download time; we may not know
12309          target capabilities at definition time.  */
12310       if (remote_supports_fast_tracepoints ())
12311         {
12312           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12313                                                 NULL))
12314             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12315                        gdb_insn_length (loc->gdbarch, tpaddr));
12316           else
12317             /* If it passed validation at definition but fails now,
12318                something is very wrong.  */
12319             internal_error (__FILE__, __LINE__,
12320                             _("Fast tracepoint not "
12321                               "valid during download"));
12322         }
12323       else
12324         /* Fast tracepoints are functionally identical to regular
12325            tracepoints, so don't take lack of support as a reason to
12326            give up on the trace run.  */
12327         warning (_("Target does not support fast tracepoints, "
12328                    "downloading %d as regular tracepoint"), b->number);
12329     }
12330   else if (b->type == bp_static_tracepoint)
12331     {
12332       /* Only test for support at download time; we may not know
12333          target capabilities at definition time.  */
12334       if (remote_supports_static_tracepoints ())
12335         {
12336           struct static_tracepoint_marker marker;
12337
12338           if (target_static_tracepoint_marker_at (tpaddr, &marker))
12339             strcat (buf, ":S");
12340           else
12341             error (_("Static tracepoint not valid during download"));
12342         }
12343       else
12344         /* Fast tracepoints are functionally identical to regular
12345            tracepoints, so don't take lack of support as a reason
12346            to give up on the trace run.  */
12347         error (_("Target does not support static tracepoints"));
12348     }
12349   /* If the tracepoint has a conditional, make it into an agent
12350      expression and append to the definition.  */
12351   if (loc->cond)
12352     {
12353       /* Only test support at download time, we may not know target
12354          capabilities at definition time.  */
12355       if (remote_supports_cond_tracepoints ())
12356         {
12357           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
12358           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
12359           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12360                      aexpr->len);
12361           pkt = buf + strlen (buf);
12362           for (ndx = 0; ndx < aexpr->len; ++ndx)
12363             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12364           *pkt = '\0';
12365           do_cleanups (aexpr_chain);
12366         }
12367       else
12368         warning (_("Target does not support conditional tracepoints, "
12369                    "ignoring tp %d cond"), b->number);
12370     }
12371
12372   if (b->commands || *default_collect)
12373     strcat (buf, "-");
12374   putpkt (buf);
12375   remote_get_noisy_reply (&target_buf, &target_buf_size);
12376   if (strcmp (target_buf, "OK"))
12377     error (_("Target does not support tracepoints."));
12378
12379   /* do_single_steps (t); */
12380   if (tdp_actions)
12381     {
12382       for (ndx = 0; tdp_actions[ndx]; ndx++)
12383         {
12384           QUIT; /* Allow user to bail out with ^C.  */
12385           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12386                      b->number, addrbuf, /* address */
12387                      tdp_actions[ndx],
12388                      ((tdp_actions[ndx + 1] || stepping_actions)
12389                       ? '-' : 0));
12390           putpkt (buf);
12391           remote_get_noisy_reply (&target_buf,
12392                                   &target_buf_size);
12393           if (strcmp (target_buf, "OK"))
12394             error (_("Error on target while setting tracepoints."));
12395         }
12396     }
12397   if (stepping_actions)
12398     {
12399       for (ndx = 0; stepping_actions[ndx]; ndx++)
12400         {
12401           QUIT; /* Allow user to bail out with ^C.  */
12402           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12403                      b->number, addrbuf, /* address */
12404                      ((ndx == 0) ? "S" : ""),
12405                      stepping_actions[ndx],
12406                      (stepping_actions[ndx + 1] ? "-" : ""));
12407           putpkt (buf);
12408           remote_get_noisy_reply (&target_buf,
12409                                   &target_buf_size);
12410           if (strcmp (target_buf, "OK"))
12411             error (_("Error on target while setting tracepoints."));
12412         }
12413     }
12414
12415   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12416     {
12417       if (b->location != NULL)
12418         {
12419           strcpy (buf, "QTDPsrc:");
12420           encode_source_string (b->number, loc->address, "at",
12421                                 event_location_to_string (b->location),
12422                                 buf + strlen (buf), 2048 - strlen (buf));
12423           putpkt (buf);
12424           remote_get_noisy_reply (&target_buf, &target_buf_size);
12425           if (strcmp (target_buf, "OK"))
12426             warning (_("Target does not support source download."));
12427         }
12428       if (b->cond_string)
12429         {
12430           strcpy (buf, "QTDPsrc:");
12431           encode_source_string (b->number, loc->address,
12432                                 "cond", b->cond_string, buf + strlen (buf),
12433                                 2048 - strlen (buf));
12434           putpkt (buf);
12435           remote_get_noisy_reply (&target_buf, &target_buf_size);
12436           if (strcmp (target_buf, "OK"))
12437             warning (_("Target does not support source download."));
12438         }
12439       remote_download_command_source (b->number, loc->address,
12440                                       breakpoint_commands (b));
12441     }
12442
12443   do_cleanups (old_chain);
12444 }
12445
12446 static int
12447 remote_can_download_tracepoint (struct target_ops *self)
12448 {
12449   struct remote_state *rs = get_remote_state ();
12450   struct trace_status *ts;
12451   int status;
12452
12453   /* Don't try to install tracepoints until we've relocated our
12454      symbols, and fetched and merged the target's tracepoint list with
12455      ours.  */
12456   if (rs->starting_up)
12457     return 0;
12458
12459   ts = current_trace_status ();
12460   status = remote_get_trace_status (self, ts);
12461
12462   if (status == -1 || !ts->running_known || !ts->running)
12463     return 0;
12464
12465   /* If we are in a tracing experiment, but remote stub doesn't support
12466      installing tracepoint in trace, we have to return.  */
12467   if (!remote_supports_install_in_trace ())
12468     return 0;
12469
12470   return 1;
12471 }
12472
12473
12474 static void
12475 remote_download_trace_state_variable (struct target_ops *self,
12476                                       struct trace_state_variable *tsv)
12477 {
12478   struct remote_state *rs = get_remote_state ();
12479   char *p;
12480
12481   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12482              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12483              tsv->builtin);
12484   p = rs->buf + strlen (rs->buf);
12485   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12486     error (_("Trace state variable name too long for tsv definition packet"));
12487   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12488   *p++ = '\0';
12489   putpkt (rs->buf);
12490   remote_get_noisy_reply (&target_buf, &target_buf_size);
12491   if (*target_buf == '\0')
12492     error (_("Target does not support this command."));
12493   if (strcmp (target_buf, "OK") != 0)
12494     error (_("Error on target while downloading trace state variable."));
12495 }
12496
12497 static void
12498 remote_enable_tracepoint (struct target_ops *self,
12499                           struct bp_location *location)
12500 {
12501   struct remote_state *rs = get_remote_state ();
12502   char addr_buf[40];
12503
12504   sprintf_vma (addr_buf, location->address);
12505   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12506              location->owner->number, addr_buf);
12507   putpkt (rs->buf);
12508   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12509   if (*rs->buf == '\0')
12510     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12511   if (strcmp (rs->buf, "OK") != 0)
12512     error (_("Error on target while enabling tracepoint."));
12513 }
12514
12515 static void
12516 remote_disable_tracepoint (struct target_ops *self,
12517                            struct bp_location *location)
12518 {
12519   struct remote_state *rs = get_remote_state ();
12520   char addr_buf[40];
12521
12522   sprintf_vma (addr_buf, location->address);
12523   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12524              location->owner->number, addr_buf);
12525   putpkt (rs->buf);
12526   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12527   if (*rs->buf == '\0')
12528     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12529   if (strcmp (rs->buf, "OK") != 0)
12530     error (_("Error on target while disabling tracepoint."));
12531 }
12532
12533 static void
12534 remote_trace_set_readonly_regions (struct target_ops *self)
12535 {
12536   asection *s;
12537   bfd *abfd = NULL;
12538   bfd_size_type size;
12539   bfd_vma vma;
12540   int anysecs = 0;
12541   int offset = 0;
12542
12543   if (!exec_bfd)
12544     return;                     /* No information to give.  */
12545
12546   strcpy (target_buf, "QTro");
12547   offset = strlen (target_buf);
12548   for (s = exec_bfd->sections; s; s = s->next)
12549     {
12550       char tmp1[40], tmp2[40];
12551       int sec_length;
12552
12553       if ((s->flags & SEC_LOAD) == 0 ||
12554       /*  (s->flags & SEC_CODE) == 0 || */
12555           (s->flags & SEC_READONLY) == 0)
12556         continue;
12557
12558       anysecs = 1;
12559       vma = bfd_get_section_vma (abfd, s);
12560       size = bfd_get_section_size (s);
12561       sprintf_vma (tmp1, vma);
12562       sprintf_vma (tmp2, vma + size);
12563       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12564       if (offset + sec_length + 1 > target_buf_size)
12565         {
12566           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12567             warning (_("\
12568 Too many sections for read-only sections definition packet."));
12569           break;
12570         }
12571       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12572                  tmp1, tmp2);
12573       offset += sec_length;
12574     }
12575   if (anysecs)
12576     {
12577       putpkt (target_buf);
12578       getpkt (&target_buf, &target_buf_size, 0);
12579     }
12580 }
12581
12582 static void
12583 remote_trace_start (struct target_ops *self)
12584 {
12585   putpkt ("QTStart");
12586   remote_get_noisy_reply (&target_buf, &target_buf_size);
12587   if (*target_buf == '\0')
12588     error (_("Target does not support this command."));
12589   if (strcmp (target_buf, "OK") != 0)
12590     error (_("Bogus reply from target: %s"), target_buf);
12591 }
12592
12593 static int
12594 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12595 {
12596   /* Initialize it just to avoid a GCC false warning.  */
12597   char *p = NULL;
12598   /* FIXME we need to get register block size some other way.  */
12599   extern int trace_regblock_size;
12600   enum packet_result result;
12601
12602   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12603     return -1;
12604
12605   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12606
12607   putpkt ("qTStatus");
12608
12609   TRY
12610     {
12611       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12612     }
12613   CATCH (ex, RETURN_MASK_ERROR)
12614     {
12615       if (ex.error != TARGET_CLOSE_ERROR)
12616         {
12617           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12618           return -1;
12619         }
12620       throw_exception (ex);
12621     }
12622   END_CATCH
12623
12624   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12625
12626   /* If the remote target doesn't do tracing, flag it.  */
12627   if (result == PACKET_UNKNOWN)
12628     return -1;
12629
12630   /* We're working with a live target.  */
12631   ts->filename = NULL;
12632
12633   if (*p++ != 'T')
12634     error (_("Bogus trace status reply from target: %s"), target_buf);
12635
12636   /* Function 'parse_trace_status' sets default value of each field of
12637      'ts' at first, so we don't have to do it here.  */
12638   parse_trace_status (p, ts);
12639
12640   return ts->running;
12641 }
12642
12643 static void
12644 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12645                               struct uploaded_tp *utp)
12646 {
12647   struct remote_state *rs = get_remote_state ();
12648   char *reply;
12649   struct bp_location *loc;
12650   struct tracepoint *tp = (struct tracepoint *) bp;
12651   size_t size = get_remote_packet_size ();
12652
12653   if (tp)
12654     {
12655       tp->base.hit_count = 0;
12656       tp->traceframe_usage = 0;
12657       for (loc = tp->base.loc; loc; loc = loc->next)
12658         {
12659           /* If the tracepoint was never downloaded, don't go asking for
12660              any status.  */
12661           if (tp->number_on_target == 0)
12662             continue;
12663           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12664                      phex_nz (loc->address, 0));
12665           putpkt (rs->buf);
12666           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12667           if (reply && *reply)
12668             {
12669               if (*reply == 'V')
12670                 parse_tracepoint_status (reply + 1, bp, utp);
12671             }
12672         }
12673     }
12674   else if (utp)
12675     {
12676       utp->hit_count = 0;
12677       utp->traceframe_usage = 0;
12678       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12679                  phex_nz (utp->addr, 0));
12680       putpkt (rs->buf);
12681       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12682       if (reply && *reply)
12683         {
12684           if (*reply == 'V')
12685             parse_tracepoint_status (reply + 1, bp, utp);
12686         }
12687     }
12688 }
12689
12690 static void
12691 remote_trace_stop (struct target_ops *self)
12692 {
12693   putpkt ("QTStop");
12694   remote_get_noisy_reply (&target_buf, &target_buf_size);
12695   if (*target_buf == '\0')
12696     error (_("Target does not support this command."));
12697   if (strcmp (target_buf, "OK") != 0)
12698     error (_("Bogus reply from target: %s"), target_buf);
12699 }
12700
12701 static int
12702 remote_trace_find (struct target_ops *self,
12703                    enum trace_find_type type, int num,
12704                    CORE_ADDR addr1, CORE_ADDR addr2,
12705                    int *tpp)
12706 {
12707   struct remote_state *rs = get_remote_state ();
12708   char *endbuf = rs->buf + get_remote_packet_size ();
12709   char *p, *reply;
12710   int target_frameno = -1, target_tracept = -1;
12711
12712   /* Lookups other than by absolute frame number depend on the current
12713      trace selected, so make sure it is correct on the remote end
12714      first.  */
12715   if (type != tfind_number)
12716     set_remote_traceframe ();
12717
12718   p = rs->buf;
12719   strcpy (p, "QTFrame:");
12720   p = strchr (p, '\0');
12721   switch (type)
12722     {
12723     case tfind_number:
12724       xsnprintf (p, endbuf - p, "%x", num);
12725       break;
12726     case tfind_pc:
12727       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12728       break;
12729     case tfind_tp:
12730       xsnprintf (p, endbuf - p, "tdp:%x", num);
12731       break;
12732     case tfind_range:
12733       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12734                  phex_nz (addr2, 0));
12735       break;
12736     case tfind_outside:
12737       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12738                  phex_nz (addr2, 0));
12739       break;
12740     default:
12741       error (_("Unknown trace find type %d"), type);
12742     }
12743
12744   putpkt (rs->buf);
12745   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12746   if (*reply == '\0')
12747     error (_("Target does not support this command."));
12748
12749   while (reply && *reply)
12750     switch (*reply)
12751       {
12752       case 'F':
12753         p = ++reply;
12754         target_frameno = (int) strtol (p, &reply, 16);
12755         if (reply == p)
12756           error (_("Unable to parse trace frame number"));
12757         /* Don't update our remote traceframe number cache on failure
12758            to select a remote traceframe.  */
12759         if (target_frameno == -1)
12760           return -1;
12761         break;
12762       case 'T':
12763         p = ++reply;
12764         target_tracept = (int) strtol (p, &reply, 16);
12765         if (reply == p)
12766           error (_("Unable to parse tracepoint number"));
12767         break;
12768       case 'O':         /* "OK"? */
12769         if (reply[1] == 'K' && reply[2] == '\0')
12770           reply += 2;
12771         else
12772           error (_("Bogus reply from target: %s"), reply);
12773         break;
12774       default:
12775         error (_("Bogus reply from target: %s"), reply);
12776       }
12777   if (tpp)
12778     *tpp = target_tracept;
12779
12780   rs->remote_traceframe_number = target_frameno;
12781   return target_frameno;
12782 }
12783
12784 static int
12785 remote_get_trace_state_variable_value (struct target_ops *self,
12786                                        int tsvnum, LONGEST *val)
12787 {
12788   struct remote_state *rs = get_remote_state ();
12789   char *reply;
12790   ULONGEST uval;
12791
12792   set_remote_traceframe ();
12793
12794   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12795   putpkt (rs->buf);
12796   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12797   if (reply && *reply)
12798     {
12799       if (*reply == 'V')
12800         {
12801           unpack_varlen_hex (reply + 1, &uval);
12802           *val = (LONGEST) uval;
12803           return 1;
12804         }
12805     }
12806   return 0;
12807 }
12808
12809 static int
12810 remote_save_trace_data (struct target_ops *self, const char *filename)
12811 {
12812   struct remote_state *rs = get_remote_state ();
12813   char *p, *reply;
12814
12815   p = rs->buf;
12816   strcpy (p, "QTSave:");
12817   p += strlen (p);
12818   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12819     error (_("Remote file name too long for trace save packet"));
12820   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12821   *p++ = '\0';
12822   putpkt (rs->buf);
12823   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12824   if (*reply == '\0')
12825     error (_("Target does not support this command."));
12826   if (strcmp (reply, "OK") != 0)
12827     error (_("Bogus reply from target: %s"), reply);
12828   return 0;
12829 }
12830
12831 /* This is basically a memory transfer, but needs to be its own packet
12832    because we don't know how the target actually organizes its trace
12833    memory, plus we want to be able to ask for as much as possible, but
12834    not be unhappy if we don't get as much as we ask for.  */
12835
12836 static LONGEST
12837 remote_get_raw_trace_data (struct target_ops *self,
12838                            gdb_byte *buf, ULONGEST offset, LONGEST len)
12839 {
12840   struct remote_state *rs = get_remote_state ();
12841   char *reply;
12842   char *p;
12843   int rslt;
12844
12845   p = rs->buf;
12846   strcpy (p, "qTBuffer:");
12847   p += strlen (p);
12848   p += hexnumstr (p, offset);
12849   *p++ = ',';
12850   p += hexnumstr (p, len);
12851   *p++ = '\0';
12852
12853   putpkt (rs->buf);
12854   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12855   if (reply && *reply)
12856     {
12857       /* 'l' by itself means we're at the end of the buffer and
12858          there is nothing more to get.  */
12859       if (*reply == 'l')
12860         return 0;
12861
12862       /* Convert the reply into binary.  Limit the number of bytes to
12863          convert according to our passed-in buffer size, rather than
12864          what was returned in the packet; if the target is
12865          unexpectedly generous and gives us a bigger reply than we
12866          asked for, we don't want to crash.  */
12867       rslt = hex2bin (target_buf, buf, len);
12868       return rslt;
12869     }
12870
12871   /* Something went wrong, flag as an error.  */
12872   return -1;
12873 }
12874
12875 static void
12876 remote_set_disconnected_tracing (struct target_ops *self, int val)
12877 {
12878   struct remote_state *rs = get_remote_state ();
12879
12880   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12881     {
12882       char *reply;
12883
12884       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12885       putpkt (rs->buf);
12886       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12887       if (*reply == '\0')
12888         error (_("Target does not support this command."));
12889       if (strcmp (reply, "OK") != 0)
12890         error (_("Bogus reply from target: %s"), reply);
12891     }
12892   else if (val)
12893     warning (_("Target does not support disconnected tracing."));
12894 }
12895
12896 static int
12897 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12898 {
12899   struct thread_info *info = find_thread_ptid (ptid);
12900
12901   if (info && info->priv)
12902     return info->priv->core;
12903   return -1;
12904 }
12905
12906 static void
12907 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12908 {
12909   struct remote_state *rs = get_remote_state ();
12910   char *reply;
12911
12912   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12913   putpkt (rs->buf);
12914   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12915   if (*reply == '\0')
12916     error (_("Target does not support this command."));
12917   if (strcmp (reply, "OK") != 0)
12918     error (_("Bogus reply from target: %s"), reply);
12919 }
12920
12921 static struct traceframe_info *
12922 remote_traceframe_info (struct target_ops *self)
12923 {
12924   char *text;
12925
12926   text = target_read_stralloc (&current_target,
12927                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12928   if (text != NULL)
12929     {
12930       struct traceframe_info *info;
12931       struct cleanup *back_to = make_cleanup (xfree, text);
12932
12933       info = parse_traceframe_info (text);
12934       do_cleanups (back_to);
12935       return info;
12936     }
12937
12938   return NULL;
12939 }
12940
12941 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
12942    instruction on which a fast tracepoint may be placed.  Returns -1
12943    if the packet is not supported, and 0 if the minimum instruction
12944    length is unknown.  */
12945
12946 static int
12947 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12948 {
12949   struct remote_state *rs = get_remote_state ();
12950   char *reply;
12951
12952   /* If we're not debugging a process yet, the IPA can't be
12953      loaded.  */
12954   if (!target_has_execution)
12955     return 0;
12956
12957   /* Make sure the remote is pointing at the right process.  */
12958   set_general_process ();
12959
12960   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12961   putpkt (rs->buf);
12962   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12963   if (*reply == '\0')
12964     return -1;
12965   else
12966     {
12967       ULONGEST min_insn_len;
12968
12969       unpack_varlen_hex (reply, &min_insn_len);
12970
12971       return (int) min_insn_len;
12972     }
12973 }
12974
12975 static void
12976 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12977 {
12978   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12979     {
12980       struct remote_state *rs = get_remote_state ();
12981       char *buf = rs->buf;
12982       char *endbuf = rs->buf + get_remote_packet_size ();
12983       enum packet_result result;
12984
12985       gdb_assert (val >= 0 || val == -1);
12986       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12987       /* Send -1 as literal "-1" to avoid host size dependency.  */
12988       if (val < 0)
12989         {
12990           *buf++ = '-';
12991           buf += hexnumstr (buf, (ULONGEST) -val);
12992         }
12993       else
12994         buf += hexnumstr (buf, (ULONGEST) val);
12995
12996       putpkt (rs->buf);
12997       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12998       result = packet_ok (rs->buf,
12999                   &remote_protocol_packets[PACKET_QTBuffer_size]);
13000
13001       if (result != PACKET_OK)
13002         warning (_("Bogus reply from target: %s"), rs->buf);
13003     }
13004 }
13005
13006 static int
13007 remote_set_trace_notes (struct target_ops *self,
13008                         const char *user, const char *notes,
13009                         const char *stop_notes)
13010 {
13011   struct remote_state *rs = get_remote_state ();
13012   char *reply;
13013   char *buf = rs->buf;
13014   char *endbuf = rs->buf + get_remote_packet_size ();
13015   int nbytes;
13016
13017   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13018   if (user)
13019     {
13020       buf += xsnprintf (buf, endbuf - buf, "user:");
13021       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13022       buf += 2 * nbytes;
13023       *buf++ = ';';
13024     }
13025   if (notes)
13026     {
13027       buf += xsnprintf (buf, endbuf - buf, "notes:");
13028       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13029       buf += 2 * nbytes;
13030       *buf++ = ';';
13031     }
13032   if (stop_notes)
13033     {
13034       buf += xsnprintf (buf, endbuf - buf, "tstop:");
13035       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13036       buf += 2 * nbytes;
13037       *buf++ = ';';
13038     }
13039   /* Ensure the buffer is terminated.  */
13040   *buf = '\0';
13041
13042   putpkt (rs->buf);
13043   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
13044   if (*reply == '\0')
13045     return 0;
13046
13047   if (strcmp (reply, "OK") != 0)
13048     error (_("Bogus reply from target: %s"), reply);
13049
13050   return 1;
13051 }
13052
13053 static int
13054 remote_use_agent (struct target_ops *self, int use)
13055 {
13056   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13057     {
13058       struct remote_state *rs = get_remote_state ();
13059
13060       /* If the stub supports QAgent.  */
13061       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13062       putpkt (rs->buf);
13063       getpkt (&rs->buf, &rs->buf_size, 0);
13064
13065       if (strcmp (rs->buf, "OK") == 0)
13066         {
13067           use_agent = use;
13068           return 1;
13069         }
13070     }
13071
13072   return 0;
13073 }
13074
13075 static int
13076 remote_can_use_agent (struct target_ops *self)
13077 {
13078   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13079 }
13080
13081 struct btrace_target_info
13082 {
13083   /* The ptid of the traced thread.  */
13084   ptid_t ptid;
13085
13086   /* The obtained branch trace configuration.  */
13087   struct btrace_config conf;
13088 };
13089
13090 /* Reset our idea of our target's btrace configuration.  */
13091
13092 static void
13093 remote_btrace_reset (void)
13094 {
13095   struct remote_state *rs = get_remote_state ();
13096
13097   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13098 }
13099
13100 /* Check whether the target supports branch tracing.  */
13101
13102 static int
13103 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
13104 {
13105   if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
13106     return 0;
13107   if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
13108     return 0;
13109
13110   switch (format)
13111     {
13112       case BTRACE_FORMAT_NONE:
13113         return 0;
13114
13115       case BTRACE_FORMAT_BTS:
13116         return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
13117
13118       case BTRACE_FORMAT_PT:
13119         /* The trace is decoded on the host.  Even if our target supports it,
13120            we still need to have libipt to decode the trace.  */
13121 #if defined (HAVE_LIBIPT)
13122         return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
13123 #else /* !defined (HAVE_LIBIPT)  */
13124         return 0;
13125 #endif /* !defined (HAVE_LIBIPT)  */
13126     }
13127
13128   internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
13129 }
13130
13131 /* Synchronize the configuration with the target.  */
13132
13133 static void
13134 btrace_sync_conf (const struct btrace_config *conf)
13135 {
13136   struct packet_config *packet;
13137   struct remote_state *rs;
13138   char *buf, *pos, *endbuf;
13139
13140   rs = get_remote_state ();
13141   buf = rs->buf;
13142   endbuf = buf + get_remote_packet_size ();
13143
13144   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13145   if (packet_config_support (packet) == PACKET_ENABLE
13146       && conf->bts.size != rs->btrace_config.bts.size)
13147     {
13148       pos = buf;
13149       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13150                         conf->bts.size);
13151
13152       putpkt (buf);
13153       getpkt (&buf, &rs->buf_size, 0);
13154
13155       if (packet_ok (buf, packet) == PACKET_ERROR)
13156         {
13157           if (buf[0] == 'E' && buf[1] == '.')
13158             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13159           else
13160             error (_("Failed to configure the BTS buffer size."));
13161         }
13162
13163       rs->btrace_config.bts.size = conf->bts.size;
13164     }
13165
13166   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13167   if (packet_config_support (packet) == PACKET_ENABLE
13168       && conf->pt.size != rs->btrace_config.pt.size)
13169     {
13170       pos = buf;
13171       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13172                         conf->pt.size);
13173
13174       putpkt (buf);
13175       getpkt (&buf, &rs->buf_size, 0);
13176
13177       if (packet_ok (buf, packet) == PACKET_ERROR)
13178         {
13179           if (buf[0] == 'E' && buf[1] == '.')
13180             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13181           else
13182             error (_("Failed to configure the trace buffer size."));
13183         }
13184
13185       rs->btrace_config.pt.size = conf->pt.size;
13186     }
13187 }
13188
13189 /* Read the current thread's btrace configuration from the target and
13190    store it into CONF.  */
13191
13192 static void
13193 btrace_read_config (struct btrace_config *conf)
13194 {
13195   char *xml;
13196
13197   xml = target_read_stralloc (&current_target,
13198                               TARGET_OBJECT_BTRACE_CONF, "");
13199   if (xml != NULL)
13200     {
13201       struct cleanup *cleanup;
13202
13203       cleanup = make_cleanup (xfree, xml);
13204       parse_xml_btrace_conf (conf, xml);
13205       do_cleanups (cleanup);
13206     }
13207 }
13208
13209 /* Maybe reopen target btrace.  */
13210
13211 static void
13212 remote_btrace_maybe_reopen (void)
13213 {
13214   struct remote_state *rs = get_remote_state ();
13215   struct cleanup *cleanup;
13216   struct thread_info *tp;
13217   int btrace_target_pushed = 0;
13218   int warned = 0;
13219
13220   cleanup = make_cleanup_restore_current_thread ();
13221   ALL_NON_EXITED_THREADS (tp)
13222     {
13223       set_general_thread (tp->ptid);
13224
13225       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13226       btrace_read_config (&rs->btrace_config);
13227
13228       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13229         continue;
13230
13231 #if !defined (HAVE_LIBIPT)
13232       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13233         {
13234           if (!warned)
13235             {
13236               warned = 1;
13237               warning (_("GDB does not support Intel Processor Trace. "
13238                          "\"record\" will not work in this session."));
13239             }
13240
13241           continue;
13242         }
13243 #endif /* !defined (HAVE_LIBIPT) */
13244
13245       /* Push target, once, but before anything else happens.  This way our
13246          changes to the threads will be cleaned up by unpushing the target
13247          in case btrace_read_config () throws.  */
13248       if (!btrace_target_pushed)
13249         {
13250           btrace_target_pushed = 1;
13251           record_btrace_push_target ();
13252           printf_filtered (_("Target is recording using %s.\n"),
13253                            btrace_format_string (rs->btrace_config.format));
13254         }
13255
13256       tp->btrace.target = XCNEW (struct btrace_target_info);
13257       tp->btrace.target->ptid = tp->ptid;
13258       tp->btrace.target->conf = rs->btrace_config;
13259     }
13260   do_cleanups (cleanup);
13261 }
13262
13263 /* Enable branch tracing.  */
13264
13265 static struct btrace_target_info *
13266 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
13267                       const struct btrace_config *conf)
13268 {
13269   struct btrace_target_info *tinfo = NULL;
13270   struct packet_config *packet = NULL;
13271   struct remote_state *rs = get_remote_state ();
13272   char *buf = rs->buf;
13273   char *endbuf = rs->buf + get_remote_packet_size ();
13274
13275   switch (conf->format)
13276     {
13277       case BTRACE_FORMAT_BTS:
13278         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13279         break;
13280
13281       case BTRACE_FORMAT_PT:
13282         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13283         break;
13284     }
13285
13286   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13287     error (_("Target does not support branch tracing."));
13288
13289   btrace_sync_conf (conf);
13290
13291   set_general_thread (ptid);
13292
13293   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13294   putpkt (rs->buf);
13295   getpkt (&rs->buf, &rs->buf_size, 0);
13296
13297   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13298     {
13299       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13300         error (_("Could not enable branch tracing for %s: %s"),
13301                target_pid_to_str (ptid), rs->buf + 2);
13302       else
13303         error (_("Could not enable branch tracing for %s."),
13304                target_pid_to_str (ptid));
13305     }
13306
13307   tinfo = XCNEW (struct btrace_target_info);
13308   tinfo->ptid = ptid;
13309
13310   /* If we fail to read the configuration, we lose some information, but the
13311      tracing itself is not impacted.  */
13312   TRY
13313     {
13314       btrace_read_config (&tinfo->conf);
13315     }
13316   CATCH (err, RETURN_MASK_ERROR)
13317     {
13318       if (err.message != NULL)
13319         warning ("%s", err.message);
13320     }
13321   END_CATCH
13322
13323   return tinfo;
13324 }
13325
13326 /* Disable branch tracing.  */
13327
13328 static void
13329 remote_disable_btrace (struct target_ops *self,
13330                        struct btrace_target_info *tinfo)
13331 {
13332   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13333   struct remote_state *rs = get_remote_state ();
13334   char *buf = rs->buf;
13335   char *endbuf = rs->buf + get_remote_packet_size ();
13336
13337   if (packet_config_support (packet) != PACKET_ENABLE)
13338     error (_("Target does not support branch tracing."));
13339
13340   set_general_thread (tinfo->ptid);
13341
13342   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13343   putpkt (rs->buf);
13344   getpkt (&rs->buf, &rs->buf_size, 0);
13345
13346   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13347     {
13348       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13349         error (_("Could not disable branch tracing for %s: %s"),
13350                target_pid_to_str (tinfo->ptid), rs->buf + 2);
13351       else
13352         error (_("Could not disable branch tracing for %s."),
13353                target_pid_to_str (tinfo->ptid));
13354     }
13355
13356   xfree (tinfo);
13357 }
13358
13359 /* Teardown branch tracing.  */
13360
13361 static void
13362 remote_teardown_btrace (struct target_ops *self,
13363                         struct btrace_target_info *tinfo)
13364 {
13365   /* We must not talk to the target during teardown.  */
13366   xfree (tinfo);
13367 }
13368
13369 /* Read the branch trace.  */
13370
13371 static enum btrace_error
13372 remote_read_btrace (struct target_ops *self,
13373                     struct btrace_data *btrace,
13374                     struct btrace_target_info *tinfo,
13375                     enum btrace_read_type type)
13376 {
13377   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13378   struct cleanup *cleanup;
13379   const char *annex;
13380   char *xml;
13381
13382   if (packet_config_support (packet) != PACKET_ENABLE)
13383     error (_("Target does not support branch tracing."));
13384
13385 #if !defined(HAVE_LIBEXPAT)
13386   error (_("Cannot process branch tracing result. XML parsing not supported."));
13387 #endif
13388
13389   switch (type)
13390     {
13391     case BTRACE_READ_ALL:
13392       annex = "all";
13393       break;
13394     case BTRACE_READ_NEW:
13395       annex = "new";
13396       break;
13397     case BTRACE_READ_DELTA:
13398       annex = "delta";
13399       break;
13400     default:
13401       internal_error (__FILE__, __LINE__,
13402                       _("Bad branch tracing read type: %u."),
13403                       (unsigned int) type);
13404     }
13405
13406   xml = target_read_stralloc (&current_target,
13407                               TARGET_OBJECT_BTRACE, annex);
13408   if (xml == NULL)
13409     return BTRACE_ERR_UNKNOWN;
13410
13411   cleanup = make_cleanup (xfree, xml);
13412   parse_xml_btrace (btrace, xml);
13413   do_cleanups (cleanup);
13414
13415   return BTRACE_ERR_NONE;
13416 }
13417
13418 static const struct btrace_config *
13419 remote_btrace_conf (struct target_ops *self,
13420                     const struct btrace_target_info *tinfo)
13421 {
13422   return &tinfo->conf;
13423 }
13424
13425 static int
13426 remote_augmented_libraries_svr4_read (struct target_ops *self)
13427 {
13428   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13429           == PACKET_ENABLE);
13430 }
13431
13432 /* Implementation of to_load.  */
13433
13434 static void
13435 remote_load (struct target_ops *self, const char *name, int from_tty)
13436 {
13437   generic_load (name, from_tty);
13438 }
13439
13440 /* Accepts an integer PID; returns a string representing a file that
13441    can be opened on the remote side to get the symbols for the child
13442    process.  Returns NULL if the operation is not supported.  */
13443
13444 static char *
13445 remote_pid_to_exec_file (struct target_ops *self, int pid)
13446 {
13447   static char *filename = NULL;
13448   struct inferior *inf;
13449   char *annex = NULL;
13450
13451   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13452     return NULL;
13453
13454   if (filename != NULL)
13455     xfree (filename);
13456
13457   inf = find_inferior_pid (pid);
13458   if (inf == NULL)
13459     internal_error (__FILE__, __LINE__,
13460                     _("not currently attached to process %d"), pid);
13461
13462   if (!inf->fake_pid_p)
13463     {
13464       const int annex_size = 9;
13465
13466       annex = (char *) alloca (annex_size);
13467       xsnprintf (annex, annex_size, "%x", pid);
13468     }
13469
13470   filename = target_read_stralloc (&current_target,
13471                                    TARGET_OBJECT_EXEC_FILE, annex);
13472
13473   return filename;
13474 }
13475
13476 /* Implement the to_can_do_single_step target_ops method.  */
13477
13478 static int
13479 remote_can_do_single_step (struct target_ops *ops)
13480 {
13481   /* We can only tell whether target supports single step or not by
13482      supported s and S vCont actions if the stub supports vContSupported
13483      feature.  If the stub doesn't support vContSupported feature,
13484      we have conservatively to think target doesn't supports single
13485      step.  */
13486   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13487     {
13488       struct remote_state *rs = get_remote_state ();
13489
13490       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13491         remote_vcont_probe (rs);
13492
13493       return rs->supports_vCont.s && rs->supports_vCont.S;
13494     }
13495   else
13496     return 0;
13497 }
13498
13499 /* Implementation of the to_execution_direction method for the remote
13500    target.  */
13501
13502 static enum exec_direction_kind
13503 remote_execution_direction (struct target_ops *self)
13504 {
13505   struct remote_state *rs = get_remote_state ();
13506
13507   return rs->last_resume_exec_dir;
13508 }
13509
13510 static void
13511 init_remote_ops (void)
13512 {
13513   remote_ops.to_shortname = "remote";
13514   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13515   remote_ops.to_doc =
13516     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13517 Specify the serial device it is connected to\n\
13518 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13519   remote_ops.to_open = remote_open;
13520   remote_ops.to_close = remote_close;
13521   remote_ops.to_detach = remote_detach;
13522   remote_ops.to_disconnect = remote_disconnect;
13523   remote_ops.to_resume = remote_resume;
13524   remote_ops.to_commit_resume = remote_commit_resume;
13525   remote_ops.to_wait = remote_wait;
13526   remote_ops.to_fetch_registers = remote_fetch_registers;
13527   remote_ops.to_store_registers = remote_store_registers;
13528   remote_ops.to_prepare_to_store = remote_prepare_to_store;
13529   remote_ops.to_files_info = remote_files_info;
13530   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13531   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13532   remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13533   remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13534   remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13535   remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13536   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13537   remote_ops.to_stopped_data_address = remote_stopped_data_address;
13538   remote_ops.to_watchpoint_addr_within_range =
13539     remote_watchpoint_addr_within_range;
13540   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13541   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13542   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13543   remote_ops.to_region_ok_for_hw_watchpoint
13544      = remote_region_ok_for_hw_watchpoint;
13545   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13546   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13547   remote_ops.to_kill = remote_kill;
13548   remote_ops.to_load = remote_load;
13549   remote_ops.to_mourn_inferior = remote_mourn;
13550   remote_ops.to_pass_signals = remote_pass_signals;
13551   remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13552   remote_ops.to_program_signals = remote_program_signals;
13553   remote_ops.to_thread_alive = remote_thread_alive;
13554   remote_ops.to_thread_name = remote_thread_name;
13555   remote_ops.to_update_thread_list = remote_update_thread_list;
13556   remote_ops.to_pid_to_str = remote_pid_to_str;
13557   remote_ops.to_extra_thread_info = remote_threads_extra_info;
13558   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13559   remote_ops.to_stop = remote_stop;
13560   remote_ops.to_interrupt = remote_interrupt;
13561   remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
13562   remote_ops.to_xfer_partial = remote_xfer_partial;
13563   remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
13564   remote_ops.to_rcmd = remote_rcmd;
13565   remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13566   remote_ops.to_log_command = serial_log_command;
13567   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13568   remote_ops.to_stratum = process_stratum;
13569   remote_ops.to_has_all_memory = default_child_has_all_memory;
13570   remote_ops.to_has_memory = default_child_has_memory;
13571   remote_ops.to_has_stack = default_child_has_stack;
13572   remote_ops.to_has_registers = default_child_has_registers;
13573   remote_ops.to_has_execution = default_child_has_execution;
13574   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
13575   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13576   remote_ops.to_magic = OPS_MAGIC;
13577   remote_ops.to_memory_map = remote_memory_map;
13578   remote_ops.to_flash_erase = remote_flash_erase;
13579   remote_ops.to_flash_done = remote_flash_done;
13580   remote_ops.to_read_description = remote_read_description;
13581   remote_ops.to_search_memory = remote_search_memory;
13582   remote_ops.to_can_async_p = remote_can_async_p;
13583   remote_ops.to_is_async_p = remote_is_async_p;
13584   remote_ops.to_async = remote_async;
13585   remote_ops.to_thread_events = remote_thread_events;
13586   remote_ops.to_can_do_single_step = remote_can_do_single_step;
13587   remote_ops.to_terminal_inferior = remote_terminal_inferior;
13588   remote_ops.to_terminal_ours = remote_terminal_ours;
13589   remote_ops.to_supports_non_stop = remote_supports_non_stop;
13590   remote_ops.to_supports_multi_process = remote_supports_multi_process;
13591   remote_ops.to_supports_disable_randomization
13592     = remote_supports_disable_randomization;
13593   remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13594   remote_ops.to_fileio_open = remote_hostio_open;
13595   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13596   remote_ops.to_fileio_pread = remote_hostio_pread;
13597   remote_ops.to_fileio_fstat = remote_hostio_fstat;
13598   remote_ops.to_fileio_close = remote_hostio_close;
13599   remote_ops.to_fileio_unlink = remote_hostio_unlink;
13600   remote_ops.to_fileio_readlink = remote_hostio_readlink;
13601   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13602   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13603   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13604   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13605   remote_ops.to_trace_init = remote_trace_init;
13606   remote_ops.to_download_tracepoint = remote_download_tracepoint;
13607   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13608   remote_ops.to_download_trace_state_variable
13609     = remote_download_trace_state_variable;
13610   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13611   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13612   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13613   remote_ops.to_trace_start = remote_trace_start;
13614   remote_ops.to_get_trace_status = remote_get_trace_status;
13615   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13616   remote_ops.to_trace_stop = remote_trace_stop;
13617   remote_ops.to_trace_find = remote_trace_find;
13618   remote_ops.to_get_trace_state_variable_value
13619     = remote_get_trace_state_variable_value;
13620   remote_ops.to_save_trace_data = remote_save_trace_data;
13621   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13622   remote_ops.to_upload_trace_state_variables
13623     = remote_upload_trace_state_variables;
13624   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13625   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13626   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13627   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13628   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13629   remote_ops.to_set_trace_notes = remote_set_trace_notes;
13630   remote_ops.to_core_of_thread = remote_core_of_thread;
13631   remote_ops.to_verify_memory = remote_verify_memory;
13632   remote_ops.to_get_tib_address = remote_get_tib_address;
13633   remote_ops.to_set_permissions = remote_set_permissions;
13634   remote_ops.to_static_tracepoint_marker_at
13635     = remote_static_tracepoint_marker_at;
13636   remote_ops.to_static_tracepoint_markers_by_strid
13637     = remote_static_tracepoint_markers_by_strid;
13638   remote_ops.to_traceframe_info = remote_traceframe_info;
13639   remote_ops.to_use_agent = remote_use_agent;
13640   remote_ops.to_can_use_agent = remote_can_use_agent;
13641   remote_ops.to_supports_btrace = remote_supports_btrace;
13642   remote_ops.to_enable_btrace = remote_enable_btrace;
13643   remote_ops.to_disable_btrace = remote_disable_btrace;
13644   remote_ops.to_teardown_btrace = remote_teardown_btrace;
13645   remote_ops.to_read_btrace = remote_read_btrace;
13646   remote_ops.to_btrace_conf = remote_btrace_conf;
13647   remote_ops.to_augmented_libraries_svr4_read =
13648     remote_augmented_libraries_svr4_read;
13649   remote_ops.to_follow_fork = remote_follow_fork;
13650   remote_ops.to_follow_exec = remote_follow_exec;
13651   remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13652   remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13653   remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13654   remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13655   remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13656   remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13657   remote_ops.to_execution_direction = remote_execution_direction;
13658 }
13659
13660 /* Set up the extended remote vector by making a copy of the standard
13661    remote vector and adding to it.  */
13662
13663 static void
13664 init_extended_remote_ops (void)
13665 {
13666   extended_remote_ops = remote_ops;
13667
13668   extended_remote_ops.to_shortname = "extended-remote";
13669   extended_remote_ops.to_longname =
13670     "Extended remote serial target in gdb-specific protocol";
13671   extended_remote_ops.to_doc =
13672     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13673 Specify the serial device it is connected to (e.g. /dev/ttya).";
13674   extended_remote_ops.to_open = extended_remote_open;
13675   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13676   extended_remote_ops.to_detach = extended_remote_detach;
13677   extended_remote_ops.to_attach = extended_remote_attach;
13678   extended_remote_ops.to_post_attach = extended_remote_post_attach;
13679   extended_remote_ops.to_supports_disable_randomization
13680     = extended_remote_supports_disable_randomization;
13681 }
13682
13683 static int
13684 remote_can_async_p (struct target_ops *ops)
13685 {
13686   struct remote_state *rs = get_remote_state ();
13687
13688   if (!target_async_permitted)
13689     /* We only enable async when the user specifically asks for it.  */
13690     return 0;
13691
13692   /* We're async whenever the serial device is.  */
13693   return serial_can_async_p (rs->remote_desc);
13694 }
13695
13696 static int
13697 remote_is_async_p (struct target_ops *ops)
13698 {
13699   struct remote_state *rs = get_remote_state ();
13700
13701   if (!target_async_permitted)
13702     /* We only enable async when the user specifically asks for it.  */
13703     return 0;
13704
13705   /* We're async whenever the serial device is.  */
13706   return serial_is_async_p (rs->remote_desc);
13707 }
13708
13709 /* Pass the SERIAL event on and up to the client.  One day this code
13710    will be able to delay notifying the client of an event until the
13711    point where an entire packet has been received.  */
13712
13713 static serial_event_ftype remote_async_serial_handler;
13714
13715 static void
13716 remote_async_serial_handler (struct serial *scb, void *context)
13717 {
13718   /* Don't propogate error information up to the client.  Instead let
13719      the client find out about the error by querying the target.  */
13720   inferior_event_handler (INF_REG_EVENT, NULL);
13721 }
13722
13723 static void
13724 remote_async_inferior_event_handler (gdb_client_data data)
13725 {
13726   inferior_event_handler (INF_REG_EVENT, NULL);
13727 }
13728
13729 static void
13730 remote_async (struct target_ops *ops, int enable)
13731 {
13732   struct remote_state *rs = get_remote_state ();
13733
13734   if (enable)
13735     {
13736       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13737
13738       /* If there are pending events in the stop reply queue tell the
13739          event loop to process them.  */
13740       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13741         mark_async_event_handler (remote_async_inferior_event_token);
13742       /* For simplicity, below we clear the pending events token
13743          without remembering whether it is marked, so here we always
13744          mark it.  If there's actually no pending notification to
13745          process, this ends up being a no-op (other than a spurious
13746          event-loop wakeup).  */
13747       if (target_is_non_stop_p ())
13748         mark_async_event_handler (rs->notif_state->get_pending_events_token);
13749     }
13750   else
13751     {
13752       serial_async (rs->remote_desc, NULL, NULL);
13753       /* If the core is disabling async, it doesn't want to be
13754          disturbed with target events.  Clear all async event sources
13755          too.  */
13756       clear_async_event_handler (remote_async_inferior_event_token);
13757       if (target_is_non_stop_p ())
13758         clear_async_event_handler (rs->notif_state->get_pending_events_token);
13759     }
13760 }
13761
13762 /* Implementation of the to_thread_events method.  */
13763
13764 static void
13765 remote_thread_events (struct target_ops *ops, int enable)
13766 {
13767   struct remote_state *rs = get_remote_state ();
13768   size_t size = get_remote_packet_size ();
13769
13770   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13771     return;
13772
13773   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13774   putpkt (rs->buf);
13775   getpkt (&rs->buf, &rs->buf_size, 0);
13776
13777   switch (packet_ok (rs->buf,
13778                      &remote_protocol_packets[PACKET_QThreadEvents]))
13779     {
13780     case PACKET_OK:
13781       if (strcmp (rs->buf, "OK") != 0)
13782         error (_("Remote refused setting thread events: %s"), rs->buf);
13783       break;
13784     case PACKET_ERROR:
13785       warning (_("Remote failure reply: %s"), rs->buf);
13786       break;
13787     case PACKET_UNKNOWN:
13788       break;
13789     }
13790 }
13791
13792 static void
13793 set_remote_cmd (char *args, int from_tty)
13794 {
13795   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13796 }
13797
13798 static void
13799 show_remote_cmd (char *args, int from_tty)
13800 {
13801   /* We can't just use cmd_show_list here, because we want to skip
13802      the redundant "show remote Z-packet" and the legacy aliases.  */
13803   struct cleanup *showlist_chain;
13804   struct cmd_list_element *list = remote_show_cmdlist;
13805   struct ui_out *uiout = current_uiout;
13806
13807   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13808   for (; list != NULL; list = list->next)
13809     if (strcmp (list->name, "Z-packet") == 0)
13810       continue;
13811     else if (list->type == not_set_cmd)
13812       /* Alias commands are exactly like the original, except they
13813          don't have the normal type.  */
13814       continue;
13815     else
13816       {
13817         struct cleanup *option_chain
13818           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13819
13820         ui_out_field_string (uiout, "name", list->name);
13821         ui_out_text (uiout, ":  ");
13822         if (list->type == show_cmd)
13823           do_show_command (NULL, from_tty, list);
13824         else
13825           cmd_func (list, NULL, from_tty);
13826         /* Close the tuple.  */
13827         do_cleanups (option_chain);
13828       }
13829
13830   /* Close the tuple.  */
13831   do_cleanups (showlist_chain);
13832 }
13833
13834
13835 /* Function to be called whenever a new objfile (shlib) is detected.  */
13836 static void
13837 remote_new_objfile (struct objfile *objfile)
13838 {
13839   struct remote_state *rs = get_remote_state ();
13840
13841   if (rs->remote_desc != 0)             /* Have a remote connection.  */
13842     remote_check_symbols ();
13843 }
13844
13845 /* Pull all the tracepoints defined on the target and create local
13846    data structures representing them.  We don't want to create real
13847    tracepoints yet, we don't want to mess up the user's existing
13848    collection.  */
13849   
13850 static int
13851 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13852 {
13853   struct remote_state *rs = get_remote_state ();
13854   char *p;
13855
13856   /* Ask for a first packet of tracepoint definition.  */
13857   putpkt ("qTfP");
13858   getpkt (&rs->buf, &rs->buf_size, 0);
13859   p = rs->buf;
13860   while (*p && *p != 'l')
13861     {
13862       parse_tracepoint_definition (p, utpp);
13863       /* Ask for another packet of tracepoint definition.  */
13864       putpkt ("qTsP");
13865       getpkt (&rs->buf, &rs->buf_size, 0);
13866       p = rs->buf;
13867     }
13868   return 0;
13869 }
13870
13871 static int
13872 remote_upload_trace_state_variables (struct target_ops *self,
13873                                      struct uploaded_tsv **utsvp)
13874 {
13875   struct remote_state *rs = get_remote_state ();
13876   char *p;
13877
13878   /* Ask for a first packet of variable definition.  */
13879   putpkt ("qTfV");
13880   getpkt (&rs->buf, &rs->buf_size, 0);
13881   p = rs->buf;
13882   while (*p && *p != 'l')
13883     {
13884       parse_tsv_definition (p, utsvp);
13885       /* Ask for another packet of variable definition.  */
13886       putpkt ("qTsV");
13887       getpkt (&rs->buf, &rs->buf_size, 0);
13888       p = rs->buf;
13889     }
13890   return 0;
13891 }
13892
13893 /* The "set/show range-stepping" show hook.  */
13894
13895 static void
13896 show_range_stepping (struct ui_file *file, int from_tty,
13897                      struct cmd_list_element *c,
13898                      const char *value)
13899 {
13900   fprintf_filtered (file,
13901                     _("Debugger's willingness to use range stepping "
13902                       "is %s.\n"), value);
13903 }
13904
13905 /* The "set/show range-stepping" set hook.  */
13906
13907 static void
13908 set_range_stepping (char *ignore_args, int from_tty,
13909                     struct cmd_list_element *c)
13910 {
13911   struct remote_state *rs = get_remote_state ();
13912
13913   /* Whene enabling, check whether range stepping is actually
13914      supported by the target, and warn if not.  */
13915   if (use_range_stepping)
13916     {
13917       if (rs->remote_desc != NULL)
13918         {
13919           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13920             remote_vcont_probe (rs);
13921
13922           if (packet_support (PACKET_vCont) == PACKET_ENABLE
13923               && rs->supports_vCont.r)
13924             return;
13925         }
13926
13927       warning (_("Range stepping is not supported by the current target"));
13928     }
13929 }
13930
13931 void
13932 _initialize_remote (void)
13933 {
13934   struct cmd_list_element *cmd;
13935   const char *cmd_name;
13936
13937   /* architecture specific data */
13938   remote_gdbarch_data_handle =
13939     gdbarch_data_register_post_init (init_remote_state);
13940   remote_g_packet_data_handle =
13941     gdbarch_data_register_pre_init (remote_g_packet_data_init);
13942
13943   remote_pspace_data
13944     = register_program_space_data_with_cleanup (NULL,
13945                                                 remote_pspace_data_cleanup);
13946
13947   /* Initialize the per-target state.  At the moment there is only one
13948      of these, not one per target.  Only one target is active at a
13949      time.  */
13950   remote_state = new_remote_state ();
13951
13952   init_remote_ops ();
13953   add_target (&remote_ops);
13954
13955   init_extended_remote_ops ();
13956   add_target (&extended_remote_ops);
13957
13958   /* Hook into new objfile notification.  */
13959   observer_attach_new_objfile (remote_new_objfile);
13960   /* We're no longer interested in notification events of an inferior
13961      when it exits.  */
13962   observer_attach_inferior_exit (discard_pending_stop_replies);
13963
13964 #if 0
13965   init_remote_threadtests ();
13966 #endif
13967
13968   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13969   /* set/show remote ...  */
13970
13971   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13972 Remote protocol specific variables\n\
13973 Configure various remote-protocol specific variables such as\n\
13974 the packets being used"),
13975                   &remote_set_cmdlist, "set remote ",
13976                   0 /* allow-unknown */, &setlist);
13977   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13978 Remote protocol specific variables\n\
13979 Configure various remote-protocol specific variables such as\n\
13980 the packets being used"),
13981                   &remote_show_cmdlist, "show remote ",
13982                   0 /* allow-unknown */, &showlist);
13983
13984   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13985 Compare section data on target to the exec file.\n\
13986 Argument is a single section name (default: all loaded sections).\n\
13987 To compare only read-only loaded sections, specify the -r option."),
13988            &cmdlist);
13989
13990   add_cmd ("packet", class_maintenance, packet_command, _("\
13991 Send an arbitrary packet to a remote target.\n\
13992    maintenance packet TEXT\n\
13993 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13994 this command sends the string TEXT to the inferior, and displays the\n\
13995 response packet.  GDB supplies the initial `$' character, and the\n\
13996 terminating `#' character and checksum."),
13997            &maintenancelist);
13998
13999   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14000 Set whether to send break if interrupted."), _("\
14001 Show whether to send break if interrupted."), _("\
14002 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14003                            set_remotebreak, show_remotebreak,
14004                            &setlist, &showlist);
14005   cmd_name = "remotebreak";
14006   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14007   deprecate_cmd (cmd, "set remote interrupt-sequence");
14008   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14009   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14010   deprecate_cmd (cmd, "show remote interrupt-sequence");
14011
14012   add_setshow_enum_cmd ("interrupt-sequence", class_support,
14013                         interrupt_sequence_modes, &interrupt_sequence_mode,
14014                         _("\
14015 Set interrupt sequence to remote target."), _("\
14016 Show interrupt sequence to remote target."), _("\
14017 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14018                         NULL, show_interrupt_sequence,
14019                         &remote_set_cmdlist,
14020                         &remote_show_cmdlist);
14021
14022   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14023                            &interrupt_on_connect, _("\
14024 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
14025 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
14026 If set, interrupt sequence is sent to remote target."),
14027                            NULL, NULL,
14028                            &remote_set_cmdlist, &remote_show_cmdlist);
14029
14030   /* Install commands for configuring memory read/write packets.  */
14031
14032   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14033 Set the maximum number of bytes per memory write packet (deprecated)."),
14034            &setlist);
14035   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14036 Show the maximum number of bytes per memory write packet (deprecated)."),
14037            &showlist);
14038   add_cmd ("memory-write-packet-size", no_class,
14039            set_memory_write_packet_size, _("\
14040 Set the maximum number of bytes per memory-write packet.\n\
14041 Specify the number of bytes in a packet or 0 (zero) for the\n\
14042 default packet size.  The actual limit is further reduced\n\
14043 dependent on the target.  Specify ``fixed'' to disable the\n\
14044 further restriction and ``limit'' to enable that restriction."),
14045            &remote_set_cmdlist);
14046   add_cmd ("memory-read-packet-size", no_class,
14047            set_memory_read_packet_size, _("\
14048 Set the maximum number of bytes per memory-read packet.\n\
14049 Specify the number of bytes in a packet or 0 (zero) for the\n\
14050 default packet size.  The actual limit is further reduced\n\
14051 dependent on the target.  Specify ``fixed'' to disable the\n\
14052 further restriction and ``limit'' to enable that restriction."),
14053            &remote_set_cmdlist);
14054   add_cmd ("memory-write-packet-size", no_class,
14055            show_memory_write_packet_size,
14056            _("Show the maximum number of bytes per memory-write packet."),
14057            &remote_show_cmdlist);
14058   add_cmd ("memory-read-packet-size", no_class,
14059            show_memory_read_packet_size,
14060            _("Show the maximum number of bytes per memory-read packet."),
14061            &remote_show_cmdlist);
14062
14063   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14064                             &remote_hw_watchpoint_limit, _("\
14065 Set the maximum number of target hardware watchpoints."), _("\
14066 Show the maximum number of target hardware watchpoints."), _("\
14067 Specify a negative limit for unlimited."),
14068                             NULL, NULL, /* FIXME: i18n: The maximum
14069                                            number of target hardware
14070                                            watchpoints is %s.  */
14071                             &remote_set_cmdlist, &remote_show_cmdlist);
14072   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14073                             &remote_hw_watchpoint_length_limit, _("\
14074 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14075 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14076 Specify a negative limit for unlimited."),
14077                             NULL, NULL, /* FIXME: i18n: The maximum
14078                                            length (in bytes) of a target
14079                                            hardware watchpoint is %s.  */
14080                             &remote_set_cmdlist, &remote_show_cmdlist);
14081   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14082                             &remote_hw_breakpoint_limit, _("\
14083 Set the maximum number of target hardware breakpoints."), _("\
14084 Show the maximum number of target hardware breakpoints."), _("\
14085 Specify a negative limit for unlimited."),
14086                             NULL, NULL, /* FIXME: i18n: The maximum
14087                                            number of target hardware
14088                                            breakpoints is %s.  */
14089                             &remote_set_cmdlist, &remote_show_cmdlist);
14090
14091   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14092                              &remote_address_size, _("\
14093 Set the maximum size of the address (in bits) in a memory packet."), _("\
14094 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14095                              NULL,
14096                              NULL, /* FIXME: i18n: */
14097                              &setlist, &showlist);
14098
14099   init_all_packet_configs ();
14100
14101   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14102                          "X", "binary-download", 1);
14103
14104   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14105                          "vCont", "verbose-resume", 0);
14106
14107   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14108                          "QPassSignals", "pass-signals", 0);
14109
14110   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14111                          "QCatchSyscalls", "catch-syscalls", 0);
14112
14113   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14114                          "QProgramSignals", "program-signals", 0);
14115
14116   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14117                          "qSymbol", "symbol-lookup", 0);
14118
14119   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14120                          "P", "set-register", 1);
14121
14122   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14123                          "p", "fetch-register", 1);
14124
14125   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14126                          "Z0", "software-breakpoint", 0);
14127
14128   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14129                          "Z1", "hardware-breakpoint", 0);
14130
14131   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14132                          "Z2", "write-watchpoint", 0);
14133
14134   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14135                          "Z3", "read-watchpoint", 0);
14136
14137   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14138                          "Z4", "access-watchpoint", 0);
14139
14140   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14141                          "qXfer:auxv:read", "read-aux-vector", 0);
14142
14143   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14144                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
14145
14146   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14147                          "qXfer:features:read", "target-features", 0);
14148
14149   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14150                          "qXfer:libraries:read", "library-info", 0);
14151
14152   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14153                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14154
14155   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14156                          "qXfer:memory-map:read", "memory-map", 0);
14157
14158   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14159                          "qXfer:spu:read", "read-spu-object", 0);
14160
14161   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14162                          "qXfer:spu:write", "write-spu-object", 0);
14163
14164   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14165                         "qXfer:osdata:read", "osdata", 0);
14166
14167   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14168                          "qXfer:threads:read", "threads", 0);
14169
14170   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14171                          "qXfer:siginfo:read", "read-siginfo-object", 0);
14172
14173   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14174                          "qXfer:siginfo:write", "write-siginfo-object", 0);
14175
14176   add_packet_config_cmd
14177     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14178      "qXfer:traceframe-info:read", "traceframe-info", 0);
14179
14180   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14181                          "qXfer:uib:read", "unwind-info-block", 0);
14182
14183   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14184                          "qGetTLSAddr", "get-thread-local-storage-address",
14185                          0);
14186
14187   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14188                          "qGetTIBAddr", "get-thread-information-block-address",
14189                          0);
14190
14191   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14192                          "bc", "reverse-continue", 0);
14193
14194   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14195                          "bs", "reverse-step", 0);
14196
14197   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14198                          "qSupported", "supported-packets", 0);
14199
14200   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14201                          "qSearch:memory", "search-memory", 0);
14202
14203   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14204                          "qTStatus", "trace-status", 0);
14205
14206   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14207                          "vFile:setfs", "hostio-setfs", 0);
14208
14209   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14210                          "vFile:open", "hostio-open", 0);
14211
14212   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14213                          "vFile:pread", "hostio-pread", 0);
14214
14215   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14216                          "vFile:pwrite", "hostio-pwrite", 0);
14217
14218   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14219                          "vFile:close", "hostio-close", 0);
14220
14221   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14222                          "vFile:unlink", "hostio-unlink", 0);
14223
14224   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14225                          "vFile:readlink", "hostio-readlink", 0);
14226
14227   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14228                          "vFile:fstat", "hostio-fstat", 0);
14229
14230   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14231                          "vAttach", "attach", 0);
14232
14233   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14234                          "vRun", "run", 0);
14235
14236   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14237                          "QStartNoAckMode", "noack", 0);
14238
14239   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14240                          "vKill", "kill", 0);
14241
14242   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14243                          "qAttached", "query-attached", 0);
14244
14245   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14246                          "ConditionalTracepoints",
14247                          "conditional-tracepoints", 0);
14248
14249   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14250                          "ConditionalBreakpoints",
14251                          "conditional-breakpoints", 0);
14252
14253   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14254                          "BreakpointCommands",
14255                          "breakpoint-commands", 0);
14256
14257   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14258                          "FastTracepoints", "fast-tracepoints", 0);
14259
14260   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14261                          "TracepointSource", "TracepointSource", 0);
14262
14263   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14264                          "QAllow", "allow", 0);
14265
14266   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14267                          "StaticTracepoints", "static-tracepoints", 0);
14268
14269   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14270                          "InstallInTrace", "install-in-trace", 0);
14271
14272   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14273                          "qXfer:statictrace:read", "read-sdata-object", 0);
14274
14275   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14276                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14277
14278   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14279                          "QDisableRandomization", "disable-randomization", 0);
14280
14281   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14282                          "QAgent", "agent", 0);
14283
14284   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14285                          "QTBuffer:size", "trace-buffer-size", 0);
14286
14287   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14288        "Qbtrace:off", "disable-btrace", 0);
14289
14290   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14291        "Qbtrace:bts", "enable-btrace-bts", 0);
14292
14293   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14294        "Qbtrace:pt", "enable-btrace-pt", 0);
14295
14296   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14297        "qXfer:btrace", "read-btrace", 0);
14298
14299   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14300        "qXfer:btrace-conf", "read-btrace-conf", 0);
14301
14302   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14303        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14304
14305   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14306        "multiprocess-feature", "multiprocess-feature", 0);
14307
14308   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14309                          "swbreak-feature", "swbreak-feature", 0);
14310
14311   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14312                          "hwbreak-feature", "hwbreak-feature", 0);
14313
14314   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14315                          "fork-event-feature", "fork-event-feature", 0);
14316
14317   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14318                          "vfork-event-feature", "vfork-event-feature", 0);
14319
14320   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14321        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14322
14323   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14324                          "vContSupported", "verbose-resume-supported", 0);
14325
14326   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14327                          "exec-event-feature", "exec-event-feature", 0);
14328
14329   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14330                          "vCtrlC", "ctrl-c", 0);
14331
14332   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14333                          "QThreadEvents", "thread-events", 0);
14334
14335   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14336                          "N stop reply", "no-resumed-stop-reply", 0);
14337
14338   /* Assert that we've registered "set remote foo-packet" commands
14339      for all packet configs.  */
14340   {
14341     int i;
14342
14343     for (i = 0; i < PACKET_MAX; i++)
14344       {
14345         /* Ideally all configs would have a command associated.  Some
14346            still don't though.  */
14347         int excepted;
14348
14349         switch (i)
14350           {
14351           case PACKET_QNonStop:
14352           case PACKET_EnableDisableTracepoints_feature:
14353           case PACKET_tracenz_feature:
14354           case PACKET_DisconnectedTracing_feature:
14355           case PACKET_augmented_libraries_svr4_read_feature:
14356           case PACKET_qCRC:
14357             /* Additions to this list need to be well justified:
14358                pre-existing packets are OK; new packets are not.  */
14359             excepted = 1;
14360             break;
14361           default:
14362             excepted = 0;
14363             break;
14364           }
14365
14366         /* This catches both forgetting to add a config command, and
14367            forgetting to remove a packet from the exception list.  */
14368         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14369       }
14370   }
14371
14372   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
14373      Z sub-packet has its own set and show commands, but users may
14374      have sets to this variable in their .gdbinit files (or in their
14375      documentation).  */
14376   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14377                                 &remote_Z_packet_detect, _("\
14378 Set use of remote protocol `Z' packets"), _("\
14379 Show use of remote protocol `Z' packets "), _("\
14380 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14381 packets."),
14382                                 set_remote_protocol_Z_packet_cmd,
14383                                 show_remote_protocol_Z_packet_cmd,
14384                                 /* FIXME: i18n: Use of remote protocol
14385                                    `Z' packets is %s.  */
14386                                 &remote_set_cmdlist, &remote_show_cmdlist);
14387
14388   add_prefix_cmd ("remote", class_files, remote_command, _("\
14389 Manipulate files on the remote system\n\
14390 Transfer files to and from the remote target system."),
14391                   &remote_cmdlist, "remote ",
14392                   0 /* allow-unknown */, &cmdlist);
14393
14394   add_cmd ("put", class_files, remote_put_command,
14395            _("Copy a local file to the remote system."),
14396            &remote_cmdlist);
14397
14398   add_cmd ("get", class_files, remote_get_command,
14399            _("Copy a remote file to the local system."),
14400            &remote_cmdlist);
14401
14402   add_cmd ("delete", class_files, remote_delete_command,
14403            _("Delete a remote file."),
14404            &remote_cmdlist);
14405
14406   add_setshow_string_noescape_cmd ("exec-file", class_files,
14407                                    &remote_exec_file_var, _("\
14408 Set the remote pathname for \"run\""), _("\
14409 Show the remote pathname for \"run\""), NULL,
14410                                    set_remote_exec_file,
14411                                    show_remote_exec_file,
14412                                    &remote_set_cmdlist,
14413                                    &remote_show_cmdlist);
14414
14415   add_setshow_boolean_cmd ("range-stepping", class_run,
14416                            &use_range_stepping, _("\
14417 Enable or disable range stepping."), _("\
14418 Show whether target-assisted range stepping is enabled."), _("\
14419 If on, and the target supports it, when stepping a source line, GDB\n\
14420 tells the target to step the corresponding range of addresses itself instead\n\
14421 of issuing multiple single-steps.  This speeds up source level\n\
14422 stepping.  If off, GDB always issues single-steps, even if range\n\
14423 stepping is supported by the target.  The default is on."),
14424                            set_range_stepping,
14425                            show_range_stepping,
14426                            &setlist,
14427                            &showlist);
14428
14429   /* Eventually initialize fileio.  See fileio.c */
14430   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14431
14432   /* Take advantage of the fact that the TID field is not used, to tag
14433      special ptids with it set to != 0.  */
14434   magic_null_ptid = ptid_build (42000, -1, 1);
14435   not_sent_ptid = ptid_build (42000, -2, 1);
14436   any_thread_ptid = ptid_build (42000, 0, 1);
14437
14438   target_buf_size = 2048;
14439   target_buf = (char *) xmalloc (target_buf_size);
14440 }
14441