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