528d863762cc5720fc682ca2aba5a97824622631
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2016 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* See the GDB User Guide for details of the GDB remote protocol.  */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 /*#include "terminal.h" */
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observer.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "filestuff.h"
46 #include "rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdb_sys_time.h"
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "agent.h"
72 #include "btrace.h"
73
74 /* Temp hacks for tracepoint encoding migration.  */
75 static char *target_buf;
76 static long target_buf_size;
77
78 /* Per-program-space data key.  */
79 static const struct program_space_data *remote_pspace_data;
80
81 /* The variable registered as the control variable used by the
82    remote exec-file commands.  While the remote exec-file setting is
83    per-program-space, the set/show machinery uses this as the 
84    location of the remote exec-file value.  */
85 static char *remote_exec_file_var;
86
87 /* The size to align memory write packets, when practical.  The protocol
88    does not guarantee any alignment, and gdb will generate short
89    writes and unaligned writes, but even as a best-effort attempt this
90    can improve bulk transfers.  For instance, if a write is misaligned
91    relative to the target's data bus, the stub may need to make an extra
92    round trip fetching data from the target.  This doesn't make a
93    huge difference, but it's easy to do, so we try to be helpful.
94
95    The alignment chosen is arbitrary; usually data bus width is
96    important here, not the possibly larger cache line size.  */
97 enum { REMOTE_ALIGN_WRITES = 16 };
98
99 /* Prototypes for local functions.  */
100 static void async_cleanup_sigint_signal_handler (void *dummy);
101 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
102 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
103                                  int forever, int *is_notif);
104
105 static void async_handle_remote_sigint (int);
106 static void async_handle_remote_sigint_twice (int);
107
108 static void remote_files_info (struct target_ops *ignore);
109
110 static void remote_prepare_to_store (struct target_ops *self,
111                                      struct regcache *regcache);
112
113 static void remote_open_1 (const char *, int, struct target_ops *,
114                            int extended_p);
115
116 static void remote_close (struct target_ops *self);
117
118 struct remote_state;
119
120 static int remote_vkill (int pid, struct remote_state *rs);
121
122 static void remote_kill_k (void);
123
124 static void remote_mourn (struct target_ops *ops);
125
126 static void extended_remote_restart (void);
127
128 static void remote_send (char **buf, long *sizeof_buf_p);
129
130 static int readchar (int timeout);
131
132 static void remote_serial_write (const char *str, int len);
133
134 static void remote_kill (struct target_ops *ops);
135
136 static int remote_can_async_p (struct target_ops *);
137
138 static int remote_is_async_p (struct target_ops *);
139
140 static void remote_async (struct target_ops *ops, int enable);
141
142 static void remote_thread_events (struct target_ops *ops, int enable);
143
144 static void sync_remote_interrupt_twice (int signo);
145
146 static void interrupt_query (void);
147
148 static void set_general_thread (struct ptid ptid);
149 static void set_continue_thread (struct ptid ptid);
150
151 static void get_offsets (void);
152
153 static void skip_frame (void);
154
155 static long read_frame (char **buf_p, long *sizeof_buf);
156
157 static int hexnumlen (ULONGEST num);
158
159 static void init_remote_ops (void);
160
161 static void init_extended_remote_ops (void);
162
163 static void remote_stop (struct target_ops *self, ptid_t);
164
165 static int stubhex (int ch);
166
167 static int hexnumstr (char *, ULONGEST);
168
169 static int hexnumnstr (char *, ULONGEST, int);
170
171 static CORE_ADDR remote_address_masked (CORE_ADDR);
172
173 static void print_packet (const char *);
174
175 static void compare_sections_command (char *, int);
176
177 static void packet_command (char *, int);
178
179 static int stub_unpack_int (char *buff, int fieldlength);
180
181 static ptid_t remote_current_thread (ptid_t oldptid);
182
183 static int putpkt_binary (const char *buf, int cnt);
184
185 static void check_binary_download (CORE_ADDR addr);
186
187 struct packet_config;
188
189 static void show_packet_config_cmd (struct packet_config *config);
190
191 static void show_remote_protocol_packet_cmd (struct ui_file *file,
192                                              int from_tty,
193                                              struct cmd_list_element *c,
194                                              const char *value);
195
196 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
197 static ptid_t read_ptid (char *buf, char **obuf);
198
199 static void remote_set_permissions (struct target_ops *self);
200
201 static int remote_get_trace_status (struct target_ops *self,
202                                     struct trace_status *ts);
203
204 static int remote_upload_tracepoints (struct target_ops *self,
205                                       struct uploaded_tp **utpp);
206
207 static int remote_upload_trace_state_variables (struct target_ops *self,
208                                                 struct uploaded_tsv **utsvp);
209   
210 static void remote_query_supported (void);
211
212 static void remote_check_symbols (void);
213
214 void _initialize_remote (void);
215
216 struct stop_reply;
217 static void stop_reply_xfree (struct stop_reply *);
218 static void remote_parse_stop_reply (char *, struct stop_reply *);
219 static void push_stop_reply (struct stop_reply *);
220 static void discard_pending_stop_replies_in_queue (struct remote_state *);
221 static int peek_stop_reply (ptid_t ptid);
222
223 struct threads_listing_context;
224 static void remove_new_fork_children (struct threads_listing_context *);
225
226 static void remote_async_inferior_event_handler (gdb_client_data);
227
228 static void remote_terminal_ours (struct target_ops *self);
229
230 static int remote_read_description_p (struct target_ops *target);
231
232 static void remote_console_output (char *msg);
233
234 static int remote_supports_cond_breakpoints (struct target_ops *self);
235
236 static int remote_can_run_breakpoint_commands (struct target_ops *self);
237
238 static void remote_btrace_reset (void);
239
240 static int stop_reply_queue_length (void);
241
242 static void readahead_cache_invalidate (void);
243
244 /* For "remote".  */
245
246 static struct cmd_list_element *remote_cmdlist;
247
248 /* For "set remote" and "show remote".  */
249
250 static struct cmd_list_element *remote_set_cmdlist;
251 static struct cmd_list_element *remote_show_cmdlist;
252
253 /* Stub vCont actions support.
254
255    Each field is a boolean flag indicating whether the stub reports
256    support for the corresponding action.  */
257
258 struct vCont_action_support
259 {
260   /* vCont;t */
261   int t;
262
263   /* vCont;r */
264   int r;
265
266   /* vCont;s */
267   int s;
268
269   /* vCont;S */
270   int S;
271 };
272
273 /* Controls whether GDB is willing to use range stepping.  */
274
275 static int use_range_stepping = 1;
276
277 #define OPAQUETHREADBYTES 8
278
279 /* a 64 bit opaque identifier */
280 typedef unsigned char threadref[OPAQUETHREADBYTES];
281
282 /* About this many threadisds fit in a packet.  */
283
284 #define MAXTHREADLISTRESULTS 32
285
286 /* Data for the vFile:pread readahead cache.  */
287
288 struct readahead_cache
289 {
290   /* The file descriptor for the file that is being cached.  -1 if the
291      cache is invalid.  */
292   int fd;
293
294   /* The offset into the file that the cache buffer corresponds
295      to.  */
296   ULONGEST offset;
297
298   /* The buffer holding the cache contents.  */
299   gdb_byte *buf;
300   /* The buffer's size.  We try to read as much as fits into a packet
301      at a time.  */
302   size_t bufsize;
303
304   /* Cache hit and miss counters.  */
305   ULONGEST hit_count;
306   ULONGEST miss_count;
307 };
308
309 /* Description of the remote protocol state for the currently
310    connected target.  This is per-target state, and independent of the
311    selected architecture.  */
312
313 struct remote_state
314 {
315   /* A buffer to use for incoming packets, and its current size.  The
316      buffer is grown dynamically for larger incoming packets.
317      Outgoing packets may also be constructed in this buffer.
318      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
320      packets.  */
321   char *buf;
322   long buf_size;
323
324   /* True if we're going through initial connection setup (finding out
325      about the remote side's threads, relocating symbols, etc.).  */
326   int starting_up;
327
328   /* If we negotiated packet size explicitly (and thus can bypass
329      heuristics for the largest packet size that will not overflow
330      a buffer in the stub), this will be set to that packet size.
331      Otherwise zero, meaning to use the guessed size.  */
332   long explicit_packet_size;
333
334   /* remote_wait is normally called when the target is running and
335      waits for a stop reply packet.  But sometimes we need to call it
336      when the target is already stopped.  We can send a "?" packet
337      and have remote_wait read the response.  Or, if we already have
338      the response, we can stash it in BUF and tell remote_wait to
339      skip calling getpkt.  This flag is set when BUF contains a
340      stop reply packet and the target is not waiting.  */
341   int cached_wait_status;
342
343   /* True, if in no ack mode.  That is, neither GDB nor the stub will
344      expect acks from each other.  The connection is assumed to be
345      reliable.  */
346   int noack_mode;
347
348   /* True if we're connected in extended remote mode.  */
349   int extended;
350
351   /* True if we resumed the target and we're waiting for the target to
352      stop.  In the mean time, we can't start another command/query.
353      The remote server wouldn't be ready to process it, so we'd
354      timeout waiting for a reply that would never come and eventually
355      we'd close the connection.  This can happen in asynchronous mode
356      because we allow GDB commands while the target is running.  */
357   int waiting_for_stop_reply;
358
359   /* The status of the stub support for the various vCont actions.  */
360   struct vCont_action_support supports_vCont;
361
362   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363      responded to that.  */
364   int ctrlc_pending_p;
365
366   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
367      remote_open knows that we don't have a file open when the program
368      starts.  */
369   struct serial *remote_desc;
370
371   /* These are the threads which we last sent to the remote system.  The
372      TID member will be -1 for all or -2 for not sent yet.  */
373   ptid_t general_thread;
374   ptid_t continue_thread;
375
376   /* This is the traceframe which we last selected on the remote system.
377      It will be -1 if no traceframe is selected.  */
378   int remote_traceframe_number;
379
380   char *last_pass_packet;
381
382   /* The last QProgramSignals packet sent to the target.  We bypass
383      sending a new program signals list down to the target if the new
384      packet is exactly the same as the last we sent.  IOW, we only let
385      the target know about program signals list changes.  */
386   char *last_program_signals_packet;
387
388   enum gdb_signal last_sent_signal;
389
390   int last_sent_step;
391
392   char *finished_object;
393   char *finished_annex;
394   ULONGEST finished_offset;
395
396   /* Should we try the 'ThreadInfo' query packet?
397
398      This variable (NOT available to the user: auto-detect only!)
399      determines whether GDB will use the new, simpler "ThreadInfo"
400      query or the older, more complex syntax for thread queries.
401      This is an auto-detect variable (set to true at each connect,
402      and set to false when the target fails to recognize it).  */
403   int use_threadinfo_query;
404   int use_threadextra_query;
405
406   threadref echo_nextthread;
407   threadref nextthread;
408   threadref resultthreadlist[MAXTHREADLISTRESULTS];
409
410   /* The state of remote notification.  */
411   struct remote_notif_state *notif_state;
412
413   /* The branch trace configuration.  */
414   struct btrace_config btrace_config;
415
416   /* The argument to the last "vFile:setfs:" packet we sent, used
417      to avoid sending repeated unnecessary "vFile:setfs:" packets.
418      Initialized to -1 to indicate that no "vFile:setfs:" packet
419      has yet been sent.  */
420   int fs_pid;
421
422   /* A readahead cache for vFile:pread.  Often, reading a binary
423      involves a sequence of small reads.  E.g., when parsing an ELF
424      file.  A readahead cache helps mostly the case of remote
425      debugging on a connection with higher latency, due to the
426      request/reply nature of the RSP.  We only cache data for a single
427      file descriptor at a time.  */
428   struct readahead_cache readahead_cache;
429 };
430
431 /* Private data that we'll store in (struct thread_info)->private.  */
432 struct private_thread_info
433 {
434   char *extra;
435   char *name;
436   int core;
437
438   /* Whether the target stopped for a breakpoint/watchpoint.  */
439   enum target_stop_reason stop_reason;
440
441   /* This is set to the data address of the access causing the target
442      to stop for a watchpoint.  */
443   CORE_ADDR watch_data_address;
444 };
445
446 static void
447 free_private_thread_info (struct private_thread_info *info)
448 {
449   xfree (info->extra);
450   xfree (info->name);
451   xfree (info);
452 }
453
454 /* This data could be associated with a target, but we do not always
455    have access to the current target when we need it, so for now it is
456    static.  This will be fine for as long as only one target is in use
457    at a time.  */
458 static struct remote_state *remote_state;
459
460 static struct remote_state *
461 get_remote_state_raw (void)
462 {
463   return remote_state;
464 }
465
466 /* Allocate a new struct remote_state with xmalloc, initialize it, and
467    return it.  */
468
469 static struct remote_state *
470 new_remote_state (void)
471 {
472   struct remote_state *result = XCNEW (struct remote_state);
473
474   /* The default buffer size is unimportant; it will be expanded
475      whenever a larger buffer is needed. */
476   result->buf_size = 400;
477   result->buf = (char *) xmalloc (result->buf_size);
478   result->remote_traceframe_number = -1;
479   result->last_sent_signal = GDB_SIGNAL_0;
480   result->fs_pid = -1;
481
482   return result;
483 }
484
485 /* Description of the remote protocol for a given architecture.  */
486
487 struct packet_reg
488 {
489   long offset; /* Offset into G packet.  */
490   long regnum; /* GDB's internal register number.  */
491   LONGEST pnum; /* Remote protocol register number.  */
492   int in_g_packet; /* Always part of G packet.  */
493   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
494      at present.  */
495   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
496      at present.  */
497 };
498
499 struct remote_arch_state
500 {
501   /* Description of the remote protocol registers.  */
502   long sizeof_g_packet;
503
504   /* Description of the remote protocol registers indexed by REGNUM
505      (making an array gdbarch_num_regs in size).  */
506   struct packet_reg *regs;
507
508   /* This is the size (in chars) of the first response to the ``g''
509      packet.  It is used as a heuristic when determining the maximum
510      size of memory-read and memory-write packets.  A target will
511      typically only reserve a buffer large enough to hold the ``g''
512      packet.  The size does not include packet overhead (headers and
513      trailers).  */
514   long actual_register_packet_size;
515
516   /* This is the maximum size (in chars) of a non read/write packet.
517      It is also used as a cap on the size of read/write packets.  */
518   long remote_packet_size;
519 };
520
521 /* Utility: generate error from an incoming stub packet.  */
522 static void
523 trace_error (char *buf)
524 {
525   if (*buf++ != 'E')
526     return;                     /* not an error msg */
527   switch (*buf)
528     {
529     case '1':                   /* malformed packet error */
530       if (*++buf == '0')        /*   general case: */
531         error (_("remote.c: error in outgoing packet."));
532       else
533         error (_("remote.c: error in outgoing packet at field #%ld."),
534                strtol (buf, NULL, 16));
535     default:
536       error (_("Target returns error code '%s'."), buf);
537     }
538 }
539
540 /* Utility: wait for reply from stub, while accepting "O" packets.  */
541 static char *
542 remote_get_noisy_reply (char **buf_p,
543                         long *sizeof_buf)
544 {
545   do                            /* Loop on reply from remote stub.  */
546     {
547       char *buf;
548
549       QUIT;                     /* Allow user to bail out with ^C.  */
550       getpkt (buf_p, sizeof_buf, 0);
551       buf = *buf_p;
552       if (buf[0] == 'E')
553         trace_error (buf);
554       else if (startswith (buf, "qRelocInsn:"))
555         {
556           ULONGEST ul;
557           CORE_ADDR from, to, org_to;
558           char *p, *pp;
559           int adjusted_size = 0;
560           int relocated = 0;
561
562           p = buf + strlen ("qRelocInsn:");
563           pp = unpack_varlen_hex (p, &ul);
564           if (*pp != ';')
565             error (_("invalid qRelocInsn packet: %s"), buf);
566           from = ul;
567
568           p = pp + 1;
569           unpack_varlen_hex (p, &ul);
570           to = ul;
571
572           org_to = to;
573
574           TRY
575             {
576               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
577               relocated = 1;
578             }
579           CATCH (ex, RETURN_MASK_ALL)
580             {
581               if (ex.error == MEMORY_ERROR)
582                 {
583                   /* Propagate memory errors silently back to the
584                      target.  The stub may have limited the range of
585                      addresses we can write to, for example.  */
586                 }
587               else
588                 {
589                   /* Something unexpectedly bad happened.  Be verbose
590                      so we can tell what, and propagate the error back
591                      to the stub, so it doesn't get stuck waiting for
592                      a response.  */
593                   exception_fprintf (gdb_stderr, ex,
594                                      _("warning: relocating instruction: "));
595                 }
596               putpkt ("E01");
597             }
598           END_CATCH
599
600           if (relocated)
601             {
602               adjusted_size = to - org_to;
603
604               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
605               putpkt (buf);
606             }
607         }
608       else if (buf[0] == 'O' && buf[1] != 'K')
609         remote_console_output (buf + 1);        /* 'O' message from stub */
610       else
611         return buf;             /* Here's the actual reply.  */
612     }
613   while (1);
614 }
615
616 /* Handle for retreving the remote protocol data from gdbarch.  */
617 static struct gdbarch_data *remote_gdbarch_data_handle;
618
619 static struct remote_arch_state *
620 get_remote_arch_state (void)
621 {
622   gdb_assert (target_gdbarch () != NULL);
623   return ((struct remote_arch_state *)
624           gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
625 }
626
627 /* Fetch the global remote target state.  */
628
629 static struct remote_state *
630 get_remote_state (void)
631 {
632   /* Make sure that the remote architecture state has been
633      initialized, because doing so might reallocate rs->buf.  Any
634      function which calls getpkt also needs to be mindful of changes
635      to rs->buf, but this call limits the number of places which run
636      into trouble.  */
637   get_remote_arch_state ();
638
639   return get_remote_state_raw ();
640 }
641
642 /* Cleanup routine for the remote module's pspace data.  */
643
644 static void
645 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
646 {
647   char *remote_exec_file = (char *) arg;
648
649   xfree (remote_exec_file);
650 }
651
652 /* Fetch the remote exec-file from the current program space.  */
653
654 static const char *
655 get_remote_exec_file (void)
656 {
657   char *remote_exec_file;
658
659   remote_exec_file
660     = (char *) program_space_data (current_program_space,
661                                    remote_pspace_data);
662   if (remote_exec_file == NULL)
663     return "";
664
665   return remote_exec_file;
666 }
667
668 /* Set the remote exec file for PSPACE.  */
669
670 static void
671 set_pspace_remote_exec_file (struct program_space *pspace,
672                         char *remote_exec_file)
673 {
674   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
675
676   xfree (old_file);
677   set_program_space_data (pspace, remote_pspace_data,
678                           xstrdup (remote_exec_file));
679 }
680
681 /* The "set/show remote exec-file" set command hook.  */
682
683 static void
684 set_remote_exec_file (char *ignored, int from_tty,
685                       struct cmd_list_element *c)
686 {
687   gdb_assert (remote_exec_file_var != NULL);
688   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
689 }
690
691 /* The "set/show remote exec-file" show command hook.  */
692
693 static void
694 show_remote_exec_file (struct ui_file *file, int from_tty,
695                        struct cmd_list_element *cmd, const char *value)
696 {
697   fprintf_filtered (file, "%s\n", remote_exec_file_var);
698 }
699
700 static int
701 compare_pnums (const void *lhs_, const void *rhs_)
702 {
703   const struct packet_reg * const *lhs
704     = (const struct packet_reg * const *) lhs_;
705   const struct packet_reg * const *rhs
706     = (const struct packet_reg * const *) rhs_;
707
708   if ((*lhs)->pnum < (*rhs)->pnum)
709     return -1;
710   else if ((*lhs)->pnum == (*rhs)->pnum)
711     return 0;
712   else
713     return 1;
714 }
715
716 static int
717 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
718 {
719   int regnum, num_remote_regs, offset;
720   struct packet_reg **remote_regs;
721
722   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
723     {
724       struct packet_reg *r = &regs[regnum];
725
726       if (register_size (gdbarch, regnum) == 0)
727         /* Do not try to fetch zero-sized (placeholder) registers.  */
728         r->pnum = -1;
729       else
730         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
731
732       r->regnum = regnum;
733     }
734
735   /* Define the g/G packet format as the contents of each register
736      with a remote protocol number, in order of ascending protocol
737      number.  */
738
739   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
740   for (num_remote_regs = 0, regnum = 0;
741        regnum < gdbarch_num_regs (gdbarch);
742        regnum++)
743     if (regs[regnum].pnum != -1)
744       remote_regs[num_remote_regs++] = &regs[regnum];
745
746   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
747          compare_pnums);
748
749   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
750     {
751       remote_regs[regnum]->in_g_packet = 1;
752       remote_regs[regnum]->offset = offset;
753       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
754     }
755
756   return offset;
757 }
758
759 /* Given the architecture described by GDBARCH, return the remote
760    protocol register's number and the register's offset in the g/G
761    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
762    If the target does not have a mapping for REGNUM, return false,
763    otherwise, return true.  */
764
765 int
766 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
767                                    int *pnum, int *poffset)
768 {
769   int sizeof_g_packet;
770   struct packet_reg *regs;
771   struct cleanup *old_chain;
772
773   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
774
775   regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
776   old_chain = make_cleanup (xfree, regs);
777
778   sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
779
780   *pnum = regs[regnum].pnum;
781   *poffset = regs[regnum].offset;
782
783   do_cleanups (old_chain);
784
785   return *pnum != -1;
786 }
787
788 static void *
789 init_remote_state (struct gdbarch *gdbarch)
790 {
791   struct remote_state *rs = get_remote_state_raw ();
792   struct remote_arch_state *rsa;
793
794   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
795
796   /* Use the architecture to build a regnum<->pnum table, which will be
797      1:1 unless a feature set specifies otherwise.  */
798   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
799                                       gdbarch_num_regs (gdbarch),
800                                       struct packet_reg);
801
802   /* Record the maximum possible size of the g packet - it may turn out
803      to be smaller.  */
804   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
805
806   /* Default maximum number of characters in a packet body.  Many
807      remote stubs have a hardwired buffer size of 400 bytes
808      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
809      as the maximum packet-size to ensure that the packet and an extra
810      NUL character can always fit in the buffer.  This stops GDB
811      trashing stubs that try to squeeze an extra NUL into what is
812      already a full buffer (As of 1999-12-04 that was most stubs).  */
813   rsa->remote_packet_size = 400 - 1;
814
815   /* This one is filled in when a ``g'' packet is received.  */
816   rsa->actual_register_packet_size = 0;
817
818   /* Should rsa->sizeof_g_packet needs more space than the
819      default, adjust the size accordingly.  Remember that each byte is
820      encoded as two characters.  32 is the overhead for the packet
821      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
822      (``$NN:G...#NN'') is a better guess, the below has been padded a
823      little.  */
824   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
825     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
826
827   /* Make sure that the packet buffer is plenty big enough for
828      this architecture.  */
829   if (rs->buf_size < rsa->remote_packet_size)
830     {
831       rs->buf_size = 2 * rsa->remote_packet_size;
832       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
833     }
834
835   return rsa;
836 }
837
838 /* Return the current allowed size of a remote packet.  This is
839    inferred from the current architecture, and should be used to
840    limit the length of outgoing packets.  */
841 static long
842 get_remote_packet_size (void)
843 {
844   struct remote_state *rs = get_remote_state ();
845   struct remote_arch_state *rsa = get_remote_arch_state ();
846
847   if (rs->explicit_packet_size)
848     return rs->explicit_packet_size;
849
850   return rsa->remote_packet_size;
851 }
852
853 static struct packet_reg *
854 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
855 {
856   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
857     return NULL;
858   else
859     {
860       struct packet_reg *r = &rsa->regs[regnum];
861
862       gdb_assert (r->regnum == regnum);
863       return r;
864     }
865 }
866
867 static struct packet_reg *
868 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
869 {
870   int i;
871
872   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
873     {
874       struct packet_reg *r = &rsa->regs[i];
875
876       if (r->pnum == pnum)
877         return r;
878     }
879   return NULL;
880 }
881
882 static struct target_ops remote_ops;
883
884 static struct target_ops extended_remote_ops;
885
886 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
887    ``forever'' still use the normal timeout mechanism.  This is
888    currently used by the ASYNC code to guarentee that target reads
889    during the initial connect always time-out.  Once getpkt has been
890    modified to return a timeout indication and, in turn
891    remote_wait()/wait_for_inferior() have gained a timeout parameter
892    this can go away.  */
893 static int wait_forever_enabled_p = 1;
894
895 /* Allow the user to specify what sequence to send to the remote
896    when he requests a program interruption: Although ^C is usually
897    what remote systems expect (this is the default, here), it is
898    sometimes preferable to send a break.  On other systems such
899    as the Linux kernel, a break followed by g, which is Magic SysRq g
900    is required in order to interrupt the execution.  */
901 const char interrupt_sequence_control_c[] = "Ctrl-C";
902 const char interrupt_sequence_break[] = "BREAK";
903 const char interrupt_sequence_break_g[] = "BREAK-g";
904 static const char *const interrupt_sequence_modes[] =
905   {
906     interrupt_sequence_control_c,
907     interrupt_sequence_break,
908     interrupt_sequence_break_g,
909     NULL
910   };
911 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
912
913 static void
914 show_interrupt_sequence (struct ui_file *file, int from_tty,
915                          struct cmd_list_element *c,
916                          const char *value)
917 {
918   if (interrupt_sequence_mode == interrupt_sequence_control_c)
919     fprintf_filtered (file,
920                       _("Send the ASCII ETX character (Ctrl-c) "
921                         "to the remote target to interrupt the "
922                         "execution of the program.\n"));
923   else if (interrupt_sequence_mode == interrupt_sequence_break)
924     fprintf_filtered (file,
925                       _("send a break signal to the remote target "
926                         "to interrupt the execution of the program.\n"));
927   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
928     fprintf_filtered (file,
929                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
930                         "the remote target to interrupt the execution "
931                         "of Linux kernel.\n"));
932   else
933     internal_error (__FILE__, __LINE__,
934                     _("Invalid value for interrupt_sequence_mode: %s."),
935                     interrupt_sequence_mode);
936 }
937
938 /* This boolean variable specifies whether interrupt_sequence is sent
939    to the remote target when gdb connects to it.
940    This is mostly needed when you debug the Linux kernel: The Linux kernel
941    expects BREAK g which is Magic SysRq g for connecting gdb.  */
942 static int interrupt_on_connect = 0;
943
944 /* This variable is used to implement the "set/show remotebreak" commands.
945    Since these commands are now deprecated in favor of "set/show remote
946    interrupt-sequence", it no longer has any effect on the code.  */
947 static int remote_break;
948
949 static void
950 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
951 {
952   if (remote_break)
953     interrupt_sequence_mode = interrupt_sequence_break;
954   else
955     interrupt_sequence_mode = interrupt_sequence_control_c;
956 }
957
958 static void
959 show_remotebreak (struct ui_file *file, int from_tty,
960                   struct cmd_list_element *c,
961                   const char *value)
962 {
963 }
964
965 /* This variable sets the number of bits in an address that are to be
966    sent in a memory ("M" or "m") packet.  Normally, after stripping
967    leading zeros, the entire address would be sent.  This variable
968    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
969    initial implementation of remote.c restricted the address sent in
970    memory packets to ``host::sizeof long'' bytes - (typically 32
971    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
972    address was never sent.  Since fixing this bug may cause a break in
973    some remote targets this variable is principly provided to
974    facilitate backward compatibility.  */
975
976 static unsigned int remote_address_size;
977
978 /* Temporary to track who currently owns the terminal.  See
979    remote_terminal_* for more details.  */
980
981 static int remote_async_terminal_ours_p;
982
983 \f
984 /* User configurable variables for the number of characters in a
985    memory read/write packet.  MIN (rsa->remote_packet_size,
986    rsa->sizeof_g_packet) is the default.  Some targets need smaller
987    values (fifo overruns, et.al.) and some users need larger values
988    (speed up transfers).  The variables ``preferred_*'' (the user
989    request), ``current_*'' (what was actually set) and ``forced_*''
990    (Positive - a soft limit, negative - a hard limit).  */
991
992 struct memory_packet_config
993 {
994   char *name;
995   long size;
996   int fixed_p;
997 };
998
999 /* The default max memory-write-packet-size.  The 16k is historical.
1000    (It came from older GDB's using alloca for buffers and the
1001    knowledge (folklore?) that some hosts don't cope very well with
1002    large alloca calls.)  */
1003 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1004
1005 /* The minimum remote packet size for memory transfers.  Ensures we
1006    can write at least one byte.  */
1007 #define MIN_MEMORY_PACKET_SIZE 20
1008
1009 /* Compute the current size of a read/write packet.  Since this makes
1010    use of ``actual_register_packet_size'' the computation is dynamic.  */
1011
1012 static long
1013 get_memory_packet_size (struct memory_packet_config *config)
1014 {
1015   struct remote_state *rs = get_remote_state ();
1016   struct remote_arch_state *rsa = get_remote_arch_state ();
1017
1018   long what_they_get;
1019   if (config->fixed_p)
1020     {
1021       if (config->size <= 0)
1022         what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1023       else
1024         what_they_get = config->size;
1025     }
1026   else
1027     {
1028       what_they_get = get_remote_packet_size ();
1029       /* Limit the packet to the size specified by the user.  */
1030       if (config->size > 0
1031           && what_they_get > config->size)
1032         what_they_get = config->size;
1033
1034       /* Limit it to the size of the targets ``g'' response unless we have
1035          permission from the stub to use a larger packet size.  */
1036       if (rs->explicit_packet_size == 0
1037           && rsa->actual_register_packet_size > 0
1038           && what_they_get > rsa->actual_register_packet_size)
1039         what_they_get = rsa->actual_register_packet_size;
1040     }
1041   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1042     what_they_get = MIN_MEMORY_PACKET_SIZE;
1043
1044   /* Make sure there is room in the global buffer for this packet
1045      (including its trailing NUL byte).  */
1046   if (rs->buf_size < what_they_get + 1)
1047     {
1048       rs->buf_size = 2 * what_they_get;
1049       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1050     }
1051
1052   return what_they_get;
1053 }
1054
1055 /* Update the size of a read/write packet.  If they user wants
1056    something really big then do a sanity check.  */
1057
1058 static void
1059 set_memory_packet_size (char *args, struct memory_packet_config *config)
1060 {
1061   int fixed_p = config->fixed_p;
1062   long size = config->size;
1063
1064   if (args == NULL)
1065     error (_("Argument required (integer, `fixed' or `limited')."));
1066   else if (strcmp (args, "hard") == 0
1067       || strcmp (args, "fixed") == 0)
1068     fixed_p = 1;
1069   else if (strcmp (args, "soft") == 0
1070            || strcmp (args, "limit") == 0)
1071     fixed_p = 0;
1072   else
1073     {
1074       char *end;
1075
1076       size = strtoul (args, &end, 0);
1077       if (args == end)
1078         error (_("Invalid %s (bad syntax)."), config->name);
1079
1080       /* Instead of explicitly capping the size of a packet to or
1081          disallowing it, the user is allowed to set the size to
1082          something arbitrarily large.  */
1083     }
1084
1085   /* So that the query shows the correct value.  */
1086   if (size <= 0)
1087     size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1088
1089   /* Extra checks?  */
1090   if (fixed_p && !config->fixed_p)
1091     {
1092       if (! query (_("The target may not be able to correctly handle a %s\n"
1093                    "of %ld bytes. Change the packet size? "),
1094                    config->name, size))
1095         error (_("Packet size not changed."));
1096     }
1097   /* Update the config.  */
1098   config->fixed_p = fixed_p;
1099   config->size = size;
1100 }
1101
1102 static void
1103 show_memory_packet_size (struct memory_packet_config *config)
1104 {
1105   printf_filtered (_("The %s is %ld. "), config->name, config->size);
1106   if (config->fixed_p)
1107     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1108                      get_memory_packet_size (config));
1109   else
1110     printf_filtered (_("Packets are limited to %ld bytes.\n"),
1111                      get_memory_packet_size (config));
1112 }
1113
1114 static struct memory_packet_config memory_write_packet_config =
1115 {
1116   "memory-write-packet-size",
1117 };
1118
1119 static void
1120 set_memory_write_packet_size (char *args, int from_tty)
1121 {
1122   set_memory_packet_size (args, &memory_write_packet_config);
1123 }
1124
1125 static void
1126 show_memory_write_packet_size (char *args, int from_tty)
1127 {
1128   show_memory_packet_size (&memory_write_packet_config);
1129 }
1130
1131 static long
1132 get_memory_write_packet_size (void)
1133 {
1134   return get_memory_packet_size (&memory_write_packet_config);
1135 }
1136
1137 static struct memory_packet_config memory_read_packet_config =
1138 {
1139   "memory-read-packet-size",
1140 };
1141
1142 static void
1143 set_memory_read_packet_size (char *args, int from_tty)
1144 {
1145   set_memory_packet_size (args, &memory_read_packet_config);
1146 }
1147
1148 static void
1149 show_memory_read_packet_size (char *args, int from_tty)
1150 {
1151   show_memory_packet_size (&memory_read_packet_config);
1152 }
1153
1154 static long
1155 get_memory_read_packet_size (void)
1156 {
1157   long size = get_memory_packet_size (&memory_read_packet_config);
1158
1159   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1160      extra buffer size argument before the memory read size can be
1161      increased beyond this.  */
1162   if (size > get_remote_packet_size ())
1163     size = get_remote_packet_size ();
1164   return size;
1165 }
1166
1167 \f
1168 /* Generic configuration support for packets the stub optionally
1169    supports.  Allows the user to specify the use of the packet as well
1170    as allowing GDB to auto-detect support in the remote stub.  */
1171
1172 enum packet_support
1173   {
1174     PACKET_SUPPORT_UNKNOWN = 0,
1175     PACKET_ENABLE,
1176     PACKET_DISABLE
1177   };
1178
1179 struct packet_config
1180   {
1181     const char *name;
1182     const char *title;
1183
1184     /* If auto, GDB auto-detects support for this packet or feature,
1185        either through qSupported, or by trying the packet and looking
1186        at the response.  If true, GDB assumes the target supports this
1187        packet.  If false, the packet is disabled.  Configs that don't
1188        have an associated command always have this set to auto.  */
1189     enum auto_boolean detect;
1190
1191     /* Does the target support this packet?  */
1192     enum packet_support support;
1193   };
1194
1195 /* Analyze a packet's return value and update the packet config
1196    accordingly.  */
1197
1198 enum packet_result
1199 {
1200   PACKET_ERROR,
1201   PACKET_OK,
1202   PACKET_UNKNOWN
1203 };
1204
1205 static enum packet_support packet_config_support (struct packet_config *config);
1206 static enum packet_support packet_support (int packet);
1207
1208 static void
1209 show_packet_config_cmd (struct packet_config *config)
1210 {
1211   char *support = "internal-error";
1212
1213   switch (packet_config_support (config))
1214     {
1215     case PACKET_ENABLE:
1216       support = "enabled";
1217       break;
1218     case PACKET_DISABLE:
1219       support = "disabled";
1220       break;
1221     case PACKET_SUPPORT_UNKNOWN:
1222       support = "unknown";
1223       break;
1224     }
1225   switch (config->detect)
1226     {
1227     case AUTO_BOOLEAN_AUTO:
1228       printf_filtered (_("Support for the `%s' packet "
1229                          "is auto-detected, currently %s.\n"),
1230                        config->name, support);
1231       break;
1232     case AUTO_BOOLEAN_TRUE:
1233     case AUTO_BOOLEAN_FALSE:
1234       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1235                        config->name, support);
1236       break;
1237     }
1238 }
1239
1240 static void
1241 add_packet_config_cmd (struct packet_config *config, const char *name,
1242                        const char *title, int legacy)
1243 {
1244   char *set_doc;
1245   char *show_doc;
1246   char *cmd_name;
1247
1248   config->name = name;
1249   config->title = title;
1250   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1251                         name, title);
1252   show_doc = xstrprintf ("Show current use of remote "
1253                          "protocol `%s' (%s) packet",
1254                          name, title);
1255   /* set/show TITLE-packet {auto,on,off} */
1256   cmd_name = xstrprintf ("%s-packet", title);
1257   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1258                                 &config->detect, set_doc,
1259                                 show_doc, NULL, /* help_doc */
1260                                 NULL,
1261                                 show_remote_protocol_packet_cmd,
1262                                 &remote_set_cmdlist, &remote_show_cmdlist);
1263   /* The command code copies the documentation strings.  */
1264   xfree (set_doc);
1265   xfree (show_doc);
1266   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1267   if (legacy)
1268     {
1269       char *legacy_name;
1270
1271       legacy_name = xstrprintf ("%s-packet", name);
1272       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1273                      &remote_set_cmdlist);
1274       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1275                      &remote_show_cmdlist);
1276     }
1277 }
1278
1279 static enum packet_result
1280 packet_check_result (const char *buf)
1281 {
1282   if (buf[0] != '\0')
1283     {
1284       /* The stub recognized the packet request.  Check that the
1285          operation succeeded.  */
1286       if (buf[0] == 'E'
1287           && isxdigit (buf[1]) && isxdigit (buf[2])
1288           && buf[3] == '\0')
1289         /* "Enn"  - definitly an error.  */
1290         return PACKET_ERROR;
1291
1292       /* Always treat "E." as an error.  This will be used for
1293          more verbose error messages, such as E.memtypes.  */
1294       if (buf[0] == 'E' && buf[1] == '.')
1295         return PACKET_ERROR;
1296
1297       /* The packet may or may not be OK.  Just assume it is.  */
1298       return PACKET_OK;
1299     }
1300   else
1301     /* The stub does not support the packet.  */
1302     return PACKET_UNKNOWN;
1303 }
1304
1305 static enum packet_result
1306 packet_ok (const char *buf, struct packet_config *config)
1307 {
1308   enum packet_result result;
1309
1310   if (config->detect != AUTO_BOOLEAN_TRUE
1311       && config->support == PACKET_DISABLE)
1312     internal_error (__FILE__, __LINE__,
1313                     _("packet_ok: attempt to use a disabled packet"));
1314
1315   result = packet_check_result (buf);
1316   switch (result)
1317     {
1318     case PACKET_OK:
1319     case PACKET_ERROR:
1320       /* The stub recognized the packet request.  */
1321       if (config->support == PACKET_SUPPORT_UNKNOWN)
1322         {
1323           if (remote_debug)
1324             fprintf_unfiltered (gdb_stdlog,
1325                                 "Packet %s (%s) is supported\n",
1326                                 config->name, config->title);
1327           config->support = PACKET_ENABLE;
1328         }
1329       break;
1330     case PACKET_UNKNOWN:
1331       /* The stub does not support the packet.  */
1332       if (config->detect == AUTO_BOOLEAN_AUTO
1333           && config->support == PACKET_ENABLE)
1334         {
1335           /* If the stub previously indicated that the packet was
1336              supported then there is a protocol error.  */
1337           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1338                  config->name, config->title);
1339         }
1340       else if (config->detect == AUTO_BOOLEAN_TRUE)
1341         {
1342           /* The user set it wrong.  */
1343           error (_("Enabled packet %s (%s) not recognized by stub"),
1344                  config->name, config->title);
1345         }
1346
1347       if (remote_debug)
1348         fprintf_unfiltered (gdb_stdlog,
1349                             "Packet %s (%s) is NOT supported\n",
1350                             config->name, config->title);
1351       config->support = PACKET_DISABLE;
1352       break;
1353     }
1354
1355   return result;
1356 }
1357
1358 enum {
1359   PACKET_vCont = 0,
1360   PACKET_X,
1361   PACKET_qSymbol,
1362   PACKET_P,
1363   PACKET_p,
1364   PACKET_Z0,
1365   PACKET_Z1,
1366   PACKET_Z2,
1367   PACKET_Z3,
1368   PACKET_Z4,
1369   PACKET_vFile_setfs,
1370   PACKET_vFile_open,
1371   PACKET_vFile_pread,
1372   PACKET_vFile_pwrite,
1373   PACKET_vFile_close,
1374   PACKET_vFile_unlink,
1375   PACKET_vFile_readlink,
1376   PACKET_vFile_fstat,
1377   PACKET_qXfer_auxv,
1378   PACKET_qXfer_features,
1379   PACKET_qXfer_exec_file,
1380   PACKET_qXfer_libraries,
1381   PACKET_qXfer_libraries_svr4,
1382   PACKET_qXfer_memory_map,
1383   PACKET_qXfer_spu_read,
1384   PACKET_qXfer_spu_write,
1385   PACKET_qXfer_osdata,
1386   PACKET_qXfer_threads,
1387   PACKET_qXfer_statictrace_read,
1388   PACKET_qXfer_traceframe_info,
1389   PACKET_qXfer_uib,
1390   PACKET_qGetTIBAddr,
1391   PACKET_qGetTLSAddr,
1392   PACKET_qSupported,
1393   PACKET_qTStatus,
1394   PACKET_QPassSignals,
1395   PACKET_QProgramSignals,
1396   PACKET_qCRC,
1397   PACKET_qSearch_memory,
1398   PACKET_vAttach,
1399   PACKET_vRun,
1400   PACKET_QStartNoAckMode,
1401   PACKET_vKill,
1402   PACKET_qXfer_siginfo_read,
1403   PACKET_qXfer_siginfo_write,
1404   PACKET_qAttached,
1405
1406   /* Support for conditional tracepoints.  */
1407   PACKET_ConditionalTracepoints,
1408
1409   /* Support for target-side breakpoint conditions.  */
1410   PACKET_ConditionalBreakpoints,
1411
1412   /* Support for target-side breakpoint commands.  */
1413   PACKET_BreakpointCommands,
1414
1415   /* Support for fast tracepoints.  */
1416   PACKET_FastTracepoints,
1417
1418   /* Support for static tracepoints.  */
1419   PACKET_StaticTracepoints,
1420
1421   /* Support for installing tracepoints while a trace experiment is
1422      running.  */
1423   PACKET_InstallInTrace,
1424
1425   PACKET_bc,
1426   PACKET_bs,
1427   PACKET_TracepointSource,
1428   PACKET_QAllow,
1429   PACKET_qXfer_fdpic,
1430   PACKET_QDisableRandomization,
1431   PACKET_QAgent,
1432   PACKET_QTBuffer_size,
1433   PACKET_Qbtrace_off,
1434   PACKET_Qbtrace_bts,
1435   PACKET_Qbtrace_pt,
1436   PACKET_qXfer_btrace,
1437
1438   /* Support for the QNonStop packet.  */
1439   PACKET_QNonStop,
1440
1441   /* Support for the QThreadEvents packet.  */
1442   PACKET_QThreadEvents,
1443
1444   /* Support for multi-process extensions.  */
1445   PACKET_multiprocess_feature,
1446
1447   /* Support for enabling and disabling tracepoints while a trace
1448      experiment is running.  */
1449   PACKET_EnableDisableTracepoints_feature,
1450
1451   /* Support for collecting strings using the tracenz bytecode.  */
1452   PACKET_tracenz_feature,
1453
1454   /* Support for continuing to run a trace experiment while GDB is
1455      disconnected.  */
1456   PACKET_DisconnectedTracing_feature,
1457
1458   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1459   PACKET_augmented_libraries_svr4_read_feature,
1460
1461   /* Support for the qXfer:btrace-conf:read packet.  */
1462   PACKET_qXfer_btrace_conf,
1463
1464   /* Support for the Qbtrace-conf:bts:size packet.  */
1465   PACKET_Qbtrace_conf_bts_size,
1466
1467   /* Support for swbreak+ feature.  */
1468   PACKET_swbreak_feature,
1469
1470   /* Support for hwbreak+ feature.  */
1471   PACKET_hwbreak_feature,
1472
1473   /* Support for fork events.  */
1474   PACKET_fork_event_feature,
1475
1476   /* Support for vfork events.  */
1477   PACKET_vfork_event_feature,
1478
1479   /* Support for the Qbtrace-conf:pt:size packet.  */
1480   PACKET_Qbtrace_conf_pt_size,
1481
1482   /* Support for exec events.  */
1483   PACKET_exec_event_feature,
1484
1485   /* Support for query supported vCont actions.  */
1486   PACKET_vContSupported,
1487
1488   /* Support remote CTRL-C.  */
1489   PACKET_vCtrlC,
1490
1491   /* Support TARGET_WAITKIND_NO_RESUMED.  */
1492   PACKET_no_resumed,
1493
1494   PACKET_MAX
1495 };
1496
1497 static struct packet_config remote_protocol_packets[PACKET_MAX];
1498
1499 /* Returns the packet's corresponding "set remote foo-packet" command
1500    state.  See struct packet_config for more details.  */
1501
1502 static enum auto_boolean
1503 packet_set_cmd_state (int packet)
1504 {
1505   return remote_protocol_packets[packet].detect;
1506 }
1507
1508 /* Returns whether a given packet or feature is supported.  This takes
1509    into account the state of the corresponding "set remote foo-packet"
1510    command, which may be used to bypass auto-detection.  */
1511
1512 static enum packet_support
1513 packet_config_support (struct packet_config *config)
1514 {
1515   switch (config->detect)
1516     {
1517     case AUTO_BOOLEAN_TRUE:
1518       return PACKET_ENABLE;
1519     case AUTO_BOOLEAN_FALSE:
1520       return PACKET_DISABLE;
1521     case AUTO_BOOLEAN_AUTO:
1522       return config->support;
1523     default:
1524       gdb_assert_not_reached (_("bad switch"));
1525     }
1526 }
1527
1528 /* Same as packet_config_support, but takes the packet's enum value as
1529    argument.  */
1530
1531 static enum packet_support
1532 packet_support (int packet)
1533 {
1534   struct packet_config *config = &remote_protocol_packets[packet];
1535
1536   return packet_config_support (config);
1537 }
1538
1539 static void
1540 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1541                                  struct cmd_list_element *c,
1542                                  const char *value)
1543 {
1544   struct packet_config *packet;
1545
1546   for (packet = remote_protocol_packets;
1547        packet < &remote_protocol_packets[PACKET_MAX];
1548        packet++)
1549     {
1550       if (&packet->detect == c->var)
1551         {
1552           show_packet_config_cmd (packet);
1553           return;
1554         }
1555     }
1556   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1557                   c->name);
1558 }
1559
1560 /* Should we try one of the 'Z' requests?  */
1561
1562 enum Z_packet_type
1563 {
1564   Z_PACKET_SOFTWARE_BP,
1565   Z_PACKET_HARDWARE_BP,
1566   Z_PACKET_WRITE_WP,
1567   Z_PACKET_READ_WP,
1568   Z_PACKET_ACCESS_WP,
1569   NR_Z_PACKET_TYPES
1570 };
1571
1572 /* For compatibility with older distributions.  Provide a ``set remote
1573    Z-packet ...'' command that updates all the Z packet types.  */
1574
1575 static enum auto_boolean remote_Z_packet_detect;
1576
1577 static void
1578 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1579                                   struct cmd_list_element *c)
1580 {
1581   int i;
1582
1583   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1584     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1585 }
1586
1587 static void
1588 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1589                                    struct cmd_list_element *c,
1590                                    const char *value)
1591 {
1592   int i;
1593
1594   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1595     {
1596       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1597     }
1598 }
1599
1600 /* Returns true if the multi-process extensions are in effect.  */
1601
1602 static int
1603 remote_multi_process_p (struct remote_state *rs)
1604 {
1605   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1606 }
1607
1608 /* Returns true if fork events are supported.  */
1609
1610 static int
1611 remote_fork_event_p (struct remote_state *rs)
1612 {
1613   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1614 }
1615
1616 /* Returns true if vfork events are supported.  */
1617
1618 static int
1619 remote_vfork_event_p (struct remote_state *rs)
1620 {
1621   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1622 }
1623
1624 /* Returns true if exec events are supported.  */
1625
1626 static int
1627 remote_exec_event_p (struct remote_state *rs)
1628 {
1629   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1630 }
1631
1632 /* Insert fork catchpoint target routine.  If fork events are enabled
1633    then return success, nothing more to do.  */
1634
1635 static int
1636 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1637 {
1638   struct remote_state *rs = get_remote_state ();
1639
1640   return !remote_fork_event_p (rs);
1641 }
1642
1643 /* Remove fork catchpoint target routine.  Nothing to do, just
1644    return success.  */
1645
1646 static int
1647 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1648 {
1649   return 0;
1650 }
1651
1652 /* Insert vfork catchpoint target routine.  If vfork events are enabled
1653    then return success, nothing more to do.  */
1654
1655 static int
1656 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1657 {
1658   struct remote_state *rs = get_remote_state ();
1659
1660   return !remote_vfork_event_p (rs);
1661 }
1662
1663 /* Remove vfork catchpoint target routine.  Nothing to do, just
1664    return success.  */
1665
1666 static int
1667 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1668 {
1669   return 0;
1670 }
1671
1672 /* Insert exec catchpoint target routine.  If exec events are
1673    enabled, just return success.  */
1674
1675 static int
1676 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1677 {
1678   struct remote_state *rs = get_remote_state ();
1679
1680   return !remote_exec_event_p (rs);
1681 }
1682
1683 /* Remove exec catchpoint target routine.  Nothing to do, just
1684    return success.  */
1685
1686 static int
1687 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1688 {
1689   return 0;
1690 }
1691
1692 /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
1693 static struct async_signal_handler *async_sigint_remote_twice_token;
1694 static struct async_signal_handler *async_sigint_remote_token;
1695
1696 \f
1697 /* Asynchronous signal handle registered as event loop source for
1698    when we have pending events ready to be passed to the core.  */
1699
1700 static struct async_event_handler *remote_async_inferior_event_token;
1701
1702 \f
1703
1704 static ptid_t magic_null_ptid;
1705 static ptid_t not_sent_ptid;
1706 static ptid_t any_thread_ptid;
1707
1708 /* Find out if the stub attached to PID (and hence GDB should offer to
1709    detach instead of killing it when bailing out).  */
1710
1711 static int
1712 remote_query_attached (int pid)
1713 {
1714   struct remote_state *rs = get_remote_state ();
1715   size_t size = get_remote_packet_size ();
1716
1717   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1718     return 0;
1719
1720   if (remote_multi_process_p (rs))
1721     xsnprintf (rs->buf, size, "qAttached:%x", pid);
1722   else
1723     xsnprintf (rs->buf, size, "qAttached");
1724
1725   putpkt (rs->buf);
1726   getpkt (&rs->buf, &rs->buf_size, 0);
1727
1728   switch (packet_ok (rs->buf,
1729                      &remote_protocol_packets[PACKET_qAttached]))
1730     {
1731     case PACKET_OK:
1732       if (strcmp (rs->buf, "1") == 0)
1733         return 1;
1734       break;
1735     case PACKET_ERROR:
1736       warning (_("Remote failure reply: %s"), rs->buf);
1737       break;
1738     case PACKET_UNKNOWN:
1739       break;
1740     }
1741
1742   return 0;
1743 }
1744
1745 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
1746    has been invented by GDB, instead of reported by the target.  Since
1747    we can be connected to a remote system before before knowing about
1748    any inferior, mark the target with execution when we find the first
1749    inferior.  If ATTACHED is 1, then we had just attached to this
1750    inferior.  If it is 0, then we just created this inferior.  If it
1751    is -1, then try querying the remote stub to find out if it had
1752    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
1753    attempt to open this inferior's executable as the main executable
1754    if no main executable is open already.  */
1755
1756 static struct inferior *
1757 remote_add_inferior (int fake_pid_p, int pid, int attached,
1758                      int try_open_exec)
1759 {
1760   struct inferior *inf;
1761
1762   /* Check whether this process we're learning about is to be
1763      considered attached, or if is to be considered to have been
1764      spawned by the stub.  */
1765   if (attached == -1)
1766     attached = remote_query_attached (pid);
1767
1768   if (gdbarch_has_global_solist (target_gdbarch ()))
1769     {
1770       /* If the target shares code across all inferiors, then every
1771          attach adds a new inferior.  */
1772       inf = add_inferior (pid);
1773
1774       /* ... and every inferior is bound to the same program space.
1775          However, each inferior may still have its own address
1776          space.  */
1777       inf->aspace = maybe_new_address_space ();
1778       inf->pspace = current_program_space;
1779     }
1780   else
1781     {
1782       /* In the traditional debugging scenario, there's a 1-1 match
1783          between program/address spaces.  We simply bind the inferior
1784          to the program space's address space.  */
1785       inf = current_inferior ();
1786       inferior_appeared (inf, pid);
1787     }
1788
1789   inf->attach_flag = attached;
1790   inf->fake_pid_p = fake_pid_p;
1791
1792   /* If no main executable is currently open then attempt to
1793      open the file that was executed to create this inferior.  */
1794   if (try_open_exec && get_exec_file (0) == NULL)
1795     exec_file_locate_attach (pid, 1);
1796
1797   return inf;
1798 }
1799
1800 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1801    according to RUNNING.  */
1802
1803 static void
1804 remote_add_thread (ptid_t ptid, int running)
1805 {
1806   struct remote_state *rs = get_remote_state ();
1807
1808   /* GDB historically didn't pull threads in the initial connection
1809      setup.  If the remote target doesn't even have a concept of
1810      threads (e.g., a bare-metal target), even if internally we
1811      consider that a single-threaded target, mentioning a new thread
1812      might be confusing to the user.  Be silent then, preserving the
1813      age old behavior.  */
1814   if (rs->starting_up)
1815     add_thread_silent (ptid);
1816   else
1817     add_thread (ptid);
1818
1819   set_executing (ptid, running);
1820   set_running (ptid, running);
1821 }
1822
1823 /* Come here when we learn about a thread id from the remote target.
1824    It may be the first time we hear about such thread, so take the
1825    opportunity to add it to GDB's thread list.  In case this is the
1826    first time we're noticing its corresponding inferior, add it to
1827    GDB's inferior list as well.  */
1828
1829 static void
1830 remote_notice_new_inferior (ptid_t currthread, int running)
1831 {
1832   /* If this is a new thread, add it to GDB's thread list.
1833      If we leave it up to WFI to do this, bad things will happen.  */
1834
1835   if (in_thread_list (currthread) && is_exited (currthread))
1836     {
1837       /* We're seeing an event on a thread id we knew had exited.
1838          This has to be a new thread reusing the old id.  Add it.  */
1839       remote_add_thread (currthread, running);
1840       return;
1841     }
1842
1843   if (!in_thread_list (currthread))
1844     {
1845       struct inferior *inf = NULL;
1846       int pid = ptid_get_pid (currthread);
1847
1848       if (ptid_is_pid (inferior_ptid)
1849           && pid == ptid_get_pid (inferior_ptid))
1850         {
1851           /* inferior_ptid has no thread member yet.  This can happen
1852              with the vAttach -> remote_wait,"TAAthread:" path if the
1853              stub doesn't support qC.  This is the first stop reported
1854              after an attach, so this is the main thread.  Update the
1855              ptid in the thread list.  */
1856           if (in_thread_list (pid_to_ptid (pid)))
1857             thread_change_ptid (inferior_ptid, currthread);
1858           else
1859             {
1860               remote_add_thread (currthread, running);
1861               inferior_ptid = currthread;
1862             }
1863           return;
1864         }
1865
1866       if (ptid_equal (magic_null_ptid, inferior_ptid))
1867         {
1868           /* inferior_ptid is not set yet.  This can happen with the
1869              vRun -> remote_wait,"TAAthread:" path if the stub
1870              doesn't support qC.  This is the first stop reported
1871              after an attach, so this is the main thread.  Update the
1872              ptid in the thread list.  */
1873           thread_change_ptid (inferior_ptid, currthread);
1874           return;
1875         }
1876
1877       /* When connecting to a target remote, or to a target
1878          extended-remote which already was debugging an inferior, we
1879          may not know about it yet.  Add it before adding its child
1880          thread, so notifications are emitted in a sensible order.  */
1881       if (!in_inferior_list (ptid_get_pid (currthread)))
1882         {
1883           struct remote_state *rs = get_remote_state ();
1884           int fake_pid_p = !remote_multi_process_p (rs);
1885
1886           inf = remote_add_inferior (fake_pid_p,
1887                                      ptid_get_pid (currthread), -1, 1);
1888         }
1889
1890       /* This is really a new thread.  Add it.  */
1891       remote_add_thread (currthread, running);
1892
1893       /* If we found a new inferior, let the common code do whatever
1894          it needs to with it (e.g., read shared libraries, insert
1895          breakpoints), unless we're just setting up an all-stop
1896          connection.  */
1897       if (inf != NULL)
1898         {
1899           struct remote_state *rs = get_remote_state ();
1900
1901           if (!rs->starting_up)
1902             notice_new_inferior (currthread, running, 0);
1903         }
1904     }
1905 }
1906
1907 /* Return the private thread data, creating it if necessary.  */
1908
1909 static struct private_thread_info *
1910 demand_private_info (ptid_t ptid)
1911 {
1912   struct thread_info *info = find_thread_ptid (ptid);
1913
1914   gdb_assert (info);
1915
1916   if (!info->priv)
1917     {
1918       info->priv = XNEW (struct private_thread_info);
1919       info->private_dtor = free_private_thread_info;
1920       info->priv->core = -1;
1921       info->priv->extra = NULL;
1922       info->priv->name = NULL;
1923     }
1924
1925   return info->priv;
1926 }
1927
1928 /* Call this function as a result of
1929    1) A halt indication (T packet) containing a thread id
1930    2) A direct query of currthread
1931    3) Successful execution of set thread */
1932
1933 static void
1934 record_currthread (struct remote_state *rs, ptid_t currthread)
1935 {
1936   rs->general_thread = currthread;
1937 }
1938
1939 /* If 'QPassSignals' is supported, tell the remote stub what signals
1940    it can simply pass through to the inferior without reporting.  */
1941
1942 static void
1943 remote_pass_signals (struct target_ops *self,
1944                      int numsigs, unsigned char *pass_signals)
1945 {
1946   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1947     {
1948       char *pass_packet, *p;
1949       int count = 0, i;
1950       struct remote_state *rs = get_remote_state ();
1951
1952       gdb_assert (numsigs < 256);
1953       for (i = 0; i < numsigs; i++)
1954         {
1955           if (pass_signals[i])
1956             count++;
1957         }
1958       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1959       strcpy (pass_packet, "QPassSignals:");
1960       p = pass_packet + strlen (pass_packet);
1961       for (i = 0; i < numsigs; i++)
1962         {
1963           if (pass_signals[i])
1964             {
1965               if (i >= 16)
1966                 *p++ = tohex (i >> 4);
1967               *p++ = tohex (i & 15);
1968               if (count)
1969                 *p++ = ';';
1970               else
1971                 break;
1972               count--;
1973             }
1974         }
1975       *p = 0;
1976       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1977         {
1978           putpkt (pass_packet);
1979           getpkt (&rs->buf, &rs->buf_size, 0);
1980           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1981           if (rs->last_pass_packet)
1982             xfree (rs->last_pass_packet);
1983           rs->last_pass_packet = pass_packet;
1984         }
1985       else
1986         xfree (pass_packet);
1987     }
1988 }
1989
1990 /* If 'QProgramSignals' is supported, tell the remote stub what
1991    signals it should pass through to the inferior when detaching.  */
1992
1993 static void
1994 remote_program_signals (struct target_ops *self,
1995                         int numsigs, unsigned char *signals)
1996 {
1997   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1998     {
1999       char *packet, *p;
2000       int count = 0, i;
2001       struct remote_state *rs = get_remote_state ();
2002
2003       gdb_assert (numsigs < 256);
2004       for (i = 0; i < numsigs; i++)
2005         {
2006           if (signals[i])
2007             count++;
2008         }
2009       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2010       strcpy (packet, "QProgramSignals:");
2011       p = packet + strlen (packet);
2012       for (i = 0; i < numsigs; i++)
2013         {
2014           if (signal_pass_state (i))
2015             {
2016               if (i >= 16)
2017                 *p++ = tohex (i >> 4);
2018               *p++ = tohex (i & 15);
2019               if (count)
2020                 *p++ = ';';
2021               else
2022                 break;
2023               count--;
2024             }
2025         }
2026       *p = 0;
2027       if (!rs->last_program_signals_packet
2028           || strcmp (rs->last_program_signals_packet, packet) != 0)
2029         {
2030           putpkt (packet);
2031           getpkt (&rs->buf, &rs->buf_size, 0);
2032           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2033           xfree (rs->last_program_signals_packet);
2034           rs->last_program_signals_packet = packet;
2035         }
2036       else
2037         xfree (packet);
2038     }
2039 }
2040
2041 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2042    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2043    thread.  If GEN is set, set the general thread, if not, then set
2044    the step/continue thread.  */
2045 static void
2046 set_thread (struct ptid ptid, int gen)
2047 {
2048   struct remote_state *rs = get_remote_state ();
2049   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2050   char *buf = rs->buf;
2051   char *endbuf = rs->buf + get_remote_packet_size ();
2052
2053   if (ptid_equal (state, ptid))
2054     return;
2055
2056   *buf++ = 'H';
2057   *buf++ = gen ? 'g' : 'c';
2058   if (ptid_equal (ptid, magic_null_ptid))
2059     xsnprintf (buf, endbuf - buf, "0");
2060   else if (ptid_equal (ptid, any_thread_ptid))
2061     xsnprintf (buf, endbuf - buf, "0");
2062   else if (ptid_equal (ptid, minus_one_ptid))
2063     xsnprintf (buf, endbuf - buf, "-1");
2064   else
2065     write_ptid (buf, endbuf, ptid);
2066   putpkt (rs->buf);
2067   getpkt (&rs->buf, &rs->buf_size, 0);
2068   if (gen)
2069     rs->general_thread = ptid;
2070   else
2071     rs->continue_thread = ptid;
2072 }
2073
2074 static void
2075 set_general_thread (struct ptid ptid)
2076 {
2077   set_thread (ptid, 1);
2078 }
2079
2080 static void
2081 set_continue_thread (struct ptid ptid)
2082 {
2083   set_thread (ptid, 0);
2084 }
2085
2086 /* Change the remote current process.  Which thread within the process
2087    ends up selected isn't important, as long as it is the same process
2088    as what INFERIOR_PTID points to.
2089
2090    This comes from that fact that there is no explicit notion of
2091    "selected process" in the protocol.  The selected process for
2092    general operations is the process the selected general thread
2093    belongs to.  */
2094
2095 static void
2096 set_general_process (void)
2097 {
2098   struct remote_state *rs = get_remote_state ();
2099
2100   /* If the remote can't handle multiple processes, don't bother.  */
2101   if (!remote_multi_process_p (rs))
2102     return;
2103
2104   /* We only need to change the remote current thread if it's pointing
2105      at some other process.  */
2106   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2107     set_general_thread (inferior_ptid);
2108 }
2109
2110 \f
2111 /* Return nonzero if this is the main thread that we made up ourselves
2112    to model non-threaded targets as single-threaded.  */
2113
2114 static int
2115 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2116 {
2117   struct remote_state *rs = get_remote_state ();
2118   char *p, *endp;
2119
2120   if (ptid_equal (ptid, magic_null_ptid))
2121     /* The main thread is always alive.  */
2122     return 1;
2123
2124   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2125     /* The main thread is always alive.  This can happen after a
2126        vAttach, if the remote side doesn't support
2127        multi-threading.  */
2128     return 1;
2129
2130   return 0;
2131 }
2132
2133 /* Return nonzero if the thread PTID is still alive on the remote
2134    system.  */
2135
2136 static int
2137 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2138 {
2139   struct remote_state *rs = get_remote_state ();
2140   char *p, *endp;
2141
2142   /* Check if this is a thread that we made up ourselves to model
2143      non-threaded targets as single-threaded.  */
2144   if (remote_thread_always_alive (ops, ptid))
2145     return 1;
2146
2147   p = rs->buf;
2148   endp = rs->buf + get_remote_packet_size ();
2149
2150   *p++ = 'T';
2151   write_ptid (p, endp, ptid);
2152
2153   putpkt (rs->buf);
2154   getpkt (&rs->buf, &rs->buf_size, 0);
2155   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2156 }
2157
2158 /* Return a pointer to a thread name if we know it and NULL otherwise.
2159    The thread_info object owns the memory for the name.  */
2160
2161 static const char *
2162 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2163 {
2164   if (info->priv != NULL)
2165     return info->priv->name;
2166
2167   return NULL;
2168 }
2169
2170 /* About these extended threadlist and threadinfo packets.  They are
2171    variable length packets but, the fields within them are often fixed
2172    length.  They are redundent enough to send over UDP as is the
2173    remote protocol in general.  There is a matching unit test module
2174    in libstub.  */
2175
2176 /* WARNING: This threadref data structure comes from the remote O.S.,
2177    libstub protocol encoding, and remote.c.  It is not particularly
2178    changable.  */
2179
2180 /* Right now, the internal structure is int. We want it to be bigger.
2181    Plan to fix this.  */
2182
2183 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2184
2185 /* gdb_ext_thread_info is an internal GDB data structure which is
2186    equivalent to the reply of the remote threadinfo packet.  */
2187
2188 struct gdb_ext_thread_info
2189   {
2190     threadref threadid;         /* External form of thread reference.  */
2191     int active;                 /* Has state interesting to GDB?
2192                                    regs, stack.  */
2193     char display[256];          /* Brief state display, name,
2194                                    blocked/suspended.  */
2195     char shortname[32];         /* To be used to name threads.  */
2196     char more_display[256];     /* Long info, statistics, queue depth,
2197                                    whatever.  */
2198   };
2199
2200 /* The volume of remote transfers can be limited by submitting
2201    a mask containing bits specifying the desired information.
2202    Use a union of these values as the 'selection' parameter to
2203    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2204
2205 #define TAG_THREADID 1
2206 #define TAG_EXISTS 2
2207 #define TAG_DISPLAY 4
2208 #define TAG_THREADNAME 8
2209 #define TAG_MOREDISPLAY 16
2210
2211 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2212
2213 static char *unpack_nibble (char *buf, int *val);
2214
2215 static char *unpack_byte (char *buf, int *value);
2216
2217 static char *pack_int (char *buf, int value);
2218
2219 static char *unpack_int (char *buf, int *value);
2220
2221 static char *unpack_string (char *src, char *dest, int length);
2222
2223 static char *pack_threadid (char *pkt, threadref *id);
2224
2225 static char *unpack_threadid (char *inbuf, threadref *id);
2226
2227 void int_to_threadref (threadref *id, int value);
2228
2229 static int threadref_to_int (threadref *ref);
2230
2231 static void copy_threadref (threadref *dest, threadref *src);
2232
2233 static int threadmatch (threadref *dest, threadref *src);
2234
2235 static char *pack_threadinfo_request (char *pkt, int mode,
2236                                       threadref *id);
2237
2238 static int remote_unpack_thread_info_response (char *pkt,
2239                                                threadref *expectedref,
2240                                                struct gdb_ext_thread_info
2241                                                *info);
2242
2243
2244 static int remote_get_threadinfo (threadref *threadid,
2245                                   int fieldset, /*TAG mask */
2246                                   struct gdb_ext_thread_info *info);
2247
2248 static char *pack_threadlist_request (char *pkt, int startflag,
2249                                       int threadcount,
2250                                       threadref *nextthread);
2251
2252 static int parse_threadlist_response (char *pkt,
2253                                       int result_limit,
2254                                       threadref *original_echo,
2255                                       threadref *resultlist,
2256                                       int *doneflag);
2257
2258 static int remote_get_threadlist (int startflag,
2259                                   threadref *nextthread,
2260                                   int result_limit,
2261                                   int *done,
2262                                   int *result_count,
2263                                   threadref *threadlist);
2264
2265 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2266
2267 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2268                                        void *context, int looplimit);
2269
2270 static int remote_newthread_step (threadref *ref, void *context);
2271
2272
2273 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2274    buffer we're allowed to write to.  Returns
2275    BUF+CHARACTERS_WRITTEN.  */
2276
2277 static char *
2278 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2279 {
2280   int pid, tid;
2281   struct remote_state *rs = get_remote_state ();
2282
2283   if (remote_multi_process_p (rs))
2284     {
2285       pid = ptid_get_pid (ptid);
2286       if (pid < 0)
2287         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2288       else
2289         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2290     }
2291   tid = ptid_get_lwp (ptid);
2292   if (tid < 0)
2293     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2294   else
2295     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2296
2297   return buf;
2298 }
2299
2300 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
2301    passed the last parsed char.  Returns null_ptid on error.  */
2302
2303 static ptid_t
2304 read_ptid (char *buf, char **obuf)
2305 {
2306   char *p = buf;
2307   char *pp;
2308   ULONGEST pid = 0, tid = 0;
2309
2310   if (*p == 'p')
2311     {
2312       /* Multi-process ptid.  */
2313       pp = unpack_varlen_hex (p + 1, &pid);
2314       if (*pp != '.')
2315         error (_("invalid remote ptid: %s"), p);
2316
2317       p = pp;
2318       pp = unpack_varlen_hex (p + 1, &tid);
2319       if (obuf)
2320         *obuf = pp;
2321       return ptid_build (pid, tid, 0);
2322     }
2323
2324   /* No multi-process.  Just a tid.  */
2325   pp = unpack_varlen_hex (p, &tid);
2326
2327   /* Return null_ptid when no thread id is found.  */
2328   if (p == pp)
2329     {
2330       if (obuf)
2331         *obuf = pp;
2332       return null_ptid;
2333     }
2334
2335   /* Since the stub is not sending a process id, then default to
2336      what's in inferior_ptid, unless it's null at this point.  If so,
2337      then since there's no way to know the pid of the reported
2338      threads, use the magic number.  */
2339   if (ptid_equal (inferior_ptid, null_ptid))
2340     pid = ptid_get_pid (magic_null_ptid);
2341   else
2342     pid = ptid_get_pid (inferior_ptid);
2343
2344   if (obuf)
2345     *obuf = pp;
2346   return ptid_build (pid, tid, 0);
2347 }
2348
2349 static int
2350 stubhex (int ch)
2351 {
2352   if (ch >= 'a' && ch <= 'f')
2353     return ch - 'a' + 10;
2354   if (ch >= '0' && ch <= '9')
2355     return ch - '0';
2356   if (ch >= 'A' && ch <= 'F')
2357     return ch - 'A' + 10;
2358   return -1;
2359 }
2360
2361 static int
2362 stub_unpack_int (char *buff, int fieldlength)
2363 {
2364   int nibble;
2365   int retval = 0;
2366
2367   while (fieldlength)
2368     {
2369       nibble = stubhex (*buff++);
2370       retval |= nibble;
2371       fieldlength--;
2372       if (fieldlength)
2373         retval = retval << 4;
2374     }
2375   return retval;
2376 }
2377
2378 static char *
2379 unpack_nibble (char *buf, int *val)
2380 {
2381   *val = fromhex (*buf++);
2382   return buf;
2383 }
2384
2385 static char *
2386 unpack_byte (char *buf, int *value)
2387 {
2388   *value = stub_unpack_int (buf, 2);
2389   return buf + 2;
2390 }
2391
2392 static char *
2393 pack_int (char *buf, int value)
2394 {
2395   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2396   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2397   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2398   buf = pack_hex_byte (buf, (value & 0xff));
2399   return buf;
2400 }
2401
2402 static char *
2403 unpack_int (char *buf, int *value)
2404 {
2405   *value = stub_unpack_int (buf, 8);
2406   return buf + 8;
2407 }
2408
2409 #if 0                   /* Currently unused, uncomment when needed.  */
2410 static char *pack_string (char *pkt, char *string);
2411
2412 static char *
2413 pack_string (char *pkt, char *string)
2414 {
2415   char ch;
2416   int len;
2417
2418   len = strlen (string);
2419   if (len > 200)
2420     len = 200;          /* Bigger than most GDB packets, junk???  */
2421   pkt = pack_hex_byte (pkt, len);
2422   while (len-- > 0)
2423     {
2424       ch = *string++;
2425       if ((ch == '\0') || (ch == '#'))
2426         ch = '*';               /* Protect encapsulation.  */
2427       *pkt++ = ch;
2428     }
2429   return pkt;
2430 }
2431 #endif /* 0 (unused) */
2432
2433 static char *
2434 unpack_string (char *src, char *dest, int length)
2435 {
2436   while (length--)
2437     *dest++ = *src++;
2438   *dest = '\0';
2439   return src;
2440 }
2441
2442 static char *
2443 pack_threadid (char *pkt, threadref *id)
2444 {
2445   char *limit;
2446   unsigned char *altid;
2447
2448   altid = (unsigned char *) id;
2449   limit = pkt + BUF_THREAD_ID_SIZE;
2450   while (pkt < limit)
2451     pkt = pack_hex_byte (pkt, *altid++);
2452   return pkt;
2453 }
2454
2455
2456 static char *
2457 unpack_threadid (char *inbuf, threadref *id)
2458 {
2459   char *altref;
2460   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2461   int x, y;
2462
2463   altref = (char *) id;
2464
2465   while (inbuf < limit)
2466     {
2467       x = stubhex (*inbuf++);
2468       y = stubhex (*inbuf++);
2469       *altref++ = (x << 4) | y;
2470     }
2471   return inbuf;
2472 }
2473
2474 /* Externally, threadrefs are 64 bits but internally, they are still
2475    ints.  This is due to a mismatch of specifications.  We would like
2476    to use 64bit thread references internally.  This is an adapter
2477    function.  */
2478
2479 void
2480 int_to_threadref (threadref *id, int value)
2481 {
2482   unsigned char *scan;
2483
2484   scan = (unsigned char *) id;
2485   {
2486     int i = 4;
2487     while (i--)
2488       *scan++ = 0;
2489   }
2490   *scan++ = (value >> 24) & 0xff;
2491   *scan++ = (value >> 16) & 0xff;
2492   *scan++ = (value >> 8) & 0xff;
2493   *scan++ = (value & 0xff);
2494 }
2495
2496 static int
2497 threadref_to_int (threadref *ref)
2498 {
2499   int i, value = 0;
2500   unsigned char *scan;
2501
2502   scan = *ref;
2503   scan += 4;
2504   i = 4;
2505   while (i-- > 0)
2506     value = (value << 8) | ((*scan++) & 0xff);
2507   return value;
2508 }
2509
2510 static void
2511 copy_threadref (threadref *dest, threadref *src)
2512 {
2513   int i;
2514   unsigned char *csrc, *cdest;
2515
2516   csrc = (unsigned char *) src;
2517   cdest = (unsigned char *) dest;
2518   i = 8;
2519   while (i--)
2520     *cdest++ = *csrc++;
2521 }
2522
2523 static int
2524 threadmatch (threadref *dest, threadref *src)
2525 {
2526   /* Things are broken right now, so just assume we got a match.  */
2527 #if 0
2528   unsigned char *srcp, *destp;
2529   int i, result;
2530   srcp = (char *) src;
2531   destp = (char *) dest;
2532
2533   result = 1;
2534   while (i-- > 0)
2535     result &= (*srcp++ == *destp++) ? 1 : 0;
2536   return result;
2537 #endif
2538   return 1;
2539 }
2540
2541 /*
2542    threadid:1,        # always request threadid
2543    context_exists:2,
2544    display:4,
2545    unique_name:8,
2546    more_display:16
2547  */
2548
2549 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2550
2551 static char *
2552 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2553 {
2554   *pkt++ = 'q';                         /* Info Query */
2555   *pkt++ = 'P';                         /* process or thread info */
2556   pkt = pack_int (pkt, mode);           /* mode */
2557   pkt = pack_threadid (pkt, id);        /* threadid */
2558   *pkt = '\0';                          /* terminate */
2559   return pkt;
2560 }
2561
2562 /* These values tag the fields in a thread info response packet.  */
2563 /* Tagging the fields allows us to request specific fields and to
2564    add more fields as time goes by.  */
2565
2566 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2567 #define TAG_EXISTS 2            /* Is this process defined enough to
2568                                    fetch registers and its stack?  */
2569 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2570 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2571 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2572                                    the process.  */
2573
2574 static int
2575 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2576                                     struct gdb_ext_thread_info *info)
2577 {
2578   struct remote_state *rs = get_remote_state ();
2579   int mask, length;
2580   int tag;
2581   threadref ref;
2582   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2583   int retval = 1;
2584
2585   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2586   info->active = 0;
2587   info->display[0] = '\0';
2588   info->shortname[0] = '\0';
2589   info->more_display[0] = '\0';
2590
2591   /* Assume the characters indicating the packet type have been
2592      stripped.  */
2593   pkt = unpack_int (pkt, &mask);        /* arg mask */
2594   pkt = unpack_threadid (pkt, &ref);
2595
2596   if (mask == 0)
2597     warning (_("Incomplete response to threadinfo request."));
2598   if (!threadmatch (&ref, expectedref))
2599     {                   /* This is an answer to a different request.  */
2600       warning (_("ERROR RMT Thread info mismatch."));
2601       return 0;
2602     }
2603   copy_threadref (&info->threadid, &ref);
2604
2605   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
2606
2607   /* Packets are terminated with nulls.  */
2608   while ((pkt < limit) && mask && *pkt)
2609     {
2610       pkt = unpack_int (pkt, &tag);     /* tag */
2611       pkt = unpack_byte (pkt, &length); /* length */
2612       if (!(tag & mask))                /* Tags out of synch with mask.  */
2613         {
2614           warning (_("ERROR RMT: threadinfo tag mismatch."));
2615           retval = 0;
2616           break;
2617         }
2618       if (tag == TAG_THREADID)
2619         {
2620           if (length != 16)
2621             {
2622               warning (_("ERROR RMT: length of threadid is not 16."));
2623               retval = 0;
2624               break;
2625             }
2626           pkt = unpack_threadid (pkt, &ref);
2627           mask = mask & ~TAG_THREADID;
2628           continue;
2629         }
2630       if (tag == TAG_EXISTS)
2631         {
2632           info->active = stub_unpack_int (pkt, length);
2633           pkt += length;
2634           mask = mask & ~(TAG_EXISTS);
2635           if (length > 8)
2636             {
2637               warning (_("ERROR RMT: 'exists' length too long."));
2638               retval = 0;
2639               break;
2640             }
2641           continue;
2642         }
2643       if (tag == TAG_THREADNAME)
2644         {
2645           pkt = unpack_string (pkt, &info->shortname[0], length);
2646           mask = mask & ~TAG_THREADNAME;
2647           continue;
2648         }
2649       if (tag == TAG_DISPLAY)
2650         {
2651           pkt = unpack_string (pkt, &info->display[0], length);
2652           mask = mask & ~TAG_DISPLAY;
2653           continue;
2654         }
2655       if (tag == TAG_MOREDISPLAY)
2656         {
2657           pkt = unpack_string (pkt, &info->more_display[0], length);
2658           mask = mask & ~TAG_MOREDISPLAY;
2659           continue;
2660         }
2661       warning (_("ERROR RMT: unknown thread info tag."));
2662       break;                    /* Not a tag we know about.  */
2663     }
2664   return retval;
2665 }
2666
2667 static int
2668 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2669                        struct gdb_ext_thread_info *info)
2670 {
2671   struct remote_state *rs = get_remote_state ();
2672   int result;
2673
2674   pack_threadinfo_request (rs->buf, fieldset, threadid);
2675   putpkt (rs->buf);
2676   getpkt (&rs->buf, &rs->buf_size, 0);
2677
2678   if (rs->buf[0] == '\0')
2679     return 0;
2680
2681   result = remote_unpack_thread_info_response (rs->buf + 2,
2682                                                threadid, info);
2683   return result;
2684 }
2685
2686 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2687
2688 static char *
2689 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2690                          threadref *nextthread)
2691 {
2692   *pkt++ = 'q';                 /* info query packet */
2693   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2694   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2695   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2696   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2697   *pkt = '\0';
2698   return pkt;
2699 }
2700
2701 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2702
2703 static int
2704 parse_threadlist_response (char *pkt, int result_limit,
2705                            threadref *original_echo, threadref *resultlist,
2706                            int *doneflag)
2707 {
2708   struct remote_state *rs = get_remote_state ();
2709   char *limit;
2710   int count, resultcount, done;
2711
2712   resultcount = 0;
2713   /* Assume the 'q' and 'M chars have been stripped.  */
2714   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2715   /* done parse past here */
2716   pkt = unpack_byte (pkt, &count);      /* count field */
2717   pkt = unpack_nibble (pkt, &done);
2718   /* The first threadid is the argument threadid.  */
2719   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2720   while ((count-- > 0) && (pkt < limit))
2721     {
2722       pkt = unpack_threadid (pkt, resultlist++);
2723       if (resultcount++ >= result_limit)
2724         break;
2725     }
2726   if (doneflag)
2727     *doneflag = done;
2728   return resultcount;
2729 }
2730
2731 /* Fetch the next batch of threads from the remote.  Returns -1 if the
2732    qL packet is not supported, 0 on error and 1 on success.  */
2733
2734 static int
2735 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2736                        int *done, int *result_count, threadref *threadlist)
2737 {
2738   struct remote_state *rs = get_remote_state ();
2739   int result = 1;
2740
2741   /* Trancate result limit to be smaller than the packet size.  */
2742   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2743       >= get_remote_packet_size ())
2744     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2745
2746   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2747   putpkt (rs->buf);
2748   getpkt (&rs->buf, &rs->buf_size, 0);
2749   if (*rs->buf == '\0')
2750     {
2751       /* Packet not supported.  */
2752       return -1;
2753     }
2754
2755   *result_count =
2756     parse_threadlist_response (rs->buf + 2, result_limit,
2757                                &rs->echo_nextthread, threadlist, done);
2758
2759   if (!threadmatch (&rs->echo_nextthread, nextthread))
2760     {
2761       /* FIXME: This is a good reason to drop the packet.  */
2762       /* Possably, there is a duplicate response.  */
2763       /* Possabilities :
2764          retransmit immediatly - race conditions
2765          retransmit after timeout - yes
2766          exit
2767          wait for packet, then exit
2768        */
2769       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2770       return 0;                 /* I choose simply exiting.  */
2771     }
2772   if (*result_count <= 0)
2773     {
2774       if (*done != 1)
2775         {
2776           warning (_("RMT ERROR : failed to get remote thread list."));
2777           result = 0;
2778         }
2779       return result;            /* break; */
2780     }
2781   if (*result_count > result_limit)
2782     {
2783       *result_count = 0;
2784       warning (_("RMT ERROR: threadlist response longer than requested."));
2785       return 0;
2786     }
2787   return result;
2788 }
2789
2790 /* Fetch the list of remote threads, with the qL packet, and call
2791    STEPFUNCTION for each thread found.  Stops iterating and returns 1
2792    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
2793    STEPFUNCTION returns false.  If the packet is not supported,
2794    returns -1.  */
2795
2796 static int
2797 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2798                             int looplimit)
2799 {
2800   struct remote_state *rs = get_remote_state ();
2801   int done, i, result_count;
2802   int startflag = 1;
2803   int result = 1;
2804   int loopcount = 0;
2805
2806   done = 0;
2807   while (!done)
2808     {
2809       if (loopcount++ > looplimit)
2810         {
2811           result = 0;
2812           warning (_("Remote fetch threadlist -infinite loop-."));
2813           break;
2814         }
2815       result = remote_get_threadlist (startflag, &rs->nextthread,
2816                                       MAXTHREADLISTRESULTS,
2817                                       &done, &result_count,
2818                                       rs->resultthreadlist);
2819       if (result <= 0)
2820         break;
2821       /* Clear for later iterations.  */
2822       startflag = 0;
2823       /* Setup to resume next batch of thread references, set nextthread.  */
2824       if (result_count >= 1)
2825         copy_threadref (&rs->nextthread,
2826                         &rs->resultthreadlist[result_count - 1]);
2827       i = 0;
2828       while (result_count--)
2829         {
2830           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2831             {
2832               result = 0;
2833               break;
2834             }
2835         }
2836     }
2837   return result;
2838 }
2839
2840 /* A thread found on the remote target.  */
2841
2842 typedef struct thread_item
2843 {
2844   /* The thread's PTID.  */
2845   ptid_t ptid;
2846
2847   /* The thread's extra info.  May be NULL.  */
2848   char *extra;
2849
2850   /* The thread's name.  May be NULL.  */
2851   char *name;
2852
2853   /* The core the thread was running on.  -1 if not known.  */
2854   int core;
2855 } thread_item_t;
2856 DEF_VEC_O(thread_item_t);
2857
2858 /* Context passed around to the various methods listing remote
2859    threads.  As new threads are found, they're added to the ITEMS
2860    vector.  */
2861
2862 struct threads_listing_context
2863 {
2864   /* The threads found on the remote target.  */
2865   VEC (thread_item_t) *items;
2866 };
2867
2868 /* Discard the contents of the constructed thread listing context.  */
2869
2870 static void
2871 clear_threads_listing_context (void *p)
2872 {
2873   struct threads_listing_context *context
2874     = (struct threads_listing_context *) p;
2875   int i;
2876   struct thread_item *item;
2877
2878   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2879     {
2880       xfree (item->extra);
2881       xfree (item->name);
2882     }
2883
2884   VEC_free (thread_item_t, context->items);
2885 }
2886
2887 /* Remove the thread specified as the related_pid field of WS
2888    from the CONTEXT list.  */
2889
2890 static void
2891 threads_listing_context_remove (struct target_waitstatus *ws,
2892                                 struct threads_listing_context *context)
2893 {
2894   struct thread_item *item;
2895   int i;
2896   ptid_t child_ptid = ws->value.related_pid;
2897
2898   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2899     {
2900       if (ptid_equal (item->ptid, child_ptid))
2901         {
2902           VEC_ordered_remove (thread_item_t, context->items, i);
2903           break;
2904         }
2905     }
2906 }
2907
2908 static int
2909 remote_newthread_step (threadref *ref, void *data)
2910 {
2911   struct threads_listing_context *context
2912     = (struct threads_listing_context *) data;
2913   struct thread_item item;
2914   int pid = ptid_get_pid (inferior_ptid);
2915
2916   item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2917   item.core = -1;
2918   item.name = NULL;
2919   item.extra = NULL;
2920
2921   VEC_safe_push (thread_item_t, context->items, &item);
2922
2923   return 1;                     /* continue iterator */
2924 }
2925
2926 #define CRAZY_MAX_THREADS 1000
2927
2928 static ptid_t
2929 remote_current_thread (ptid_t oldpid)
2930 {
2931   struct remote_state *rs = get_remote_state ();
2932
2933   putpkt ("qC");
2934   getpkt (&rs->buf, &rs->buf_size, 0);
2935   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2936     {
2937       char *obuf;
2938       ptid_t result;
2939
2940       result = read_ptid (&rs->buf[2], &obuf);
2941       if (*obuf != '\0' && remote_debug)
2942         fprintf_unfiltered (gdb_stdlog,
2943                             "warning: garbage in qC reply\n");
2944
2945       return result;
2946     }
2947   else
2948     return oldpid;
2949 }
2950
2951 /* List remote threads using the deprecated qL packet.  */
2952
2953 static int
2954 remote_get_threads_with_ql (struct target_ops *ops,
2955                             struct threads_listing_context *context)
2956 {
2957   if (remote_threadlist_iterator (remote_newthread_step, context,
2958                                   CRAZY_MAX_THREADS) >= 0)
2959     return 1;
2960
2961   return 0;
2962 }
2963
2964 #if defined(HAVE_LIBEXPAT)
2965
2966 static void
2967 start_thread (struct gdb_xml_parser *parser,
2968               const struct gdb_xml_element *element,
2969               void *user_data, VEC(gdb_xml_value_s) *attributes)
2970 {
2971   struct threads_listing_context *data
2972     = (struct threads_listing_context *) user_data;
2973
2974   struct thread_item item;
2975   char *id;
2976   struct gdb_xml_value *attr;
2977
2978   id = (char *) xml_find_attribute (attributes, "id")->value;
2979   item.ptid = read_ptid (id, NULL);
2980
2981   attr = xml_find_attribute (attributes, "core");
2982   if (attr != NULL)
2983     item.core = *(ULONGEST *) attr->value;
2984   else
2985     item.core = -1;
2986
2987   attr = xml_find_attribute (attributes, "name");
2988   item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
2989
2990   item.extra = 0;
2991
2992   VEC_safe_push (thread_item_t, data->items, &item);
2993 }
2994
2995 static void
2996 end_thread (struct gdb_xml_parser *parser,
2997             const struct gdb_xml_element *element,
2998             void *user_data, const char *body_text)
2999 {
3000   struct threads_listing_context *data
3001     = (struct threads_listing_context *) user_data;
3002
3003   if (body_text && *body_text)
3004     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3005 }
3006
3007 const struct gdb_xml_attribute thread_attributes[] = {
3008   { "id", GDB_XML_AF_NONE, NULL, NULL },
3009   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3010   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3011   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3012 };
3013
3014 const struct gdb_xml_element thread_children[] = {
3015   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3016 };
3017
3018 const struct gdb_xml_element threads_children[] = {
3019   { "thread", thread_attributes, thread_children,
3020     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3021     start_thread, end_thread },
3022   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3023 };
3024
3025 const struct gdb_xml_element threads_elements[] = {
3026   { "threads", NULL, threads_children,
3027     GDB_XML_EF_NONE, NULL, NULL },
3028   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3029 };
3030
3031 #endif
3032
3033 /* List remote threads using qXfer:threads:read.  */
3034
3035 static int
3036 remote_get_threads_with_qxfer (struct target_ops *ops,
3037                                struct threads_listing_context *context)
3038 {
3039 #if defined(HAVE_LIBEXPAT)
3040   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3041     {
3042       char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3043       struct cleanup *back_to = make_cleanup (xfree, xml);
3044
3045       if (xml != NULL && *xml != '\0')
3046         {
3047           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3048                                threads_elements, xml, context);
3049         }
3050
3051       do_cleanups (back_to);
3052       return 1;
3053     }
3054 #endif
3055
3056   return 0;
3057 }
3058
3059 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3060
3061 static int
3062 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3063                                      struct threads_listing_context *context)
3064 {
3065   struct remote_state *rs = get_remote_state ();
3066
3067   if (rs->use_threadinfo_query)
3068     {
3069       char *bufp;
3070
3071       putpkt ("qfThreadInfo");
3072       getpkt (&rs->buf, &rs->buf_size, 0);
3073       bufp = rs->buf;
3074       if (bufp[0] != '\0')              /* q packet recognized */
3075         {
3076           while (*bufp++ == 'm')        /* reply contains one or more TID */
3077             {
3078               do
3079                 {
3080                   struct thread_item item;
3081
3082                   item.ptid = read_ptid (bufp, &bufp);
3083                   item.core = -1;
3084                   item.name = NULL;
3085                   item.extra = NULL;
3086
3087                   VEC_safe_push (thread_item_t, context->items, &item);
3088                 }
3089               while (*bufp++ == ',');   /* comma-separated list */
3090               putpkt ("qsThreadInfo");
3091               getpkt (&rs->buf, &rs->buf_size, 0);
3092               bufp = rs->buf;
3093             }
3094           return 1;
3095         }
3096       else
3097         {
3098           /* Packet not recognized.  */
3099           rs->use_threadinfo_query = 0;
3100         }
3101     }
3102
3103   return 0;
3104 }
3105
3106 /* Implement the to_update_thread_list function for the remote
3107    targets.  */
3108
3109 static void
3110 remote_update_thread_list (struct target_ops *ops)
3111 {
3112   struct remote_state *rs = get_remote_state ();
3113   struct threads_listing_context context;
3114   struct cleanup *old_chain;
3115   int got_list = 0;
3116
3117   context.items = NULL;
3118   old_chain = make_cleanup (clear_threads_listing_context, &context);
3119
3120   /* We have a few different mechanisms to fetch the thread list.  Try
3121      them all, starting with the most preferred one first, falling
3122      back to older methods.  */
3123   if (remote_get_threads_with_qxfer (ops, &context)
3124       || remote_get_threads_with_qthreadinfo (ops, &context)
3125       || remote_get_threads_with_ql (ops, &context))
3126     {
3127       int i;
3128       struct thread_item *item;
3129       struct thread_info *tp, *tmp;
3130
3131       got_list = 1;
3132
3133       if (VEC_empty (thread_item_t, context.items)
3134           && remote_thread_always_alive (ops, inferior_ptid))
3135         {
3136           /* Some targets don't really support threads, but still
3137              reply an (empty) thread list in response to the thread
3138              listing packets, instead of replying "packet not
3139              supported".  Exit early so we don't delete the main
3140              thread.  */
3141           do_cleanups (old_chain);
3142           return;
3143         }
3144
3145       /* CONTEXT now holds the current thread list on the remote
3146          target end.  Delete GDB-side threads no longer found on the
3147          target.  */
3148       ALL_THREADS_SAFE (tp, tmp)
3149         {
3150           for (i = 0;
3151                VEC_iterate (thread_item_t, context.items, i, item);
3152                ++i)
3153             {
3154               if (ptid_equal (item->ptid, tp->ptid))
3155                 break;
3156             }
3157
3158           if (i == VEC_length (thread_item_t, context.items))
3159             {
3160               /* Not found.  */
3161               delete_thread (tp->ptid);
3162             }
3163         }
3164
3165       /* Remove any unreported fork child threads from CONTEXT so
3166          that we don't interfere with follow fork, which is where
3167          creation of such threads is handled.  */
3168       remove_new_fork_children (&context);
3169
3170       /* And now add threads we don't know about yet to our list.  */
3171       for (i = 0;
3172            VEC_iterate (thread_item_t, context.items, i, item);
3173            ++i)
3174         {
3175           if (!ptid_equal (item->ptid, null_ptid))
3176             {
3177               struct private_thread_info *info;
3178               /* In non-stop mode, we assume new found threads are
3179                  running until proven otherwise with a stop reply.  In
3180                  all-stop, we can only get here if all threads are
3181                  stopped.  */
3182               int running = target_is_non_stop_p () ? 1 : 0;
3183
3184               remote_notice_new_inferior (item->ptid, running);
3185
3186               info = demand_private_info (item->ptid);
3187               info->core = item->core;
3188               info->extra = item->extra;
3189               item->extra = NULL;
3190               info->name = item->name;
3191               item->name = NULL;
3192             }
3193         }
3194     }
3195
3196   if (!got_list)
3197     {
3198       /* If no thread listing method is supported, then query whether
3199          each known thread is alive, one by one, with the T packet.
3200          If the target doesn't support threads at all, then this is a
3201          no-op.  See remote_thread_alive.  */
3202       prune_threads ();
3203     }
3204
3205   do_cleanups (old_chain);
3206 }
3207
3208 /*
3209  * Collect a descriptive string about the given thread.
3210  * The target may say anything it wants to about the thread
3211  * (typically info about its blocked / runnable state, name, etc.).
3212  * This string will appear in the info threads display.
3213  *
3214  * Optional: targets are not required to implement this function.
3215  */
3216
3217 static char *
3218 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3219 {
3220   struct remote_state *rs = get_remote_state ();
3221   int result;
3222   int set;
3223   threadref id;
3224   struct gdb_ext_thread_info threadinfo;
3225   static char display_buf[100]; /* arbitrary...  */
3226   int n = 0;                    /* position in display_buf */
3227
3228   if (rs->remote_desc == 0)             /* paranoia */
3229     internal_error (__FILE__, __LINE__,
3230                     _("remote_threads_extra_info"));
3231
3232   if (ptid_equal (tp->ptid, magic_null_ptid)
3233       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3234     /* This is the main thread which was added by GDB.  The remote
3235        server doesn't know about it.  */
3236     return NULL;
3237
3238   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3239     {
3240       struct thread_info *info = find_thread_ptid (tp->ptid);
3241
3242       if (info && info->priv)
3243         return info->priv->extra;
3244       else
3245         return NULL;
3246     }
3247
3248   if (rs->use_threadextra_query)
3249     {
3250       char *b = rs->buf;
3251       char *endb = rs->buf + get_remote_packet_size ();
3252
3253       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3254       b += strlen (b);
3255       write_ptid (b, endb, tp->ptid);
3256
3257       putpkt (rs->buf);
3258       getpkt (&rs->buf, &rs->buf_size, 0);
3259       if (rs->buf[0] != 0)
3260         {
3261           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3262           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3263           display_buf [result] = '\0';
3264           return display_buf;
3265         }
3266     }
3267
3268   /* If the above query fails, fall back to the old method.  */
3269   rs->use_threadextra_query = 0;
3270   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3271     | TAG_MOREDISPLAY | TAG_DISPLAY;
3272   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3273   if (remote_get_threadinfo (&id, set, &threadinfo))
3274     if (threadinfo.active)
3275       {
3276         if (*threadinfo.shortname)
3277           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3278                           " Name: %s,", threadinfo.shortname);
3279         if (*threadinfo.display)
3280           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3281                           " State: %s,", threadinfo.display);
3282         if (*threadinfo.more_display)
3283           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3284                           " Priority: %s", threadinfo.more_display);
3285
3286         if (n > 0)
3287           {
3288             /* For purely cosmetic reasons, clear up trailing commas.  */
3289             if (',' == display_buf[n-1])
3290               display_buf[n-1] = ' ';
3291             return display_buf;
3292           }
3293       }
3294   return NULL;
3295 }
3296 \f
3297
3298 static int
3299 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3300                                     struct static_tracepoint_marker *marker)
3301 {
3302   struct remote_state *rs = get_remote_state ();
3303   char *p = rs->buf;
3304
3305   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3306   p += strlen (p);
3307   p += hexnumstr (p, addr);
3308   putpkt (rs->buf);
3309   getpkt (&rs->buf, &rs->buf_size, 0);
3310   p = rs->buf;
3311
3312   if (*p == 'E')
3313     error (_("Remote failure reply: %s"), p);
3314
3315   if (*p++ == 'm')
3316     {
3317       parse_static_tracepoint_marker_definition (p, &p, marker);
3318       return 1;
3319     }
3320
3321   return 0;
3322 }
3323
3324 static VEC(static_tracepoint_marker_p) *
3325 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3326                                            const char *strid)
3327 {
3328   struct remote_state *rs = get_remote_state ();
3329   VEC(static_tracepoint_marker_p) *markers = NULL;
3330   struct static_tracepoint_marker *marker = NULL;
3331   struct cleanup *old_chain;
3332   char *p;
3333
3334   /* Ask for a first packet of static tracepoint marker
3335      definition.  */
3336   putpkt ("qTfSTM");
3337   getpkt (&rs->buf, &rs->buf_size, 0);
3338   p = rs->buf;
3339   if (*p == 'E')
3340     error (_("Remote failure reply: %s"), p);
3341
3342   old_chain = make_cleanup (free_current_marker, &marker);
3343
3344   while (*p++ == 'm')
3345     {
3346       if (marker == NULL)
3347         marker = XCNEW (struct static_tracepoint_marker);
3348
3349       do
3350         {
3351           parse_static_tracepoint_marker_definition (p, &p, marker);
3352
3353           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3354             {
3355               VEC_safe_push (static_tracepoint_marker_p,
3356                              markers, marker);
3357               marker = NULL;
3358             }
3359           else
3360             {
3361               release_static_tracepoint_marker (marker);
3362               memset (marker, 0, sizeof (*marker));
3363             }
3364         }
3365       while (*p++ == ',');      /* comma-separated list */
3366       /* Ask for another packet of static tracepoint definition.  */
3367       putpkt ("qTsSTM");
3368       getpkt (&rs->buf, &rs->buf_size, 0);
3369       p = rs->buf;
3370     }
3371
3372   do_cleanups (old_chain);
3373   return markers;
3374 }
3375
3376 \f
3377 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3378
3379 static ptid_t
3380 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3381 {
3382   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3383 }
3384 \f
3385
3386 /* Restart the remote side; this is an extended protocol operation.  */
3387
3388 static void
3389 extended_remote_restart (void)
3390 {
3391   struct remote_state *rs = get_remote_state ();
3392
3393   /* Send the restart command; for reasons I don't understand the
3394      remote side really expects a number after the "R".  */
3395   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3396   putpkt (rs->buf);
3397
3398   remote_fileio_reset ();
3399 }
3400 \f
3401 /* Clean up connection to a remote debugger.  */
3402
3403 static void
3404 remote_close (struct target_ops *self)
3405 {
3406   struct remote_state *rs = get_remote_state ();
3407
3408   if (rs->remote_desc == NULL)
3409     return; /* already closed */
3410
3411   /* Make sure we leave stdin registered in the event loop, and we
3412      don't leave the async SIGINT signal handler installed.  */
3413   remote_terminal_ours (self);
3414
3415   serial_close (rs->remote_desc);
3416   rs->remote_desc = NULL;
3417
3418   /* We don't have a connection to the remote stub anymore.  Get rid
3419      of all the inferiors and their threads we were controlling.
3420      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3421      will be unable to find the thread corresponding to (pid, 0, 0).  */
3422   inferior_ptid = null_ptid;
3423   discard_all_inferiors ();
3424
3425   /* We are closing the remote target, so we should discard
3426      everything of this target.  */
3427   discard_pending_stop_replies_in_queue (rs);
3428
3429   if (remote_async_inferior_event_token)
3430     delete_async_event_handler (&remote_async_inferior_event_token);
3431
3432   remote_notif_state_xfree (rs->notif_state);
3433
3434   trace_reset_local_state ();
3435 }
3436
3437 /* Query the remote side for the text, data and bss offsets.  */
3438
3439 static void
3440 get_offsets (void)
3441 {
3442   struct remote_state *rs = get_remote_state ();
3443   char *buf;
3444   char *ptr;
3445   int lose, num_segments = 0, do_sections, do_segments;
3446   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3447   struct section_offsets *offs;
3448   struct symfile_segment_data *data;
3449
3450   if (symfile_objfile == NULL)
3451     return;
3452
3453   putpkt ("qOffsets");
3454   getpkt (&rs->buf, &rs->buf_size, 0);
3455   buf = rs->buf;
3456
3457   if (buf[0] == '\000')
3458     return;                     /* Return silently.  Stub doesn't support
3459                                    this command.  */
3460   if (buf[0] == 'E')
3461     {
3462       warning (_("Remote failure reply: %s"), buf);
3463       return;
3464     }
3465
3466   /* Pick up each field in turn.  This used to be done with scanf, but
3467      scanf will make trouble if CORE_ADDR size doesn't match
3468      conversion directives correctly.  The following code will work
3469      with any size of CORE_ADDR.  */
3470   text_addr = data_addr = bss_addr = 0;
3471   ptr = buf;
3472   lose = 0;
3473
3474   if (startswith (ptr, "Text="))
3475     {
3476       ptr += 5;
3477       /* Don't use strtol, could lose on big values.  */
3478       while (*ptr && *ptr != ';')
3479         text_addr = (text_addr << 4) + fromhex (*ptr++);
3480
3481       if (startswith (ptr, ";Data="))
3482         {
3483           ptr += 6;
3484           while (*ptr && *ptr != ';')
3485             data_addr = (data_addr << 4) + fromhex (*ptr++);
3486         }
3487       else
3488         lose = 1;
3489
3490       if (!lose && startswith (ptr, ";Bss="))
3491         {
3492           ptr += 5;
3493           while (*ptr && *ptr != ';')
3494             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3495
3496           if (bss_addr != data_addr)
3497             warning (_("Target reported unsupported offsets: %s"), buf);
3498         }
3499       else
3500         lose = 1;
3501     }
3502   else if (startswith (ptr, "TextSeg="))
3503     {
3504       ptr += 8;
3505       /* Don't use strtol, could lose on big values.  */
3506       while (*ptr && *ptr != ';')
3507         text_addr = (text_addr << 4) + fromhex (*ptr++);
3508       num_segments = 1;
3509
3510       if (startswith (ptr, ";DataSeg="))
3511         {
3512           ptr += 9;
3513           while (*ptr && *ptr != ';')
3514             data_addr = (data_addr << 4) + fromhex (*ptr++);
3515           num_segments++;
3516         }
3517     }
3518   else
3519     lose = 1;
3520
3521   if (lose)
3522     error (_("Malformed response to offset query, %s"), buf);
3523   else if (*ptr != '\0')
3524     warning (_("Target reported unsupported offsets: %s"), buf);
3525
3526   offs = ((struct section_offsets *)
3527           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3528   memcpy (offs, symfile_objfile->section_offsets,
3529           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3530
3531   data = get_symfile_segment_data (symfile_objfile->obfd);
3532   do_segments = (data != NULL);
3533   do_sections = num_segments == 0;
3534
3535   if (num_segments > 0)
3536     {
3537       segments[0] = text_addr;
3538       segments[1] = data_addr;
3539     }
3540   /* If we have two segments, we can still try to relocate everything
3541      by assuming that the .text and .data offsets apply to the whole
3542      text and data segments.  Convert the offsets given in the packet
3543      to base addresses for symfile_map_offsets_to_segments.  */
3544   else if (data && data->num_segments == 2)
3545     {
3546       segments[0] = data->segment_bases[0] + text_addr;
3547       segments[1] = data->segment_bases[1] + data_addr;
3548       num_segments = 2;
3549     }
3550   /* If the object file has only one segment, assume that it is text
3551      rather than data; main programs with no writable data are rare,
3552      but programs with no code are useless.  Of course the code might
3553      have ended up in the data segment... to detect that we would need
3554      the permissions here.  */
3555   else if (data && data->num_segments == 1)
3556     {
3557       segments[0] = data->segment_bases[0] + text_addr;
3558       num_segments = 1;
3559     }
3560   /* There's no way to relocate by segment.  */
3561   else
3562     do_segments = 0;
3563
3564   if (do_segments)
3565     {
3566       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3567                                                  offs, num_segments, segments);
3568
3569       if (ret == 0 && !do_sections)
3570         error (_("Can not handle qOffsets TextSeg "
3571                  "response with this symbol file"));
3572
3573       if (ret > 0)
3574         do_sections = 0;
3575     }
3576
3577   if (data)
3578     free_symfile_segment_data (data);
3579
3580   if (do_sections)
3581     {
3582       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3583
3584       /* This is a temporary kludge to force data and bss to use the
3585          same offsets because that's what nlmconv does now.  The real
3586          solution requires changes to the stub and remote.c that I
3587          don't have time to do right now.  */
3588
3589       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3590       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3591     }
3592
3593   objfile_relocate (symfile_objfile, offs);
3594 }
3595
3596 /* Send interrupt_sequence to remote target.  */
3597 static void
3598 send_interrupt_sequence (void)
3599 {
3600   struct remote_state *rs = get_remote_state ();
3601
3602   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3603     remote_serial_write ("\x03", 1);
3604   else if (interrupt_sequence_mode == interrupt_sequence_break)
3605     serial_send_break (rs->remote_desc);
3606   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3607     {
3608       serial_send_break (rs->remote_desc);
3609       remote_serial_write ("g", 1);
3610     }
3611   else
3612     internal_error (__FILE__, __LINE__,
3613                     _("Invalid value for interrupt_sequence_mode: %s."),
3614                     interrupt_sequence_mode);
3615 }
3616
3617
3618 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3619    and extract the PTID.  Returns NULL_PTID if not found.  */
3620
3621 static ptid_t
3622 stop_reply_extract_thread (char *stop_reply)
3623 {
3624   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3625     {
3626       char *p;
3627
3628       /* Txx r:val ; r:val (...)  */
3629       p = &stop_reply[3];
3630
3631       /* Look for "register" named "thread".  */
3632       while (*p != '\0')
3633         {
3634           char *p1;
3635
3636           p1 = strchr (p, ':');
3637           if (p1 == NULL)
3638             return null_ptid;
3639
3640           if (strncmp (p, "thread", p1 - p) == 0)
3641             return read_ptid (++p1, &p);
3642
3643           p1 = strchr (p, ';');
3644           if (p1 == NULL)
3645             return null_ptid;
3646           p1++;
3647
3648           p = p1;
3649         }
3650     }
3651
3652   return null_ptid;
3653 }
3654
3655 /* Determine the remote side's current thread.  If we have a stop
3656    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3657    "thread" register we can extract the current thread from.  If not,
3658    ask the remote which is the current thread with qC.  The former
3659    method avoids a roundtrip.  */
3660
3661 static ptid_t
3662 get_current_thread (char *wait_status)
3663 {
3664   ptid_t ptid = null_ptid;
3665
3666   /* Note we don't use remote_parse_stop_reply as that makes use of
3667      the target architecture, which we haven't yet fully determined at
3668      this point.  */
3669   if (wait_status != NULL)
3670     ptid = stop_reply_extract_thread (wait_status);
3671   if (ptid_equal (ptid, null_ptid))
3672     ptid = remote_current_thread (inferior_ptid);
3673
3674   return ptid;
3675 }
3676
3677 /* Query the remote target for which is the current thread/process,
3678    add it to our tables, and update INFERIOR_PTID.  The caller is
3679    responsible for setting the state such that the remote end is ready
3680    to return the current thread.
3681
3682    This function is called after handling the '?' or 'vRun' packets,
3683    whose response is a stop reply from which we can also try
3684    extracting the thread.  If the target doesn't support the explicit
3685    qC query, we infer the current thread from that stop reply, passed
3686    in in WAIT_STATUS, which may be NULL.  */
3687
3688 static void
3689 add_current_inferior_and_thread (char *wait_status)
3690 {
3691   struct remote_state *rs = get_remote_state ();
3692   int fake_pid_p = 0;
3693   ptid_t ptid;
3694
3695   inferior_ptid = null_ptid;
3696
3697   /* Now, if we have thread information, update inferior_ptid.  */
3698   ptid = get_current_thread (wait_status);
3699
3700   if (!ptid_equal (ptid, null_ptid))
3701     {
3702       if (!remote_multi_process_p (rs))
3703         fake_pid_p = 1;
3704
3705       inferior_ptid = ptid;
3706     }
3707   else
3708     {
3709       /* Without this, some commands which require an active target
3710          (such as kill) won't work.  This variable serves (at least)
3711          double duty as both the pid of the target process (if it has
3712          such), and as a flag indicating that a target is active.  */
3713       inferior_ptid = magic_null_ptid;
3714       fake_pid_p = 1;
3715     }
3716
3717   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3718
3719   /* Add the main thread.  */
3720   add_thread_silent (inferior_ptid);
3721 }
3722
3723 /* Print info about a thread that was found already stopped on
3724    connection.  */
3725
3726 static void
3727 print_one_stopped_thread (struct thread_info *thread)
3728 {
3729   struct target_waitstatus *ws = &thread->suspend.waitstatus;
3730
3731   switch_to_thread (thread->ptid);
3732   stop_pc = get_frame_pc (get_current_frame ());
3733   set_current_sal_from_frame (get_current_frame ());
3734
3735   thread->suspend.waitstatus_pending_p = 0;
3736
3737   if (ws->kind == TARGET_WAITKIND_STOPPED)
3738     {
3739       enum gdb_signal sig = ws->value.sig;
3740
3741       if (signal_print_state (sig))
3742         observer_notify_signal_received (sig);
3743     }
3744   observer_notify_normal_stop (NULL, 1);
3745 }
3746
3747 /* Process all initial stop replies the remote side sent in response
3748    to the ? packet.  These indicate threads that were already stopped
3749    on initial connection.  We mark these threads as stopped and print
3750    their current frame before giving the user the prompt.  */
3751
3752 static void
3753 process_initial_stop_replies (int from_tty)
3754 {
3755   int pending_stop_replies = stop_reply_queue_length ();
3756   struct inferior *inf;
3757   struct thread_info *thread;
3758   struct thread_info *selected = NULL;
3759   struct thread_info *lowest_stopped = NULL;
3760   struct thread_info *first = NULL;
3761
3762   /* Consume the initial pending events.  */
3763   while (pending_stop_replies-- > 0)
3764     {
3765       ptid_t waiton_ptid = minus_one_ptid;
3766       ptid_t event_ptid;
3767       struct target_waitstatus ws;
3768       int ignore_event = 0;
3769       struct thread_info *thread;
3770
3771       memset (&ws, 0, sizeof (ws));
3772       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3773       if (remote_debug)
3774         print_target_wait_results (waiton_ptid, event_ptid, &ws);
3775
3776       switch (ws.kind)
3777         {
3778         case TARGET_WAITKIND_IGNORE:
3779         case TARGET_WAITKIND_NO_RESUMED:
3780         case TARGET_WAITKIND_SIGNALLED:
3781         case TARGET_WAITKIND_EXITED:
3782           /* We shouldn't see these, but if we do, just ignore.  */
3783           if (remote_debug)
3784             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3785           ignore_event = 1;
3786           break;
3787
3788         case TARGET_WAITKIND_EXECD:
3789           xfree (ws.value.execd_pathname);
3790           break;
3791         default:
3792           break;
3793         }
3794
3795       if (ignore_event)
3796         continue;
3797
3798       thread = find_thread_ptid (event_ptid);
3799
3800       if (ws.kind == TARGET_WAITKIND_STOPPED)
3801         {
3802           enum gdb_signal sig = ws.value.sig;
3803
3804           /* Stubs traditionally report SIGTRAP as initial signal,
3805              instead of signal 0.  Suppress it.  */
3806           if (sig == GDB_SIGNAL_TRAP)
3807             sig = GDB_SIGNAL_0;
3808           thread->suspend.stop_signal = sig;
3809           ws.value.sig = sig;
3810         }
3811
3812       thread->suspend.waitstatus = ws;
3813
3814       if (ws.kind != TARGET_WAITKIND_STOPPED
3815           || ws.value.sig != GDB_SIGNAL_0)
3816         thread->suspend.waitstatus_pending_p = 1;
3817
3818       set_executing (event_ptid, 0);
3819       set_running (event_ptid, 0);
3820     }
3821
3822   /* "Notice" the new inferiors before anything related to
3823      registers/memory.  */
3824   ALL_INFERIORS (inf)
3825     {
3826       if (inf->pid == 0)
3827         continue;
3828
3829       inf->needs_setup = 1;
3830
3831       if (non_stop)
3832         {
3833           thread = any_live_thread_of_process (inf->pid);
3834           notice_new_inferior (thread->ptid,
3835                                thread->state == THREAD_RUNNING,
3836                                from_tty);
3837         }
3838     }
3839
3840   /* If all-stop on top of non-stop, pause all threads.  Note this
3841      records the threads' stop pc, so must be done after "noticing"
3842      the inferiors.  */
3843   if (!non_stop)
3844     {
3845       stop_all_threads ();
3846
3847       /* If all threads of an inferior were already stopped, we
3848          haven't setup the inferior yet.  */
3849       ALL_INFERIORS (inf)
3850         {
3851           if (inf->pid == 0)
3852             continue;
3853
3854           if (inf->needs_setup)
3855             {
3856               thread = any_live_thread_of_process (inf->pid);
3857               switch_to_thread_no_regs (thread);
3858               setup_inferior (0);
3859             }
3860         }
3861     }
3862
3863   /* Now go over all threads that are stopped, and print their current
3864      frame.  If all-stop, then if there's a signalled thread, pick
3865      that as current.  */
3866   ALL_NON_EXITED_THREADS (thread)
3867     {
3868       struct target_waitstatus *ws;
3869
3870       if (first == NULL)
3871         first = thread;
3872
3873       if (!non_stop)
3874         set_running (thread->ptid, 0);
3875       else if (thread->state != THREAD_STOPPED)
3876         continue;
3877
3878       ws = &thread->suspend.waitstatus;
3879
3880       if (selected == NULL
3881           && thread->suspend.waitstatus_pending_p)
3882         selected = thread;
3883
3884       if (lowest_stopped == NULL || thread->num < lowest_stopped->num)
3885         lowest_stopped = thread;
3886
3887       if (non_stop)
3888         print_one_stopped_thread (thread);
3889     }
3890
3891   /* In all-stop, we only print the status of one thread, and leave
3892      others with their status pending.  */
3893   if (!non_stop)
3894     {
3895       thread = selected;
3896       if (thread == NULL)
3897         thread = lowest_stopped;
3898       if (thread == NULL)
3899         thread = first;
3900
3901       print_one_stopped_thread (thread);
3902     }
3903
3904   /* For "info program".  */
3905   thread = inferior_thread ();
3906   if (thread->state == THREAD_STOPPED)
3907     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
3908 }
3909
3910 static void
3911 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3912 {
3913   struct remote_state *rs = get_remote_state ();
3914   struct packet_config *noack_config;
3915   char *wait_status = NULL;
3916
3917   immediate_quit++;             /* Allow user to interrupt it.  */
3918   QUIT;
3919
3920   if (interrupt_on_connect)
3921     send_interrupt_sequence ();
3922
3923   /* Ack any packet which the remote side has already sent.  */
3924   serial_write (rs->remote_desc, "+", 1);
3925
3926   /* Signal other parts that we're going through the initial setup,
3927      and so things may not be stable yet.  */
3928   rs->starting_up = 1;
3929
3930   /* The first packet we send to the target is the optional "supported
3931      packets" request.  If the target can answer this, it will tell us
3932      which later probes to skip.  */
3933   remote_query_supported ();
3934
3935   /* If the stub wants to get a QAllow, compose one and send it.  */
3936   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3937     remote_set_permissions (target);
3938
3939   /* Next, we possibly activate noack mode.
3940
3941      If the QStartNoAckMode packet configuration is set to AUTO,
3942      enable noack mode if the stub reported a wish for it with
3943      qSupported.
3944
3945      If set to TRUE, then enable noack mode even if the stub didn't
3946      report it in qSupported.  If the stub doesn't reply OK, the
3947      session ends with an error.
3948
3949      If FALSE, then don't activate noack mode, regardless of what the
3950      stub claimed should be the default with qSupported.  */
3951
3952   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3953   if (packet_config_support (noack_config) != PACKET_DISABLE)
3954     {
3955       putpkt ("QStartNoAckMode");
3956       getpkt (&rs->buf, &rs->buf_size, 0);
3957       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3958         rs->noack_mode = 1;
3959     }
3960
3961   if (extended_p)
3962     {
3963       /* Tell the remote that we are using the extended protocol.  */
3964       putpkt ("!");
3965       getpkt (&rs->buf, &rs->buf_size, 0);
3966     }
3967
3968   /* Let the target know which signals it is allowed to pass down to
3969      the program.  */
3970   update_signals_program_target ();
3971
3972   /* Next, if the target can specify a description, read it.  We do
3973      this before anything involving memory or registers.  */
3974   target_find_description ();
3975
3976   /* Next, now that we know something about the target, update the
3977      address spaces in the program spaces.  */
3978   update_address_spaces ();
3979
3980   /* On OSs where the list of libraries is global to all
3981      processes, we fetch them early.  */
3982   if (gdbarch_has_global_solist (target_gdbarch ()))
3983     solib_add (NULL, from_tty, target, auto_solib_add);
3984
3985   if (target_is_non_stop_p ())
3986     {
3987       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3988         error (_("Non-stop mode requested, but remote "
3989                  "does not support non-stop"));
3990
3991       putpkt ("QNonStop:1");
3992       getpkt (&rs->buf, &rs->buf_size, 0);
3993
3994       if (strcmp (rs->buf, "OK") != 0)
3995         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3996
3997       /* Find about threads and processes the stub is already
3998          controlling.  We default to adding them in the running state.
3999          The '?' query below will then tell us about which threads are
4000          stopped.  */
4001       remote_update_thread_list (target);
4002     }
4003   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4004     {
4005       /* Don't assume that the stub can operate in all-stop mode.
4006          Request it explicitly.  */
4007       putpkt ("QNonStop:0");
4008       getpkt (&rs->buf, &rs->buf_size, 0);
4009
4010       if (strcmp (rs->buf, "OK") != 0)
4011         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4012     }
4013
4014   /* Upload TSVs regardless of whether the target is running or not.  The
4015      remote stub, such as GDBserver, may have some predefined or builtin
4016      TSVs, even if the target is not running.  */
4017   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4018     {
4019       struct uploaded_tsv *uploaded_tsvs = NULL;
4020
4021       remote_upload_trace_state_variables (target, &uploaded_tsvs);
4022       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4023     }
4024
4025   /* Check whether the target is running now.  */
4026   putpkt ("?");
4027   getpkt (&rs->buf, &rs->buf_size, 0);
4028
4029   if (!target_is_non_stop_p ())
4030     {
4031       ptid_t ptid;
4032       int fake_pid_p = 0;
4033       struct inferior *inf;
4034
4035       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4036         {
4037           if (!extended_p)
4038             error (_("The target is not running (try extended-remote?)"));
4039
4040           /* We're connected, but not running.  Drop out before we
4041              call start_remote.  */
4042           rs->starting_up = 0;
4043           return;
4044         }
4045       else
4046         {
4047           /* Save the reply for later.  */
4048           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4049           strcpy (wait_status, rs->buf);
4050         }
4051
4052       /* Fetch thread list.  */
4053       target_update_thread_list ();
4054
4055       /* Let the stub know that we want it to return the thread.  */
4056       set_continue_thread (minus_one_ptid);
4057
4058       if (thread_count () == 0)
4059         {
4060           /* Target has no concept of threads at all.  GDB treats
4061              non-threaded target as single-threaded; add a main
4062              thread.  */
4063           add_current_inferior_and_thread (wait_status);
4064         }
4065       else
4066         {
4067           /* We have thread information; select the thread the target
4068              says should be current.  If we're reconnecting to a
4069              multi-threaded program, this will ideally be the thread
4070              that last reported an event before GDB disconnected.  */
4071           inferior_ptid = get_current_thread (wait_status);
4072           if (ptid_equal (inferior_ptid, null_ptid))
4073             {
4074               /* Odd... The target was able to list threads, but not
4075                  tell us which thread was current (no "thread"
4076                  register in T stop reply?).  Just pick the first
4077                  thread in the thread list then.  */
4078               
4079               if (remote_debug)
4080                 fprintf_unfiltered (gdb_stdlog,
4081                                     "warning: couldn't determine remote "
4082                                     "current thread; picking first in list.\n");
4083
4084               inferior_ptid = thread_list->ptid;
4085             }
4086         }
4087
4088       /* init_wait_for_inferior should be called before get_offsets in order
4089          to manage `inserted' flag in bp loc in a correct state.
4090          breakpoint_init_inferior, called from init_wait_for_inferior, set
4091          `inserted' flag to 0, while before breakpoint_re_set, called from
4092          start_remote, set `inserted' flag to 1.  In the initialization of
4093          inferior, breakpoint_init_inferior should be called first, and then
4094          breakpoint_re_set can be called.  If this order is broken, state of
4095          `inserted' flag is wrong, and cause some problems on breakpoint
4096          manipulation.  */
4097       init_wait_for_inferior ();
4098
4099       get_offsets ();           /* Get text, data & bss offsets.  */
4100
4101       /* If we could not find a description using qXfer, and we know
4102          how to do it some other way, try again.  This is not
4103          supported for non-stop; it could be, but it is tricky if
4104          there are no stopped threads when we connect.  */
4105       if (remote_read_description_p (target)
4106           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4107         {
4108           target_clear_description ();
4109           target_find_description ();
4110         }
4111
4112       /* Use the previously fetched status.  */
4113       gdb_assert (wait_status != NULL);
4114       strcpy (rs->buf, wait_status);
4115       rs->cached_wait_status = 1;
4116
4117       immediate_quit--;
4118       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4119     }
4120   else
4121     {
4122       /* Clear WFI global state.  Do this before finding about new
4123          threads and inferiors, and setting the current inferior.
4124          Otherwise we would clear the proceed status of the current
4125          inferior when we want its stop_soon state to be preserved
4126          (see notice_new_inferior).  */
4127       init_wait_for_inferior ();
4128
4129       /* In non-stop, we will either get an "OK", meaning that there
4130          are no stopped threads at this time; or, a regular stop
4131          reply.  In the latter case, there may be more than one thread
4132          stopped --- we pull them all out using the vStopped
4133          mechanism.  */
4134       if (strcmp (rs->buf, "OK") != 0)
4135         {
4136           struct notif_client *notif = &notif_client_stop;
4137
4138           /* remote_notif_get_pending_replies acks this one, and gets
4139              the rest out.  */
4140           rs->notif_state->pending_event[notif_client_stop.id]
4141             = remote_notif_parse (notif, rs->buf);
4142           remote_notif_get_pending_events (notif);
4143         }
4144
4145       if (thread_count () == 0)
4146         {
4147           if (!extended_p)
4148             error (_("The target is not running (try extended-remote?)"));
4149
4150           /* We're connected, but not running.  Drop out before we
4151              call start_remote.  */
4152           rs->starting_up = 0;
4153           return;
4154         }
4155
4156       /* In non-stop mode, any cached wait status will be stored in
4157          the stop reply queue.  */
4158       gdb_assert (wait_status == NULL);
4159
4160       /* Report all signals during attach/startup.  */
4161       remote_pass_signals (target, 0, NULL);
4162
4163       /* If there are already stopped threads, mark them stopped and
4164          report their stops before giving the prompt to the user.  */
4165       process_initial_stop_replies (from_tty);
4166
4167       if (target_can_async_p ())
4168         target_async (1);
4169     }
4170
4171   /* If we connected to a live target, do some additional setup.  */
4172   if (target_has_execution)
4173     {
4174       if (symfile_objfile)      /* No use without a symbol-file.  */
4175         remote_check_symbols ();
4176     }
4177
4178   /* Possibly the target has been engaged in a trace run started
4179      previously; find out where things are at.  */
4180   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4181     {
4182       struct uploaded_tp *uploaded_tps = NULL;
4183
4184       if (current_trace_status ()->running)
4185         printf_filtered (_("Trace is already running on the target.\n"));
4186
4187       remote_upload_tracepoints (target, &uploaded_tps);
4188
4189       merge_uploaded_tracepoints (&uploaded_tps);
4190     }
4191
4192   /* The thread and inferior lists are now synchronized with the
4193      target, our symbols have been relocated, and we're merged the
4194      target's tracepoints with ours.  We're done with basic start
4195      up.  */
4196   rs->starting_up = 0;
4197
4198   /* Maybe breakpoints are global and need to be inserted now.  */
4199   if (breakpoints_should_be_inserted_now ())
4200     insert_breakpoints ();
4201 }
4202
4203 /* Open a connection to a remote debugger.
4204    NAME is the filename used for communication.  */
4205
4206 static void
4207 remote_open (const char *name, int from_tty)
4208 {
4209   remote_open_1 (name, from_tty, &remote_ops, 0);
4210 }
4211
4212 /* Open a connection to a remote debugger using the extended
4213    remote gdb protocol.  NAME is the filename used for communication.  */
4214
4215 static void
4216 extended_remote_open (const char *name, int from_tty)
4217 {
4218   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4219 }
4220
4221 /* Reset all packets back to "unknown support".  Called when opening a
4222    new connection to a remote target.  */
4223
4224 static void
4225 reset_all_packet_configs_support (void)
4226 {
4227   int i;
4228
4229   for (i = 0; i < PACKET_MAX; i++)
4230     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4231 }
4232
4233 /* Initialize all packet configs.  */
4234
4235 static void
4236 init_all_packet_configs (void)
4237 {
4238   int i;
4239
4240   for (i = 0; i < PACKET_MAX; i++)
4241     {
4242       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4243       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4244     }
4245 }
4246
4247 /* Symbol look-up.  */
4248
4249 static void
4250 remote_check_symbols (void)
4251 {
4252   struct remote_state *rs = get_remote_state ();
4253   char *msg, *reply, *tmp;
4254   struct bound_minimal_symbol sym;
4255   int end;
4256   struct cleanup *old_chain;
4257
4258   /* The remote side has no concept of inferiors that aren't running
4259      yet, it only knows about running processes.  If we're connected
4260      but our current inferior is not running, we should not invite the
4261      remote target to request symbol lookups related to its
4262      (unrelated) current process.  */
4263   if (!target_has_execution)
4264     return;
4265
4266   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4267     return;
4268
4269   /* Make sure the remote is pointing at the right process.  Note
4270      there's no way to select "no process".  */
4271   set_general_process ();
4272
4273   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4274      because we need both at the same time.  */
4275   msg = (char *) xmalloc (get_remote_packet_size ());
4276   old_chain = make_cleanup (xfree, msg);
4277
4278   /* Invite target to request symbol lookups.  */
4279
4280   putpkt ("qSymbol::");
4281   getpkt (&rs->buf, &rs->buf_size, 0);
4282   packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4283   reply = rs->buf;
4284
4285   while (startswith (reply, "qSymbol:"))
4286     {
4287       struct bound_minimal_symbol sym;
4288
4289       tmp = &reply[8];
4290       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4291       msg[end] = '\0';
4292       sym = lookup_minimal_symbol (msg, NULL, NULL);
4293       if (sym.minsym == NULL)
4294         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4295       else
4296         {
4297           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4298           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4299
4300           /* If this is a function address, return the start of code
4301              instead of any data function descriptor.  */
4302           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4303                                                          sym_addr,
4304                                                          &current_target);
4305
4306           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4307                      phex_nz (sym_addr, addr_size), &reply[8]);
4308         }
4309   
4310       putpkt (msg);
4311       getpkt (&rs->buf, &rs->buf_size, 0);
4312       reply = rs->buf;
4313     }
4314
4315   do_cleanups (old_chain);
4316 }
4317
4318 static struct serial *
4319 remote_serial_open (const char *name)
4320 {
4321   static int udp_warning = 0;
4322
4323   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4324      of in ser-tcp.c, because it is the remote protocol assuming that the
4325      serial connection is reliable and not the serial connection promising
4326      to be.  */
4327   if (!udp_warning && startswith (name, "udp:"))
4328     {
4329       warning (_("The remote protocol may be unreliable over UDP.\n"
4330                  "Some events may be lost, rendering further debugging "
4331                  "impossible."));
4332       udp_warning = 1;
4333     }
4334
4335   return serial_open (name);
4336 }
4337
4338 /* Inform the target of our permission settings.  The permission flags
4339    work without this, but if the target knows the settings, it can do
4340    a couple things.  First, it can add its own check, to catch cases
4341    that somehow manage to get by the permissions checks in target
4342    methods.  Second, if the target is wired to disallow particular
4343    settings (for instance, a system in the field that is not set up to
4344    be able to stop at a breakpoint), it can object to any unavailable
4345    permissions.  */
4346
4347 void
4348 remote_set_permissions (struct target_ops *self)
4349 {
4350   struct remote_state *rs = get_remote_state ();
4351
4352   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4353              "WriteReg:%x;WriteMem:%x;"
4354              "InsertBreak:%x;InsertTrace:%x;"
4355              "InsertFastTrace:%x;Stop:%x",
4356              may_write_registers, may_write_memory,
4357              may_insert_breakpoints, may_insert_tracepoints,
4358              may_insert_fast_tracepoints, may_stop);
4359   putpkt (rs->buf);
4360   getpkt (&rs->buf, &rs->buf_size, 0);
4361
4362   /* If the target didn't like the packet, warn the user.  Do not try
4363      to undo the user's settings, that would just be maddening.  */
4364   if (strcmp (rs->buf, "OK") != 0)
4365     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4366 }
4367
4368 /* This type describes each known response to the qSupported
4369    packet.  */
4370 struct protocol_feature
4371 {
4372   /* The name of this protocol feature.  */
4373   const char *name;
4374
4375   /* The default for this protocol feature.  */
4376   enum packet_support default_support;
4377
4378   /* The function to call when this feature is reported, or after
4379      qSupported processing if the feature is not supported.
4380      The first argument points to this structure.  The second
4381      argument indicates whether the packet requested support be
4382      enabled, disabled, or probed (or the default, if this function
4383      is being called at the end of processing and this feature was
4384      not reported).  The third argument may be NULL; if not NULL, it
4385      is a NUL-terminated string taken from the packet following
4386      this feature's name and an equals sign.  */
4387   void (*func) (const struct protocol_feature *, enum packet_support,
4388                 const char *);
4389
4390   /* The corresponding packet for this feature.  Only used if
4391      FUNC is remote_supported_packet.  */
4392   int packet;
4393 };
4394
4395 static void
4396 remote_supported_packet (const struct protocol_feature *feature,
4397                          enum packet_support support,
4398                          const char *argument)
4399 {
4400   if (argument)
4401     {
4402       warning (_("Remote qSupported response supplied an unexpected value for"
4403                  " \"%s\"."), feature->name);
4404       return;
4405     }
4406
4407   remote_protocol_packets[feature->packet].support = support;
4408 }
4409
4410 static void
4411 remote_packet_size (const struct protocol_feature *feature,
4412                     enum packet_support support, const char *value)
4413 {
4414   struct remote_state *rs = get_remote_state ();
4415
4416   int packet_size;
4417   char *value_end;
4418
4419   if (support != PACKET_ENABLE)
4420     return;
4421
4422   if (value == NULL || *value == '\0')
4423     {
4424       warning (_("Remote target reported \"%s\" without a size."),
4425                feature->name);
4426       return;
4427     }
4428
4429   errno = 0;
4430   packet_size = strtol (value, &value_end, 16);
4431   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4432     {
4433       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4434                feature->name, value);
4435       return;
4436     }
4437
4438   /* Record the new maximum packet size.  */
4439   rs->explicit_packet_size = packet_size;
4440 }
4441
4442 static const struct protocol_feature remote_protocol_features[] = {
4443   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4444   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4445     PACKET_qXfer_auxv },
4446   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4447     PACKET_qXfer_exec_file },
4448   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4449     PACKET_qXfer_features },
4450   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4451     PACKET_qXfer_libraries },
4452   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4453     PACKET_qXfer_libraries_svr4 },
4454   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4455     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4456   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4457     PACKET_qXfer_memory_map },
4458   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4459     PACKET_qXfer_spu_read },
4460   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4461     PACKET_qXfer_spu_write },
4462   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4463     PACKET_qXfer_osdata },
4464   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4465     PACKET_qXfer_threads },
4466   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4467     PACKET_qXfer_traceframe_info },
4468   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4469     PACKET_QPassSignals },
4470   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4471     PACKET_QProgramSignals },
4472   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4473     PACKET_QStartNoAckMode },
4474   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4475     PACKET_multiprocess_feature },
4476   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4477   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4478     PACKET_qXfer_siginfo_read },
4479   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4480     PACKET_qXfer_siginfo_write },
4481   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4482     PACKET_ConditionalTracepoints },
4483   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4484     PACKET_ConditionalBreakpoints },
4485   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4486     PACKET_BreakpointCommands },
4487   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4488     PACKET_FastTracepoints },
4489   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4490     PACKET_StaticTracepoints },
4491   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4492    PACKET_InstallInTrace},
4493   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4494     PACKET_DisconnectedTracing_feature },
4495   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4496     PACKET_bc },
4497   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4498     PACKET_bs },
4499   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4500     PACKET_TracepointSource },
4501   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4502     PACKET_QAllow },
4503   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4504     PACKET_EnableDisableTracepoints_feature },
4505   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4506     PACKET_qXfer_fdpic },
4507   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4508     PACKET_qXfer_uib },
4509   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4510     PACKET_QDisableRandomization },
4511   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4512   { "QTBuffer:size", PACKET_DISABLE,
4513     remote_supported_packet, PACKET_QTBuffer_size},
4514   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4515   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4516   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4517   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4518   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4519     PACKET_qXfer_btrace },
4520   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4521     PACKET_qXfer_btrace_conf },
4522   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4523     PACKET_Qbtrace_conf_bts_size },
4524   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4525   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4526   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4527     PACKET_fork_event_feature },
4528   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4529     PACKET_vfork_event_feature },
4530   { "exec-events", PACKET_DISABLE, remote_supported_packet,
4531     PACKET_exec_event_feature },
4532   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4533     PACKET_Qbtrace_conf_pt_size },
4534   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4535   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4536   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4537 };
4538
4539 static char *remote_support_xml;
4540
4541 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4542
4543 void
4544 register_remote_support_xml (const char *xml)
4545 {
4546 #if defined(HAVE_LIBEXPAT)
4547   if (remote_support_xml == NULL)
4548     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4549   else
4550     {
4551       char *copy = xstrdup (remote_support_xml + 13);
4552       char *p = strtok (copy, ",");
4553
4554       do
4555         {
4556           if (strcmp (p, xml) == 0)
4557             {
4558               /* already there */
4559               xfree (copy);
4560               return;
4561             }
4562         }
4563       while ((p = strtok (NULL, ",")) != NULL);
4564       xfree (copy);
4565
4566       remote_support_xml = reconcat (remote_support_xml,
4567                                      remote_support_xml, ",", xml,
4568                                      (char *) NULL);
4569     }
4570 #endif
4571 }
4572
4573 static char *
4574 remote_query_supported_append (char *msg, const char *append)
4575 {
4576   if (msg)
4577     return reconcat (msg, msg, ";", append, (char *) NULL);
4578   else
4579     return xstrdup (append);
4580 }
4581
4582 static void
4583 remote_query_supported (void)
4584 {
4585   struct remote_state *rs = get_remote_state ();
4586   char *next;
4587   int i;
4588   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4589
4590   /* The packet support flags are handled differently for this packet
4591      than for most others.  We treat an error, a disabled packet, and
4592      an empty response identically: any features which must be reported
4593      to be used will be automatically disabled.  An empty buffer
4594      accomplishes this, since that is also the representation for a list
4595      containing no features.  */
4596
4597   rs->buf[0] = 0;
4598   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4599     {
4600       char *q = NULL;
4601       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4602
4603       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4604         q = remote_query_supported_append (q, "multiprocess+");
4605
4606       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4607         q = remote_query_supported_append (q, "swbreak+");
4608       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4609         q = remote_query_supported_append (q, "hwbreak+");
4610
4611       q = remote_query_supported_append (q, "qRelocInsn+");
4612
4613       if (packet_set_cmd_state (PACKET_fork_event_feature)
4614           != AUTO_BOOLEAN_FALSE)
4615         q = remote_query_supported_append (q, "fork-events+");
4616       if (packet_set_cmd_state (PACKET_vfork_event_feature)
4617           != AUTO_BOOLEAN_FALSE)
4618         q = remote_query_supported_append (q, "vfork-events+");
4619       if (packet_set_cmd_state (PACKET_exec_event_feature)
4620           != AUTO_BOOLEAN_FALSE)
4621         q = remote_query_supported_append (q, "exec-events+");
4622
4623       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4624         q = remote_query_supported_append (q, "vContSupported+");
4625
4626       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4627         q = remote_query_supported_append (q, "QThreadEvents+");
4628
4629       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4630         q = remote_query_supported_append (q, "no-resumed+");
4631
4632       /* Keep this one last to work around a gdbserver <= 7.10 bug in
4633          the qSupported:xmlRegisters=i386 handling.  */
4634       if (remote_support_xml != NULL)
4635         q = remote_query_supported_append (q, remote_support_xml);
4636
4637       q = reconcat (q, "qSupported:", q, (char *) NULL);
4638       putpkt (q);
4639
4640       do_cleanups (old_chain);
4641
4642       getpkt (&rs->buf, &rs->buf_size, 0);
4643
4644       /* If an error occured, warn, but do not return - just reset the
4645          buffer to empty and go on to disable features.  */
4646       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4647           == PACKET_ERROR)
4648         {
4649           warning (_("Remote failure reply: %s"), rs->buf);
4650           rs->buf[0] = 0;
4651         }
4652     }
4653
4654   memset (seen, 0, sizeof (seen));
4655
4656   next = rs->buf;
4657   while (*next)
4658     {
4659       enum packet_support is_supported;
4660       char *p, *end, *name_end, *value;
4661
4662       /* First separate out this item from the rest of the packet.  If
4663          there's another item after this, we overwrite the separator
4664          (terminated strings are much easier to work with).  */
4665       p = next;
4666       end = strchr (p, ';');
4667       if (end == NULL)
4668         {
4669           end = p + strlen (p);
4670           next = end;
4671         }
4672       else
4673         {
4674           *end = '\0';
4675           next = end + 1;
4676
4677           if (end == p)
4678             {
4679               warning (_("empty item in \"qSupported\" response"));
4680               continue;
4681             }
4682         }
4683
4684       name_end = strchr (p, '=');
4685       if (name_end)
4686         {
4687           /* This is a name=value entry.  */
4688           is_supported = PACKET_ENABLE;
4689           value = name_end + 1;
4690           *name_end = '\0';
4691         }
4692       else
4693         {
4694           value = NULL;
4695           switch (end[-1])
4696             {
4697             case '+':
4698               is_supported = PACKET_ENABLE;
4699               break;
4700
4701             case '-':
4702               is_supported = PACKET_DISABLE;
4703               break;
4704
4705             case '?':
4706               is_supported = PACKET_SUPPORT_UNKNOWN;
4707               break;
4708
4709             default:
4710               warning (_("unrecognized item \"%s\" "
4711                          "in \"qSupported\" response"), p);
4712               continue;
4713             }
4714           end[-1] = '\0';
4715         }
4716
4717       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4718         if (strcmp (remote_protocol_features[i].name, p) == 0)
4719           {
4720             const struct protocol_feature *feature;
4721
4722             seen[i] = 1;
4723             feature = &remote_protocol_features[i];
4724             feature->func (feature, is_supported, value);
4725             break;
4726           }
4727     }
4728
4729   /* If we increased the packet size, make sure to increase the global
4730      buffer size also.  We delay this until after parsing the entire
4731      qSupported packet, because this is the same buffer we were
4732      parsing.  */
4733   if (rs->buf_size < rs->explicit_packet_size)
4734     {
4735       rs->buf_size = rs->explicit_packet_size;
4736       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4737     }
4738
4739   /* Handle the defaults for unmentioned features.  */
4740   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4741     if (!seen[i])
4742       {
4743         const struct protocol_feature *feature;
4744
4745         feature = &remote_protocol_features[i];
4746         feature->func (feature, feature->default_support, NULL);
4747       }
4748 }
4749
4750 /* Remove any of the remote.c targets from target stack.  Upper targets depend
4751    on it so remove them first.  */
4752
4753 static void
4754 remote_unpush_target (void)
4755 {
4756   pop_all_targets_at_and_above (process_stratum);
4757 }
4758
4759 static void
4760 remote_open_1 (const char *name, int from_tty,
4761                struct target_ops *target, int extended_p)
4762 {
4763   struct remote_state *rs = get_remote_state ();
4764
4765   if (name == 0)
4766     error (_("To open a remote debug connection, you need to specify what\n"
4767            "serial device is attached to the remote system\n"
4768            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4769
4770   /* See FIXME above.  */
4771   if (!target_async_permitted)
4772     wait_forever_enabled_p = 1;
4773
4774   /* If we're connected to a running target, target_preopen will kill it.
4775      Ask this question first, before target_preopen has a chance to kill
4776      anything.  */
4777   if (rs->remote_desc != NULL && !have_inferiors ())
4778     {
4779       if (from_tty
4780           && !query (_("Already connected to a remote target.  Disconnect? ")))
4781         error (_("Still connected."));
4782     }
4783
4784   /* Here the possibly existing remote target gets unpushed.  */
4785   target_preopen (from_tty);
4786
4787   /* Make sure we send the passed signals list the next time we resume.  */
4788   xfree (rs->last_pass_packet);
4789   rs->last_pass_packet = NULL;
4790
4791   /* Make sure we send the program signals list the next time we
4792      resume.  */
4793   xfree (rs->last_program_signals_packet);
4794   rs->last_program_signals_packet = NULL;
4795
4796   remote_fileio_reset ();
4797   reopen_exec_file ();
4798   reread_symbols ();
4799
4800   rs->remote_desc = remote_serial_open (name);
4801   if (!rs->remote_desc)
4802     perror_with_name (name);
4803
4804   if (baud_rate != -1)
4805     {
4806       if (serial_setbaudrate (rs->remote_desc, baud_rate))
4807         {
4808           /* The requested speed could not be set.  Error out to
4809              top level after closing remote_desc.  Take care to
4810              set remote_desc to NULL to avoid closing remote_desc
4811              more than once.  */
4812           serial_close (rs->remote_desc);
4813           rs->remote_desc = NULL;
4814           perror_with_name (name);
4815         }
4816     }
4817
4818   serial_setparity (rs->remote_desc, serial_parity);
4819   serial_raw (rs->remote_desc);
4820
4821   /* If there is something sitting in the buffer we might take it as a
4822      response to a command, which would be bad.  */
4823   serial_flush_input (rs->remote_desc);
4824
4825   if (from_tty)
4826     {
4827       puts_filtered ("Remote debugging using ");
4828       puts_filtered (name);
4829       puts_filtered ("\n");
4830     }
4831   push_target (target);         /* Switch to using remote target now.  */
4832
4833   /* Register extra event sources in the event loop.  */
4834   remote_async_inferior_event_token
4835     = create_async_event_handler (remote_async_inferior_event_handler,
4836                                   NULL);
4837   rs->notif_state = remote_notif_state_allocate ();
4838
4839   /* Reset the target state; these things will be queried either by
4840      remote_query_supported or as they are needed.  */
4841   reset_all_packet_configs_support ();
4842   rs->cached_wait_status = 0;
4843   rs->explicit_packet_size = 0;
4844   rs->noack_mode = 0;
4845   rs->extended = extended_p;
4846   rs->waiting_for_stop_reply = 0;
4847   rs->ctrlc_pending_p = 0;
4848
4849   rs->general_thread = not_sent_ptid;
4850   rs->continue_thread = not_sent_ptid;
4851   rs->remote_traceframe_number = -1;
4852
4853   /* Probe for ability to use "ThreadInfo" query, as required.  */
4854   rs->use_threadinfo_query = 1;
4855   rs->use_threadextra_query = 1;
4856
4857   readahead_cache_invalidate ();
4858
4859   if (target_async_permitted)
4860     {
4861       /* With this target we start out by owning the terminal.  */
4862       remote_async_terminal_ours_p = 1;
4863
4864       /* FIXME: cagney/1999-09-23: During the initial connection it is
4865          assumed that the target is already ready and able to respond to
4866          requests.  Unfortunately remote_start_remote() eventually calls
4867          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
4868          around this.  Eventually a mechanism that allows
4869          wait_for_inferior() to expect/get timeouts will be
4870          implemented.  */
4871       wait_forever_enabled_p = 0;
4872     }
4873
4874   /* First delete any symbols previously loaded from shared libraries.  */
4875   no_shared_libraries (NULL, 0);
4876
4877   /* Start afresh.  */
4878   init_thread_list ();
4879
4880   /* Start the remote connection.  If error() or QUIT, discard this
4881      target (we'd otherwise be in an inconsistent state) and then
4882      propogate the error on up the exception chain.  This ensures that
4883      the caller doesn't stumble along blindly assuming that the
4884      function succeeded.  The CLI doesn't have this problem but other
4885      UI's, such as MI do.
4886
4887      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4888      this function should return an error indication letting the
4889      caller restore the previous state.  Unfortunately the command
4890      ``target remote'' is directly wired to this function making that
4891      impossible.  On a positive note, the CLI side of this problem has
4892      been fixed - the function set_cmd_context() makes it possible for
4893      all the ``target ....'' commands to share a common callback
4894      function.  See cli-dump.c.  */
4895   {
4896
4897     TRY
4898       {
4899         remote_start_remote (from_tty, target, extended_p);
4900       }
4901     CATCH (ex, RETURN_MASK_ALL)
4902       {
4903         /* Pop the partially set up target - unless something else did
4904            already before throwing the exception.  */
4905         if (rs->remote_desc != NULL)
4906           remote_unpush_target ();
4907         if (target_async_permitted)
4908           wait_forever_enabled_p = 1;
4909         throw_exception (ex);
4910       }
4911     END_CATCH
4912   }
4913
4914   remote_btrace_reset ();
4915
4916   if (target_async_permitted)
4917     wait_forever_enabled_p = 1;
4918 }
4919
4920 /* Detach the specified process.  */
4921
4922 static void
4923 remote_detach_pid (int pid)
4924 {
4925   struct remote_state *rs = get_remote_state ();
4926
4927   if (remote_multi_process_p (rs))
4928     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4929   else
4930     strcpy (rs->buf, "D");
4931
4932   putpkt (rs->buf);
4933   getpkt (&rs->buf, &rs->buf_size, 0);
4934
4935   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4936     ;
4937   else if (rs->buf[0] == '\0')
4938     error (_("Remote doesn't know how to detach"));
4939   else
4940     error (_("Can't detach process."));
4941 }
4942
4943 /* This detaches a program to which we previously attached, using
4944    inferior_ptid to identify the process.  After this is done, GDB
4945    can be used to debug some other program.  We better not have left
4946    any breakpoints in the target program or it'll die when it hits
4947    one.  */
4948
4949 static void
4950 remote_detach_1 (const char *args, int from_tty)
4951 {
4952   int pid = ptid_get_pid (inferior_ptid);
4953   struct remote_state *rs = get_remote_state ();
4954   struct thread_info *tp = find_thread_ptid (inferior_ptid);
4955   int is_fork_parent;
4956
4957   if (args)
4958     error (_("Argument given to \"detach\" when remotely debugging."));
4959
4960   if (!target_has_execution)
4961     error (_("No process to detach from."));
4962
4963   if (from_tty)
4964     {
4965       char *exec_file = get_exec_file (0);
4966       if (exec_file == NULL)
4967         exec_file = "";
4968       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4969                          target_pid_to_str (pid_to_ptid (pid)));
4970       gdb_flush (gdb_stdout);
4971     }
4972
4973   /* Tell the remote target to detach.  */
4974   remote_detach_pid (pid);
4975
4976   /* Exit only if this is the only active inferior.  */
4977   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
4978     puts_filtered (_("Ending remote debugging.\n"));
4979
4980   /* Check to see if we are detaching a fork parent.  Note that if we
4981      are detaching a fork child, tp == NULL.  */
4982   is_fork_parent = (tp != NULL
4983                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4984
4985   /* If doing detach-on-fork, we don't mourn, because that will delete
4986      breakpoints that should be available for the followed inferior.  */
4987   if (!is_fork_parent)
4988     target_mourn_inferior ();
4989   else
4990     {
4991       inferior_ptid = null_ptid;
4992       detach_inferior (pid);
4993     }
4994 }
4995
4996 static void
4997 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4998 {
4999   remote_detach_1 (args, from_tty);
5000 }
5001
5002 static void
5003 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5004 {
5005   remote_detach_1 (args, from_tty);
5006 }
5007
5008 /* Target follow-fork function for remote targets.  On entry, and
5009    at return, the current inferior is the fork parent.
5010
5011    Note that although this is currently only used for extended-remote,
5012    it is named remote_follow_fork in anticipation of using it for the
5013    remote target as well.  */
5014
5015 static int
5016 remote_follow_fork (struct target_ops *ops, int follow_child,
5017                     int detach_fork)
5018 {
5019   struct remote_state *rs = get_remote_state ();
5020   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5021
5022   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5023       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5024     {
5025       /* When following the parent and detaching the child, we detach
5026          the child here.  For the case of following the child and
5027          detaching the parent, the detach is done in the target-
5028          independent follow fork code in infrun.c.  We can't use
5029          target_detach when detaching an unfollowed child because
5030          the client side doesn't know anything about the child.  */
5031       if (detach_fork && !follow_child)
5032         {
5033           /* Detach the fork child.  */
5034           ptid_t child_ptid;
5035           pid_t child_pid;
5036
5037           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5038           child_pid = ptid_get_pid (child_ptid);
5039
5040           remote_detach_pid (child_pid);
5041           detach_inferior (child_pid);
5042         }
5043     }
5044   return 0;
5045 }
5046
5047 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5048    in the program space of the new inferior.  On entry and at return the
5049    current inferior is the exec'ing inferior.  INF is the new exec'd
5050    inferior, which may be the same as the exec'ing inferior unless
5051    follow-exec-mode is "new".  */
5052
5053 static void
5054 remote_follow_exec (struct target_ops *ops,
5055                     struct inferior *inf, char *execd_pathname)
5056 {
5057   /* We know that this is a target file name, so if it has the "target:"
5058      prefix we strip it off before saving it in the program space.  */
5059   if (is_target_filename (execd_pathname))
5060     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5061
5062   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5063 }
5064
5065 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5066
5067 static void
5068 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5069 {
5070   if (args)
5071     error (_("Argument given to \"disconnect\" when remotely debugging."));
5072
5073   /* Make sure we unpush even the extended remote targets.  Calling
5074      target_mourn_inferior won't unpush, and remote_mourn won't
5075      unpush if there is more than one inferior left.  */
5076   unpush_target (target);
5077   generic_mourn_inferior ();
5078
5079   if (from_tty)
5080     puts_filtered ("Ending remote debugging.\n");
5081 }
5082
5083 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5084    be chatty about it.  */
5085
5086 static void
5087 extended_remote_attach (struct target_ops *target, const char *args,
5088                         int from_tty)
5089 {
5090   struct remote_state *rs = get_remote_state ();
5091   int pid;
5092   char *wait_status = NULL;
5093
5094   pid = parse_pid_to_attach (args);
5095
5096   /* Remote PID can be freely equal to getpid, do not check it here the same
5097      way as in other targets.  */
5098
5099   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5100     error (_("This target does not support attaching to a process"));
5101
5102   if (from_tty)
5103     {
5104       char *exec_file = get_exec_file (0);
5105
5106       if (exec_file)
5107         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5108                            target_pid_to_str (pid_to_ptid (pid)));
5109       else
5110         printf_unfiltered (_("Attaching to %s\n"),
5111                            target_pid_to_str (pid_to_ptid (pid)));
5112
5113       gdb_flush (gdb_stdout);
5114     }
5115
5116   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5117   putpkt (rs->buf);
5118   getpkt (&rs->buf, &rs->buf_size, 0);
5119
5120   switch (packet_ok (rs->buf,
5121                      &remote_protocol_packets[PACKET_vAttach]))
5122     {
5123     case PACKET_OK:
5124       if (!target_is_non_stop_p ())
5125         {
5126           /* Save the reply for later.  */
5127           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5128           strcpy (wait_status, rs->buf);
5129         }
5130       else if (strcmp (rs->buf, "OK") != 0)
5131         error (_("Attaching to %s failed with: %s"),
5132                target_pid_to_str (pid_to_ptid (pid)),
5133                rs->buf);
5134       break;
5135     case PACKET_UNKNOWN:
5136       error (_("This target does not support attaching to a process"));
5137     default:
5138       error (_("Attaching to %s failed"),
5139              target_pid_to_str (pid_to_ptid (pid)));
5140     }
5141
5142   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5143
5144   inferior_ptid = pid_to_ptid (pid);
5145
5146   if (target_is_non_stop_p ())
5147     {
5148       struct thread_info *thread;
5149
5150       /* Get list of threads.  */
5151       remote_update_thread_list (target);
5152
5153       thread = first_thread_of_process (pid);
5154       if (thread)
5155         inferior_ptid = thread->ptid;
5156       else
5157         inferior_ptid = pid_to_ptid (pid);
5158
5159       /* Invalidate our notion of the remote current thread.  */
5160       record_currthread (rs, minus_one_ptid);
5161     }
5162   else
5163     {
5164       /* Now, if we have thread information, update inferior_ptid.  */
5165       inferior_ptid = remote_current_thread (inferior_ptid);
5166
5167       /* Add the main thread to the thread list.  */
5168       add_thread_silent (inferior_ptid);
5169     }
5170
5171   /* Next, if the target can specify a description, read it.  We do
5172      this before anything involving memory or registers.  */
5173   target_find_description ();
5174
5175   if (!target_is_non_stop_p ())
5176     {
5177       /* Use the previously fetched status.  */
5178       gdb_assert (wait_status != NULL);
5179
5180       if (target_can_async_p ())
5181         {
5182           struct notif_event *reply
5183             =  remote_notif_parse (&notif_client_stop, wait_status);
5184
5185           push_stop_reply ((struct stop_reply *) reply);
5186
5187           target_async (1);
5188         }
5189       else
5190         {
5191           gdb_assert (wait_status != NULL);
5192           strcpy (rs->buf, wait_status);
5193           rs->cached_wait_status = 1;
5194         }
5195     }
5196   else
5197     gdb_assert (wait_status == NULL);
5198 }
5199
5200 /* Implementation of the to_post_attach method.  */
5201
5202 static void
5203 extended_remote_post_attach (struct target_ops *ops, int pid)
5204 {
5205   /* Get text, data & bss offsets.  */
5206   get_offsets ();
5207
5208   /* In certain cases GDB might not have had the chance to start
5209      symbol lookup up until now.  This could happen if the debugged
5210      binary is not using shared libraries, the vsyscall page is not
5211      present (on Linux) and the binary itself hadn't changed since the
5212      debugging process was started.  */
5213   if (symfile_objfile != NULL)
5214     remote_check_symbols();
5215 }
5216
5217 \f
5218 /* Check for the availability of vCont.  This function should also check
5219    the response.  */
5220
5221 static void
5222 remote_vcont_probe (struct remote_state *rs)
5223 {
5224   char *buf;
5225
5226   strcpy (rs->buf, "vCont?");
5227   putpkt (rs->buf);
5228   getpkt (&rs->buf, &rs->buf_size, 0);
5229   buf = rs->buf;
5230
5231   /* Make sure that the features we assume are supported.  */
5232   if (startswith (buf, "vCont"))
5233     {
5234       char *p = &buf[5];
5235       int support_c, support_C;
5236
5237       rs->supports_vCont.s = 0;
5238       rs->supports_vCont.S = 0;
5239       support_c = 0;
5240       support_C = 0;
5241       rs->supports_vCont.t = 0;
5242       rs->supports_vCont.r = 0;
5243       while (p && *p == ';')
5244         {
5245           p++;
5246           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5247             rs->supports_vCont.s = 1;
5248           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5249             rs->supports_vCont.S = 1;
5250           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5251             support_c = 1;
5252           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5253             support_C = 1;
5254           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5255             rs->supports_vCont.t = 1;
5256           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5257             rs->supports_vCont.r = 1;
5258
5259           p = strchr (p, ';');
5260         }
5261
5262       /* If c, and C are not all supported, we can't use vCont.  Clearing
5263          BUF will make packet_ok disable the packet.  */
5264       if (!support_c || !support_C)
5265         buf[0] = 0;
5266     }
5267
5268   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5269 }
5270
5271 /* Helper function for building "vCont" resumptions.  Write a
5272    resumption to P.  ENDP points to one-passed-the-end of the buffer
5273    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5274    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5275    resumed thread should be single-stepped and/or signalled.  If PTID
5276    equals minus_one_ptid, then all threads are resumed; if PTID
5277    represents a process, then all threads of the process are resumed;
5278    the thread to be stepped and/or signalled is given in the global
5279    INFERIOR_PTID.  */
5280
5281 static char *
5282 append_resumption (char *p, char *endp,
5283                    ptid_t ptid, int step, enum gdb_signal siggnal)
5284 {
5285   struct remote_state *rs = get_remote_state ();
5286
5287   if (step && siggnal != GDB_SIGNAL_0)
5288     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5289   else if (step
5290            /* GDB is willing to range step.  */
5291            && use_range_stepping
5292            /* Target supports range stepping.  */
5293            && rs->supports_vCont.r
5294            /* We don't currently support range stepping multiple
5295               threads with a wildcard (though the protocol allows it,
5296               so stubs shouldn't make an active effort to forbid
5297               it).  */
5298            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5299     {
5300       struct thread_info *tp;
5301
5302       if (ptid_equal (ptid, minus_one_ptid))
5303         {
5304           /* If we don't know about the target thread's tid, then
5305              we're resuming magic_null_ptid (see caller).  */
5306           tp = find_thread_ptid (magic_null_ptid);
5307         }
5308       else
5309         tp = find_thread_ptid (ptid);
5310       gdb_assert (tp != NULL);
5311
5312       if (tp->control.may_range_step)
5313         {
5314           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5315
5316           p += xsnprintf (p, endp - p, ";r%s,%s",
5317                           phex_nz (tp->control.step_range_start,
5318                                    addr_size),
5319                           phex_nz (tp->control.step_range_end,
5320                                    addr_size));
5321         }
5322       else
5323         p += xsnprintf (p, endp - p, ";s");
5324     }
5325   else if (step)
5326     p += xsnprintf (p, endp - p, ";s");
5327   else if (siggnal != GDB_SIGNAL_0)
5328     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5329   else
5330     p += xsnprintf (p, endp - p, ";c");
5331
5332   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5333     {
5334       ptid_t nptid;
5335
5336       /* All (-1) threads of process.  */
5337       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5338
5339       p += xsnprintf (p, endp - p, ":");
5340       p = write_ptid (p, endp, nptid);
5341     }
5342   else if (!ptid_equal (ptid, minus_one_ptid))
5343     {
5344       p += xsnprintf (p, endp - p, ":");
5345       p = write_ptid (p, endp, ptid);
5346     }
5347
5348   return p;
5349 }
5350
5351 /* Clear the thread's private info on resume.  */
5352
5353 static void
5354 resume_clear_thread_private_info (struct thread_info *thread)
5355 {
5356   if (thread->priv != NULL)
5357     {
5358       thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5359       thread->priv->watch_data_address = 0;
5360     }
5361 }
5362
5363 /* Append a vCont continue-with-signal action for threads that have a
5364    non-zero stop signal.  */
5365
5366 static char *
5367 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5368 {
5369   struct thread_info *thread;
5370
5371   ALL_NON_EXITED_THREADS (thread)
5372     if (ptid_match (thread->ptid, ptid)
5373         && !ptid_equal (inferior_ptid, thread->ptid)
5374         && thread->suspend.stop_signal != GDB_SIGNAL_0)
5375       {
5376         p = append_resumption (p, endp, thread->ptid,
5377                                0, thread->suspend.stop_signal);
5378         thread->suspend.stop_signal = GDB_SIGNAL_0;
5379         resume_clear_thread_private_info (thread);
5380       }
5381
5382   return p;
5383 }
5384
5385 /* Resume the remote inferior by using a "vCont" packet.  The thread
5386    to be resumed is PTID; STEP and SIGGNAL indicate whether the
5387    resumed thread should be single-stepped and/or signalled.  If PTID
5388    equals minus_one_ptid, then all threads are resumed; the thread to
5389    be stepped and/or signalled is given in the global INFERIOR_PTID.
5390    This function returns non-zero iff it resumes the inferior.
5391
5392    This function issues a strict subset of all possible vCont commands at the
5393    moment.  */
5394
5395 static int
5396 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5397 {
5398   struct remote_state *rs = get_remote_state ();
5399   char *p;
5400   char *endp;
5401
5402   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5403     remote_vcont_probe (rs);
5404
5405   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5406     return 0;
5407
5408   p = rs->buf;
5409   endp = rs->buf + get_remote_packet_size ();
5410
5411   /* If we could generate a wider range of packets, we'd have to worry
5412      about overflowing BUF.  Should there be a generic
5413      "multi-part-packet" packet?  */
5414
5415   p += xsnprintf (p, endp - p, "vCont");
5416
5417   if (ptid_equal (ptid, magic_null_ptid))
5418     {
5419       /* MAGIC_NULL_PTID means that we don't have any active threads,
5420          so we don't have any TID numbers the inferior will
5421          understand.  Make sure to only send forms that do not specify
5422          a TID.  */
5423       append_resumption (p, endp, minus_one_ptid, step, siggnal);
5424     }
5425   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5426     {
5427       /* Resume all threads (of all processes, or of a single
5428          process), with preference for INFERIOR_PTID.  This assumes
5429          inferior_ptid belongs to the set of all threads we are about
5430          to resume.  */
5431       if (step || siggnal != GDB_SIGNAL_0)
5432         {
5433           /* Step inferior_ptid, with or without signal.  */
5434           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5435         }
5436
5437       /* Also pass down any pending signaled resumption for other
5438          threads not the current.  */
5439       p = append_pending_thread_resumptions (p, endp, ptid);
5440
5441       /* And continue others without a signal.  */
5442       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5443     }
5444   else
5445     {
5446       /* Scheduler locking; resume only PTID.  */
5447       append_resumption (p, endp, ptid, step, siggnal);
5448     }
5449
5450   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5451   putpkt (rs->buf);
5452
5453   if (target_is_non_stop_p ())
5454     {
5455       /* In non-stop, the stub replies to vCont with "OK".  The stop
5456          reply will be reported asynchronously by means of a `%Stop'
5457          notification.  */
5458       getpkt (&rs->buf, &rs->buf_size, 0);
5459       if (strcmp (rs->buf, "OK") != 0)
5460         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5461     }
5462
5463   return 1;
5464 }
5465
5466 /* Tell the remote machine to resume.  */
5467
5468 static void
5469 remote_resume (struct target_ops *ops,
5470                ptid_t ptid, int step, enum gdb_signal siggnal)
5471 {
5472   struct remote_state *rs = get_remote_state ();
5473   char *buf;
5474   struct thread_info *thread;
5475
5476   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5477      (explained in remote-notif.c:handle_notification) so
5478      remote_notif_process is not called.  We need find a place where
5479      it is safe to start a 'vNotif' sequence.  It is good to do it
5480      before resuming inferior, because inferior was stopped and no RSP
5481      traffic at that moment.  */
5482   if (!target_is_non_stop_p ())
5483     remote_notif_process (rs->notif_state, &notif_client_stop);
5484
5485   rs->last_sent_signal = siggnal;
5486   rs->last_sent_step = step;
5487
5488   /* The vCont packet doesn't need to specify threads via Hc.  */
5489   /* No reverse support (yet) for vCont.  */
5490   if (execution_direction != EXEC_REVERSE)
5491     if (remote_vcont_resume (ptid, step, siggnal))
5492       goto done;
5493
5494   /* All other supported resume packets do use Hc, so set the continue
5495      thread.  */
5496   if (ptid_equal (ptid, minus_one_ptid))
5497     set_continue_thread (any_thread_ptid);
5498   else
5499     set_continue_thread (ptid);
5500
5501   ALL_NON_EXITED_THREADS (thread)
5502     resume_clear_thread_private_info (thread);
5503
5504   buf = rs->buf;
5505   if (execution_direction == EXEC_REVERSE)
5506     {
5507       /* We don't pass signals to the target in reverse exec mode.  */
5508       if (info_verbose && siggnal != GDB_SIGNAL_0)
5509         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5510                  siggnal);
5511
5512       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5513         error (_("Remote reverse-step not supported."));
5514       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5515         error (_("Remote reverse-continue not supported."));
5516
5517       strcpy (buf, step ? "bs" : "bc");
5518     }
5519   else if (siggnal != GDB_SIGNAL_0)
5520     {
5521       buf[0] = step ? 'S' : 'C';
5522       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5523       buf[2] = tohex (((int) siggnal) & 0xf);
5524       buf[3] = '\0';
5525     }
5526   else
5527     strcpy (buf, step ? "s" : "c");
5528
5529   putpkt (buf);
5530
5531  done:
5532   /* We are about to start executing the inferior, let's register it
5533      with the event loop.  NOTE: this is the one place where all the
5534      execution commands end up.  We could alternatively do this in each
5535      of the execution commands in infcmd.c.  */
5536   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5537      into infcmd.c in order to allow inferior function calls to work
5538      NOT asynchronously.  */
5539   if (target_can_async_p ())
5540     target_async (1);
5541
5542   /* We've just told the target to resume.  The remote server will
5543      wait for the inferior to stop, and then send a stop reply.  In
5544      the mean time, we can't start another command/query ourselves
5545      because the stub wouldn't be ready to process it.  This applies
5546      only to the base all-stop protocol, however.  In non-stop (which
5547      only supports vCont), the stub replies with an "OK", and is
5548      immediate able to process further serial input.  */
5549   if (!target_is_non_stop_p ())
5550     rs->waiting_for_stop_reply = 1;
5551 }
5552 \f
5553
5554 /* Set up the signal handler for SIGINT, while the target is
5555    executing, ovewriting the 'regular' SIGINT signal handler.  */
5556 static void
5557 async_initialize_sigint_signal_handler (void)
5558 {
5559   signal (SIGINT, async_handle_remote_sigint);
5560 }
5561
5562 /* Signal handler for SIGINT, while the target is executing.  */
5563 static void
5564 async_handle_remote_sigint (int sig)
5565 {
5566   signal (sig, async_handle_remote_sigint_twice);
5567   /* Note we need to go through gdb_call_async_signal_handler in order
5568      to wake up the event loop on Windows.  */
5569   gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5570 }
5571
5572 /* Signal handler for SIGINT, installed after SIGINT has already been
5573    sent once.  It will take effect the second time that the user sends
5574    a ^C.  */
5575 static void
5576 async_handle_remote_sigint_twice (int sig)
5577 {
5578   signal (sig, async_handle_remote_sigint);
5579   /* See note in async_handle_remote_sigint.  */
5580   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5581 }
5582
5583 /* Implementation of to_check_pending_interrupt.  */
5584
5585 static void
5586 remote_check_pending_interrupt (struct target_ops *self)
5587 {
5588   struct async_signal_handler *token = async_sigint_remote_twice_token;
5589
5590   if (async_signal_handler_is_marked (token))
5591     {
5592       clear_async_signal_handler (token);
5593       call_async_signal_handler (token);
5594     }
5595 }
5596
5597 /* Perform the real interruption of the target execution, in response
5598    to a ^C.  */
5599 static void
5600 async_remote_interrupt (gdb_client_data arg)
5601 {
5602   if (remote_debug)
5603     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5604
5605   target_interrupt (inferior_ptid);
5606 }
5607
5608 /* Perform interrupt, if the first attempt did not succeed.  Just give
5609    up on the target alltogether.  */
5610 static void
5611 async_remote_interrupt_twice (gdb_client_data arg)
5612 {
5613   if (remote_debug)
5614     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5615
5616   interrupt_query ();
5617 }
5618
5619 /* Reinstall the usual SIGINT handlers, after the target has
5620    stopped.  */
5621 static void
5622 async_cleanup_sigint_signal_handler (void *dummy)
5623 {
5624   signal (SIGINT, handle_sigint);
5625 }
5626
5627 /* Send ^C to target to halt it.  Target will respond, and send us a
5628    packet.  */
5629 static void (*ofunc) (int);
5630
5631 /* The command line interface's interrupt routine.  This function is installed
5632    as a signal handler for SIGINT.  The first time a user requests an
5633    interrupt, we call remote_interrupt to send a break or ^C.  If there is no
5634    response from the target (it didn't stop when the user requested it),
5635    we ask the user if he'd like to detach from the target.  */
5636
5637 static void
5638 sync_remote_interrupt (int signo)
5639 {
5640   /* If this doesn't work, try more severe steps.  */
5641   signal (signo, sync_remote_interrupt_twice);
5642
5643   gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5644 }
5645
5646 /* The user typed ^C twice.  */
5647
5648 static void
5649 sync_remote_interrupt_twice (int signo)
5650 {
5651   signal (signo, ofunc);
5652   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5653   signal (signo, sync_remote_interrupt);
5654 }
5655
5656 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
5657    thread, all threads of a remote process, or all threads of all
5658    processes.  */
5659
5660 static void
5661 remote_stop_ns (ptid_t ptid)
5662 {
5663   struct remote_state *rs = get_remote_state ();
5664   char *p = rs->buf;
5665   char *endp = rs->buf + get_remote_packet_size ();
5666
5667   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5668     remote_vcont_probe (rs);
5669
5670   if (!rs->supports_vCont.t)
5671     error (_("Remote server does not support stopping threads"));
5672
5673   if (ptid_equal (ptid, minus_one_ptid)
5674       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5675     p += xsnprintf (p, endp - p, "vCont;t");
5676   else
5677     {
5678       ptid_t nptid;
5679
5680       p += xsnprintf (p, endp - p, "vCont;t:");
5681
5682       if (ptid_is_pid (ptid))
5683           /* All (-1) threads of process.  */
5684         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5685       else
5686         {
5687           /* Small optimization: if we already have a stop reply for
5688              this thread, no use in telling the stub we want this
5689              stopped.  */
5690           if (peek_stop_reply (ptid))
5691             return;
5692
5693           nptid = ptid;
5694         }
5695
5696       write_ptid (p, endp, nptid);
5697     }
5698
5699   /* In non-stop, we get an immediate OK reply.  The stop reply will
5700      come in asynchronously by notification.  */
5701   putpkt (rs->buf);
5702   getpkt (&rs->buf, &rs->buf_size, 0);
5703   if (strcmp (rs->buf, "OK") != 0)
5704     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5705 }
5706
5707 /* All-stop version of target_interrupt.  Sends a break or a ^C to
5708    interrupt the remote target.  It is undefined which thread of which
5709    process reports the interrupt.  */
5710
5711 static void
5712 remote_interrupt_as (void)
5713 {
5714   struct remote_state *rs = get_remote_state ();
5715
5716   rs->ctrlc_pending_p = 1;
5717
5718   /* If the inferior is stopped already, but the core didn't know
5719      about it yet, just ignore the request.  The cached wait status
5720      will be collected in remote_wait.  */
5721   if (rs->cached_wait_status)
5722     return;
5723
5724   /* Send interrupt_sequence to remote target.  */
5725   send_interrupt_sequence ();
5726 }
5727
5728 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
5729    the remote target.  It is undefined which thread of which process
5730    reports the interrupt.  Returns true if the packet is supported by
5731    the server, false otherwise.  */
5732
5733 static int
5734 remote_interrupt_ns (void)
5735 {
5736   struct remote_state *rs = get_remote_state ();
5737   char *p = rs->buf;
5738   char *endp = rs->buf + get_remote_packet_size ();
5739
5740   xsnprintf (p, endp - p, "vCtrlC");
5741
5742   /* In non-stop, we get an immediate OK reply.  The stop reply will
5743      come in asynchronously by notification.  */
5744   putpkt (rs->buf);
5745   getpkt (&rs->buf, &rs->buf_size, 0);
5746
5747   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5748     {
5749     case PACKET_OK:
5750       break;
5751     case PACKET_UNKNOWN:
5752       return 0;
5753     case PACKET_ERROR:
5754       error (_("Interrupting target failed: %s"), rs->buf);
5755     }
5756
5757   return 1;
5758 }
5759
5760 /* Implement the to_stop function for the remote targets.  */
5761
5762 static void
5763 remote_stop (struct target_ops *self, ptid_t ptid)
5764 {
5765   if (remote_debug)
5766     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5767
5768   if (target_is_non_stop_p ())
5769     remote_stop_ns (ptid);
5770   else
5771     {
5772       /* We don't currently have a way to transparently pause the
5773          remote target in all-stop mode.  Interrupt it instead.  */
5774       remote_interrupt_as ();
5775     }
5776 }
5777
5778 /* Implement the to_interrupt function for the remote targets.  */
5779
5780 static void
5781 remote_interrupt (struct target_ops *self, ptid_t ptid)
5782 {
5783   if (remote_debug)
5784     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5785
5786   if (non_stop)
5787     {
5788       /* In non-stop mode, we always stop with no signal instead.  */
5789       remote_stop_ns (ptid);
5790     }
5791   else
5792     {
5793       /* In all-stop, we emulate ^C-ing the remote target's
5794          terminal.  */
5795       if (target_is_non_stop_p ())
5796         {
5797           if (!remote_interrupt_ns ())
5798             {
5799               /* No support for ^C-ing the remote target.  Stop it
5800                  (with no signal) instead.  */
5801               remote_stop_ns (ptid);
5802             }
5803         }
5804       else
5805         remote_interrupt_as ();
5806     }
5807 }
5808
5809 /* Ask the user what to do when an interrupt is received.  */
5810
5811 static void
5812 interrupt_query (void)
5813 {
5814   struct remote_state *rs = get_remote_state ();
5815   struct cleanup *old_chain;
5816
5817   old_chain = make_cleanup_restore_target_terminal ();
5818   target_terminal_ours ();
5819
5820   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5821     {
5822       if (query (_("The target is not responding to interrupt requests.\n"
5823                    "Stop debugging it? ")))
5824         {
5825           remote_unpush_target ();
5826           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5827         }
5828     }
5829   else
5830     {
5831       if (query (_("Interrupted while waiting for the program.\n"
5832                    "Give up waiting? ")))
5833         quit ();
5834     }
5835
5836   do_cleanups (old_chain);
5837 }
5838
5839 /* Enable/disable target terminal ownership.  Most targets can use
5840    terminal groups to control terminal ownership.  Remote targets are
5841    different in that explicit transfer of ownership to/from GDB/target
5842    is required.  */
5843
5844 static void
5845 remote_terminal_inferior (struct target_ops *self)
5846 {
5847   if (!target_async_permitted)
5848     /* Nothing to do.  */
5849     return;
5850
5851   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5852      idempotent.  The event-loop GDB talking to an asynchronous target
5853      with a synchronous command calls this function from both
5854      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
5855      transfer the terminal to the target when it shouldn't this guard
5856      can go away.  */
5857   if (!remote_async_terminal_ours_p)
5858     return;
5859   delete_file_handler (input_fd);
5860   remote_async_terminal_ours_p = 0;
5861   async_initialize_sigint_signal_handler ();
5862   /* NOTE: At this point we could also register our selves as the
5863      recipient of all input.  Any characters typed could then be
5864      passed on down to the target.  */
5865 }
5866
5867 static void
5868 remote_terminal_ours (struct target_ops *self)
5869 {
5870   if (!target_async_permitted)
5871     /* Nothing to do.  */
5872     return;
5873
5874   /* See FIXME in remote_terminal_inferior.  */
5875   if (remote_async_terminal_ours_p)
5876     return;
5877   async_cleanup_sigint_signal_handler (NULL);
5878   add_file_handler (input_fd, stdin_event_handler, 0);
5879   remote_async_terminal_ours_p = 1;
5880 }
5881
5882 static void
5883 remote_console_output (char *msg)
5884 {
5885   char *p;
5886
5887   for (p = msg; p[0] && p[1]; p += 2)
5888     {
5889       char tb[2];
5890       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5891
5892       tb[0] = c;
5893       tb[1] = 0;
5894       fputs_unfiltered (tb, gdb_stdtarg);
5895     }
5896   gdb_flush (gdb_stdtarg);
5897 }
5898
5899 typedef struct cached_reg
5900 {
5901   int num;
5902   gdb_byte data[MAX_REGISTER_SIZE];
5903 } cached_reg_t;
5904
5905 DEF_VEC_O(cached_reg_t);
5906
5907 typedef struct stop_reply
5908 {
5909   struct notif_event base;
5910
5911   /* The identifier of the thread about this event  */
5912   ptid_t ptid;
5913
5914   /* The remote state this event is associated with.  When the remote
5915      connection, represented by a remote_state object, is closed,
5916      all the associated stop_reply events should be released.  */
5917   struct remote_state *rs;
5918
5919   struct target_waitstatus ws;
5920
5921   /* Expedited registers.  This makes remote debugging a bit more
5922      efficient for those targets that provide critical registers as
5923      part of their normal status mechanism (as another roundtrip to
5924      fetch them is avoided).  */
5925   VEC(cached_reg_t) *regcache;
5926
5927   enum target_stop_reason stop_reason;
5928
5929   CORE_ADDR watch_data_address;
5930
5931   int core;
5932 } *stop_reply_p;
5933
5934 DECLARE_QUEUE_P (stop_reply_p);
5935 DEFINE_QUEUE_P (stop_reply_p);
5936 /* The list of already fetched and acknowledged stop events.  This
5937    queue is used for notification Stop, and other notifications
5938    don't need queue for their events, because the notification events
5939    of Stop can't be consumed immediately, so that events should be
5940    queued first, and be consumed by remote_wait_{ns,as} one per
5941    time.  Other notifications can consume their events immediately,
5942    so queue is not needed for them.  */
5943 static QUEUE (stop_reply_p) *stop_reply_queue;
5944
5945 static void
5946 stop_reply_xfree (struct stop_reply *r)
5947 {
5948   notif_event_xfree ((struct notif_event *) r);
5949 }
5950
5951 /* Return the length of the stop reply queue.  */
5952
5953 static int
5954 stop_reply_queue_length (void)
5955 {
5956   return QUEUE_length (stop_reply_p, stop_reply_queue);
5957 }
5958
5959 static void
5960 remote_notif_stop_parse (struct notif_client *self, char *buf,
5961                          struct notif_event *event)
5962 {
5963   remote_parse_stop_reply (buf, (struct stop_reply *) event);
5964 }
5965
5966 static void
5967 remote_notif_stop_ack (struct notif_client *self, char *buf,
5968                        struct notif_event *event)
5969 {
5970   struct stop_reply *stop_reply = (struct stop_reply *) event;
5971
5972   /* acknowledge */
5973   putpkt ((char *) self->ack_command);
5974
5975   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5976       /* We got an unknown stop reply.  */
5977       error (_("Unknown stop reply"));
5978
5979   push_stop_reply (stop_reply);
5980 }
5981
5982 static int
5983 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5984 {
5985   /* We can't get pending events in remote_notif_process for
5986      notification stop, and we have to do this in remote_wait_ns
5987      instead.  If we fetch all queued events from stub, remote stub
5988      may exit and we have no chance to process them back in
5989      remote_wait_ns.  */
5990   mark_async_event_handler (remote_async_inferior_event_token);
5991   return 0;
5992 }
5993
5994 static void
5995 stop_reply_dtr (struct notif_event *event)
5996 {
5997   struct stop_reply *r = (struct stop_reply *) event;
5998
5999   VEC_free (cached_reg_t, r->regcache);
6000 }
6001
6002 static struct notif_event *
6003 remote_notif_stop_alloc_reply (void)
6004 {
6005   /* We cast to a pointer to the "base class".  */
6006   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6007
6008   r->dtr = stop_reply_dtr;
6009
6010   return r;
6011 }
6012
6013 /* A client of notification Stop.  */
6014
6015 struct notif_client notif_client_stop =
6016 {
6017   "Stop",
6018   "vStopped",
6019   remote_notif_stop_parse,
6020   remote_notif_stop_ack,
6021   remote_notif_stop_can_get_pending_events,
6022   remote_notif_stop_alloc_reply,
6023   REMOTE_NOTIF_STOP,
6024 };
6025
6026 /* A parameter to pass data in and out.  */
6027
6028 struct queue_iter_param
6029 {
6030   void *input;
6031   struct stop_reply *output;
6032 };
6033
6034 /* Determine if THREAD is a pending fork parent thread.  ARG contains
6035    the pid of the process that owns the threads we want to check, or
6036    -1 if we want to check all threads.  */
6037
6038 static int
6039 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6040                         ptid_t thread_ptid)
6041 {
6042   if (ws->kind == TARGET_WAITKIND_FORKED
6043       || ws->kind == TARGET_WAITKIND_VFORKED)
6044     {
6045       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6046         return 1;
6047     }
6048
6049   return 0;
6050 }
6051
6052 /* Check whether EVENT is a fork event, and if it is, remove the
6053    fork child from the context list passed in DATA.  */
6054
6055 static int
6056 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6057                               QUEUE_ITER (stop_reply_p) *iter,
6058                               stop_reply_p event,
6059                               void *data)
6060 {
6061   struct queue_iter_param *param = (struct queue_iter_param *) data;
6062   struct threads_listing_context *context
6063     = (struct threads_listing_context *) param->input;
6064
6065   if (event->ws.kind == TARGET_WAITKIND_FORKED
6066       || event->ws.kind == TARGET_WAITKIND_VFORKED
6067       || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6068     threads_listing_context_remove (&event->ws, context);
6069
6070   return 1;
6071 }
6072
6073 /* If CONTEXT contains any fork child threads that have not been
6074    reported yet, remove them from the CONTEXT list.  If such a
6075    thread exists it is because we are stopped at a fork catchpoint
6076    and have not yet called follow_fork, which will set up the
6077    host-side data structures for the new process.  */
6078
6079 static void
6080 remove_new_fork_children (struct threads_listing_context *context)
6081 {
6082   struct thread_info * thread;
6083   int pid = -1;
6084   struct notif_client *notif = &notif_client_stop;
6085   struct queue_iter_param param;
6086
6087   /* For any threads stopped at a fork event, remove the corresponding
6088      fork child threads from the CONTEXT list.  */
6089   ALL_NON_EXITED_THREADS (thread)
6090     {
6091       struct target_waitstatus *ws = &thread->pending_follow;
6092
6093       if (is_pending_fork_parent (ws, pid, thread->ptid))
6094         {
6095           threads_listing_context_remove (ws, context);
6096         }
6097     }
6098
6099   /* Check for any pending fork events (not reported or processed yet)
6100      in process PID and remove those fork child threads from the
6101      CONTEXT list as well.  */
6102   remote_notif_get_pending_events (notif);
6103   param.input = context;
6104   param.output = NULL;
6105   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6106                  remove_child_of_pending_fork, &param);
6107 }
6108
6109 /* Remove stop replies in the queue if its pid is equal to the given
6110    inferior's pid.  */
6111
6112 static int
6113 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6114                                 QUEUE_ITER (stop_reply_p) *iter,
6115                                 stop_reply_p event,
6116                                 void *data)
6117 {
6118   struct queue_iter_param *param = (struct queue_iter_param *) data;
6119   struct inferior *inf = (struct inferior *) param->input;
6120
6121   if (ptid_get_pid (event->ptid) == inf->pid)
6122     {
6123       stop_reply_xfree (event);
6124       QUEUE_remove_elem (stop_reply_p, q, iter);
6125     }
6126
6127   return 1;
6128 }
6129
6130 /* Discard all pending stop replies of inferior INF.  */
6131
6132 static void
6133 discard_pending_stop_replies (struct inferior *inf)
6134 {
6135   int i;
6136   struct queue_iter_param param;
6137   struct stop_reply *reply;
6138   struct remote_state *rs = get_remote_state ();
6139   struct remote_notif_state *rns = rs->notif_state;
6140
6141   /* This function can be notified when an inferior exists.  When the
6142      target is not remote, the notification state is NULL.  */
6143   if (rs->remote_desc == NULL)
6144     return;
6145
6146   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6147
6148   /* Discard the in-flight notification.  */
6149   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6150     {
6151       stop_reply_xfree (reply);
6152       rns->pending_event[notif_client_stop.id] = NULL;
6153     }
6154
6155   param.input = inf;
6156   param.output = NULL;
6157   /* Discard the stop replies we have already pulled with
6158      vStopped.  */
6159   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6160                  remove_stop_reply_for_inferior, &param);
6161 }
6162
6163 /* If its remote state is equal to the given remote state,
6164    remove EVENT from the stop reply queue.  */
6165
6166 static int
6167 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6168                                    QUEUE_ITER (stop_reply_p) *iter,
6169                                    stop_reply_p event,
6170                                    void *data)
6171 {
6172   struct queue_iter_param *param = (struct queue_iter_param *) data;
6173   struct remote_state *rs = (struct remote_state *) param->input;
6174
6175   if (event->rs == rs)
6176     {
6177       stop_reply_xfree (event);
6178       QUEUE_remove_elem (stop_reply_p, q, iter);
6179     }
6180
6181   return 1;
6182 }
6183
6184 /* Discard the stop replies for RS in stop_reply_queue.  */
6185
6186 static void
6187 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6188 {
6189   struct queue_iter_param param;
6190
6191   param.input = rs;
6192   param.output = NULL;
6193   /* Discard the stop replies we have already pulled with
6194      vStopped.  */
6195   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6196                  remove_stop_reply_of_remote_state, &param);
6197 }
6198
6199 /* A parameter to pass data in and out.  */
6200
6201 static int
6202 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6203                                    QUEUE_ITER (stop_reply_p) *iter,
6204                                    stop_reply_p event,
6205                                    void *data)
6206 {
6207   struct queue_iter_param *param = (struct queue_iter_param *) data;
6208   ptid_t *ptid = (ptid_t *) param->input;
6209
6210   if (ptid_match (event->ptid, *ptid))
6211     {
6212       param->output = event;
6213       QUEUE_remove_elem (stop_reply_p, q, iter);
6214       return 0;
6215     }
6216
6217   return 1;
6218 }
6219
6220 /* Remove the first reply in 'stop_reply_queue' which matches
6221    PTID.  */
6222
6223 static struct stop_reply *
6224 remote_notif_remove_queued_reply (ptid_t ptid)
6225 {
6226   struct queue_iter_param param;
6227
6228   param.input = &ptid;
6229   param.output = NULL;
6230
6231   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6232                  remote_notif_remove_once_on_match, &param);
6233   if (notif_debug)
6234     fprintf_unfiltered (gdb_stdlog,
6235                         "notif: discard queued event: 'Stop' in %s\n",
6236                         target_pid_to_str (ptid));
6237
6238   return param.output;
6239 }
6240
6241 /* Look for a queued stop reply belonging to PTID.  If one is found,
6242    remove it from the queue, and return it.  Returns NULL if none is
6243    found.  If there are still queued events left to process, tell the
6244    event loop to get back to target_wait soon.  */
6245
6246 static struct stop_reply *
6247 queued_stop_reply (ptid_t ptid)
6248 {
6249   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6250
6251   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6252     /* There's still at least an event left.  */
6253     mark_async_event_handler (remote_async_inferior_event_token);
6254
6255   return r;
6256 }
6257
6258 /* Push a fully parsed stop reply in the stop reply queue.  Since we
6259    know that we now have at least one queued event left to pass to the
6260    core side, tell the event loop to get back to target_wait soon.  */
6261
6262 static void
6263 push_stop_reply (struct stop_reply *new_event)
6264 {
6265   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6266
6267   if (notif_debug)
6268     fprintf_unfiltered (gdb_stdlog,
6269                         "notif: push 'Stop' %s to queue %d\n",
6270                         target_pid_to_str (new_event->ptid),
6271                         QUEUE_length (stop_reply_p,
6272                                       stop_reply_queue));
6273
6274   mark_async_event_handler (remote_async_inferior_event_token);
6275 }
6276
6277 static int
6278 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6279                               QUEUE_ITER (stop_reply_p) *iter,
6280                               struct stop_reply *event,
6281                               void *data)
6282 {
6283   ptid_t *ptid = (ptid_t *) data;
6284
6285   return !(ptid_equal (*ptid, event->ptid)
6286            && event->ws.kind == TARGET_WAITKIND_STOPPED);
6287 }
6288
6289 /* Returns true if we have a stop reply for PTID.  */
6290
6291 static int
6292 peek_stop_reply (ptid_t ptid)
6293 {
6294   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6295                          stop_reply_match_ptid_and_ws, &ptid);
6296 }
6297
6298 /* Skip PACKET until the next semi-colon (or end of string).  */
6299
6300 static char *
6301 skip_to_semicolon (char *p)
6302 {
6303   while (*p != '\0' && *p != ';')
6304     p++;
6305   return p;
6306 }
6307
6308 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
6309    starting with P and ending with PEND matches PREFIX.  */
6310
6311 static int
6312 strprefix (const char *p, const char *pend, const char *prefix)
6313 {
6314   for ( ; p < pend; p++, prefix++)
6315     if (*p != *prefix)
6316       return 0;
6317   return *prefix == '\0';
6318 }
6319
6320 /* Parse the stop reply in BUF.  Either the function succeeds, and the
6321    result is stored in EVENT, or throws an error.  */
6322
6323 static void
6324 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6325 {
6326   struct remote_arch_state *rsa = get_remote_arch_state ();
6327   ULONGEST addr;
6328   char *p;
6329   int skipregs = 0;
6330
6331   event->ptid = null_ptid;
6332   event->rs = get_remote_state ();
6333   event->ws.kind = TARGET_WAITKIND_IGNORE;
6334   event->ws.value.integer = 0;
6335   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6336   event->regcache = NULL;
6337   event->core = -1;
6338
6339   switch (buf[0])
6340     {
6341     case 'T':           /* Status with PC, SP, FP, ...  */
6342       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
6343       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
6344             ss = signal number
6345             n... = register number
6346             r... = register contents
6347       */
6348
6349       p = &buf[3];      /* after Txx */
6350       while (*p)
6351         {
6352           char *p1;
6353           int fieldsize;
6354
6355           p1 = strchr (p, ':');
6356           if (p1 == NULL)
6357             error (_("Malformed packet(a) (missing colon): %s\n\
6358 Packet: '%s'\n"),
6359                    p, buf);
6360           if (p == p1)
6361             error (_("Malformed packet(a) (missing register number): %s\n\
6362 Packet: '%s'\n"),
6363                    p, buf);
6364
6365           /* Some "registers" are actually extended stop information.
6366              Note if you're adding a new entry here: GDB 7.9 and
6367              earlier assume that all register "numbers" that start
6368              with an hex digit are real register numbers.  Make sure
6369              the server only sends such a packet if it knows the
6370              client understands it.  */
6371
6372           if (strprefix (p, p1, "thread"))
6373             event->ptid = read_ptid (++p1, &p);
6374           else if (strprefix (p, p1, "watch")
6375                    || strprefix (p, p1, "rwatch")
6376                    || strprefix (p, p1, "awatch"))
6377             {
6378               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6379               p = unpack_varlen_hex (++p1, &addr);
6380               event->watch_data_address = (CORE_ADDR) addr;
6381             }
6382           else if (strprefix (p, p1, "swbreak"))
6383             {
6384               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6385
6386               /* Make sure the stub doesn't forget to indicate support
6387                  with qSupported.  */
6388               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6389                 error (_("Unexpected swbreak stop reason"));
6390
6391               /* The value part is documented as "must be empty",
6392                  though we ignore it, in case we ever decide to make
6393                  use of it in a backward compatible way.  */
6394               p = skip_to_semicolon (p1 + 1);
6395             }
6396           else if (strprefix (p, p1, "hwbreak"))
6397             {
6398               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6399
6400               /* Make sure the stub doesn't forget to indicate support
6401                  with qSupported.  */
6402               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6403                 error (_("Unexpected hwbreak stop reason"));
6404
6405               /* See above.  */
6406               p = skip_to_semicolon (p1 + 1);
6407             }
6408           else if (strprefix (p, p1, "library"))
6409             {
6410               event->ws.kind = TARGET_WAITKIND_LOADED;
6411               p = skip_to_semicolon (p1 + 1);
6412             }
6413           else if (strprefix (p, p1, "replaylog"))
6414             {
6415               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6416               /* p1 will indicate "begin" or "end", but it makes
6417                  no difference for now, so ignore it.  */
6418               p = skip_to_semicolon (p1 + 1);
6419             }
6420           else if (strprefix (p, p1, "core"))
6421             {
6422               ULONGEST c;
6423
6424               p = unpack_varlen_hex (++p1, &c);
6425               event->core = c;
6426             }
6427           else if (strprefix (p, p1, "fork"))
6428             {
6429               event->ws.value.related_pid = read_ptid (++p1, &p);
6430               event->ws.kind = TARGET_WAITKIND_FORKED;
6431             }
6432           else if (strprefix (p, p1, "vfork"))
6433             {
6434               event->ws.value.related_pid = read_ptid (++p1, &p);
6435               event->ws.kind = TARGET_WAITKIND_VFORKED;
6436             }
6437           else if (strprefix (p, p1, "vforkdone"))
6438             {
6439               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6440               p = skip_to_semicolon (p1 + 1);
6441             }
6442           else if (strprefix (p, p1, "exec"))
6443             {
6444               ULONGEST ignored;
6445               char pathname[PATH_MAX];
6446               int pathlen;
6447
6448               /* Determine the length of the execd pathname.  */
6449               p = unpack_varlen_hex (++p1, &ignored);
6450               pathlen = (p - p1) / 2;
6451
6452               /* Save the pathname for event reporting and for
6453                  the next run command.  */
6454               hex2bin (p1, (gdb_byte *) pathname, pathlen);
6455               pathname[pathlen] = '\0';
6456
6457               /* This is freed during event handling.  */
6458               event->ws.value.execd_pathname = xstrdup (pathname);
6459               event->ws.kind = TARGET_WAITKIND_EXECD;
6460
6461               /* Skip the registers included in this packet, since
6462                  they may be for an architecture different from the
6463                  one used by the original program.  */
6464               skipregs = 1;
6465             }
6466           else if (strprefix (p, p1, "create"))
6467             {
6468               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6469               p = skip_to_semicolon (p1 + 1);
6470             }
6471           else
6472             {
6473               ULONGEST pnum;
6474               char *p_temp;
6475
6476               if (skipregs)
6477                 {
6478                   p = skip_to_semicolon (p1 + 1);
6479                   p++;
6480                   continue;
6481                 }
6482
6483               /* Maybe a real ``P'' register number.  */
6484               p_temp = unpack_varlen_hex (p, &pnum);
6485               /* If the first invalid character is the colon, we got a
6486                  register number.  Otherwise, it's an unknown stop
6487                  reason.  */
6488               if (p_temp == p1)
6489                 {
6490                   struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6491                   cached_reg_t cached_reg;
6492
6493                   if (reg == NULL)
6494                     error (_("Remote sent bad register number %s: %s\n\
6495 Packet: '%s'\n"),
6496                            hex_string (pnum), p, buf);
6497
6498                   cached_reg.num = reg->regnum;
6499
6500                   p = p1 + 1;
6501                   fieldsize = hex2bin (p, cached_reg.data,
6502                                        register_size (target_gdbarch (),
6503                                                       reg->regnum));
6504                   p += 2 * fieldsize;
6505                   if (fieldsize < register_size (target_gdbarch (),
6506                                                  reg->regnum))
6507                     warning (_("Remote reply is too short: %s"), buf);
6508
6509                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6510                 }
6511               else
6512                 {
6513                   /* Not a number.  Silently skip unknown optional
6514                      info.  */
6515                   p = skip_to_semicolon (p1 + 1);
6516                 }
6517             }
6518
6519           if (*p != ';')
6520             error (_("Remote register badly formatted: %s\nhere: %s"),
6521                    buf, p);
6522           ++p;
6523         }
6524
6525       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6526         break;
6527
6528       /* fall through */
6529     case 'S':           /* Old style status, just signal only.  */
6530       {
6531         int sig;
6532
6533         event->ws.kind = TARGET_WAITKIND_STOPPED;
6534         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6535         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6536           event->ws.value.sig = (enum gdb_signal) sig;
6537         else
6538           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6539       }
6540       break;
6541     case 'w':           /* Thread exited.  */
6542       {
6543         char *p;
6544         ULONGEST value;
6545
6546         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6547         p = unpack_varlen_hex (&buf[1], &value);
6548         event->ws.value.integer = value;
6549         if (*p != ';')
6550           error (_("stop reply packet badly formatted: %s"), buf);
6551         event->ptid = read_ptid (++p, NULL);
6552         break;
6553       }
6554     case 'W':           /* Target exited.  */
6555     case 'X':
6556       {
6557         char *p;
6558         int pid;
6559         ULONGEST value;
6560
6561         /* GDB used to accept only 2 hex chars here.  Stubs should
6562            only send more if they detect GDB supports multi-process
6563            support.  */
6564         p = unpack_varlen_hex (&buf[1], &value);
6565
6566         if (buf[0] == 'W')
6567           {
6568             /* The remote process exited.  */
6569             event->ws.kind = TARGET_WAITKIND_EXITED;
6570             event->ws.value.integer = value;
6571           }
6572         else
6573           {
6574             /* The remote process exited with a signal.  */
6575             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6576             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6577               event->ws.value.sig = (enum gdb_signal) value;
6578             else
6579               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6580           }
6581
6582         /* If no process is specified, assume inferior_ptid.  */
6583         pid = ptid_get_pid (inferior_ptid);
6584         if (*p == '\0')
6585           ;
6586         else if (*p == ';')
6587           {
6588             p++;
6589
6590             if (*p == '\0')
6591               ;
6592             else if (startswith (p, "process:"))
6593               {
6594                 ULONGEST upid;
6595
6596                 p += sizeof ("process:") - 1;
6597                 unpack_varlen_hex (p, &upid);
6598                 pid = upid;
6599               }
6600             else
6601               error (_("unknown stop reply packet: %s"), buf);
6602           }
6603         else
6604           error (_("unknown stop reply packet: %s"), buf);
6605         event->ptid = pid_to_ptid (pid);
6606       }
6607       break;
6608     case 'N':
6609       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6610       event->ptid = minus_one_ptid;
6611       break;
6612     }
6613
6614   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6615     error (_("No process or thread specified in stop reply: %s"), buf);
6616 }
6617
6618 /* When the stub wants to tell GDB about a new notification reply, it
6619    sends a notification (%Stop, for example).  Those can come it at
6620    any time, hence, we have to make sure that any pending
6621    putpkt/getpkt sequence we're making is finished, before querying
6622    the stub for more events with the corresponding ack command
6623    (vStopped, for example).  E.g., if we started a vStopped sequence
6624    immediately upon receiving the notification, something like this
6625    could happen:
6626
6627     1.1) --> Hg 1
6628     1.2) <-- OK
6629     1.3) --> g
6630     1.4) <-- %Stop
6631     1.5) --> vStopped
6632     1.6) <-- (registers reply to step #1.3)
6633
6634    Obviously, the reply in step #1.6 would be unexpected to a vStopped
6635    query.
6636
6637    To solve this, whenever we parse a %Stop notification successfully,
6638    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6639    doing whatever we were doing:
6640
6641     2.1) --> Hg 1
6642     2.2) <-- OK
6643     2.3) --> g
6644     2.4) <-- %Stop
6645       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6646     2.5) <-- (registers reply to step #2.3)
6647
6648    Eventualy after step #2.5, we return to the event loop, which
6649    notices there's an event on the
6650    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6651    associated callback --- the function below.  At this point, we're
6652    always safe to start a vStopped sequence. :
6653
6654     2.6) --> vStopped
6655     2.7) <-- T05 thread:2
6656     2.8) --> vStopped
6657     2.9) --> OK
6658 */
6659
6660 void
6661 remote_notif_get_pending_events (struct notif_client *nc)
6662 {
6663   struct remote_state *rs = get_remote_state ();
6664
6665   if (rs->notif_state->pending_event[nc->id] != NULL)
6666     {
6667       if (notif_debug)
6668         fprintf_unfiltered (gdb_stdlog,
6669                             "notif: process: '%s' ack pending event\n",
6670                             nc->name);
6671
6672       /* acknowledge */
6673       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6674       rs->notif_state->pending_event[nc->id] = NULL;
6675
6676       while (1)
6677         {
6678           getpkt (&rs->buf, &rs->buf_size, 0);
6679           if (strcmp (rs->buf, "OK") == 0)
6680             break;
6681           else
6682             remote_notif_ack (nc, rs->buf);
6683         }
6684     }
6685   else
6686     {
6687       if (notif_debug)
6688         fprintf_unfiltered (gdb_stdlog,
6689                             "notif: process: '%s' no pending reply\n",
6690                             nc->name);
6691     }
6692 }
6693
6694 /* Called when it is decided that STOP_REPLY holds the info of the
6695    event that is to be returned to the core.  This function always
6696    destroys STOP_REPLY.  */
6697
6698 static ptid_t
6699 process_stop_reply (struct stop_reply *stop_reply,
6700                     struct target_waitstatus *status)
6701 {
6702   ptid_t ptid;
6703
6704   *status = stop_reply->ws;
6705   ptid = stop_reply->ptid;
6706
6707   /* If no thread/process was reported by the stub, assume the current
6708      inferior.  */
6709   if (ptid_equal (ptid, null_ptid))
6710     ptid = inferior_ptid;
6711
6712   if (status->kind != TARGET_WAITKIND_EXITED
6713       && status->kind != TARGET_WAITKIND_SIGNALLED
6714       && status->kind != TARGET_WAITKIND_NO_RESUMED)
6715     {
6716       struct remote_state *rs = get_remote_state ();
6717       struct private_thread_info *remote_thr;
6718
6719       /* Expedited registers.  */
6720       if (stop_reply->regcache)
6721         {
6722           struct regcache *regcache
6723             = get_thread_arch_regcache (ptid, target_gdbarch ());
6724           cached_reg_t *reg;
6725           int ix;
6726
6727           for (ix = 0;
6728                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6729                ix++)
6730             regcache_raw_supply (regcache, reg->num, reg->data);
6731           VEC_free (cached_reg_t, stop_reply->regcache);
6732         }
6733
6734       remote_notice_new_inferior (ptid, 0);
6735       remote_thr = demand_private_info (ptid);
6736       remote_thr->core = stop_reply->core;
6737       remote_thr->stop_reason = stop_reply->stop_reason;
6738       remote_thr->watch_data_address = stop_reply->watch_data_address;
6739     }
6740
6741   stop_reply_xfree (stop_reply);
6742   return ptid;
6743 }
6744
6745 /* The non-stop mode version of target_wait.  */
6746
6747 static ptid_t
6748 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6749 {
6750   struct remote_state *rs = get_remote_state ();
6751   struct stop_reply *stop_reply;
6752   int ret;
6753   int is_notif = 0;
6754
6755   /* If in non-stop mode, get out of getpkt even if a
6756      notification is received.  */
6757
6758   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6759                               0 /* forever */, &is_notif);
6760   while (1)
6761     {
6762       if (ret != -1 && !is_notif)
6763         switch (rs->buf[0])
6764           {
6765           case 'E':             /* Error of some sort.  */
6766             /* We're out of sync with the target now.  Did it continue
6767                or not?  We can't tell which thread it was in non-stop,
6768                so just ignore this.  */
6769             warning (_("Remote failure reply: %s"), rs->buf);
6770             break;
6771           case 'O':             /* Console output.  */
6772             remote_console_output (rs->buf + 1);
6773             break;
6774           default:
6775             warning (_("Invalid remote reply: %s"), rs->buf);
6776             break;
6777           }
6778
6779       /* Acknowledge a pending stop reply that may have arrived in the
6780          mean time.  */
6781       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6782         remote_notif_get_pending_events (&notif_client_stop);
6783
6784       /* If indeed we noticed a stop reply, we're done.  */
6785       stop_reply = queued_stop_reply (ptid);
6786       if (stop_reply != NULL)
6787         return process_stop_reply (stop_reply, status);
6788
6789       /* Still no event.  If we're just polling for an event, then
6790          return to the event loop.  */
6791       if (options & TARGET_WNOHANG)
6792         {
6793           status->kind = TARGET_WAITKIND_IGNORE;
6794           return minus_one_ptid;
6795         }
6796
6797       /* Otherwise do a blocking wait.  */
6798       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6799                                   1 /* forever */, &is_notif);
6800     }
6801 }
6802
6803 /* Wait until the remote machine stops, then return, storing status in
6804    STATUS just as `wait' would.  */
6805
6806 static ptid_t
6807 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6808 {
6809   struct remote_state *rs = get_remote_state ();
6810   ptid_t event_ptid = null_ptid;
6811   char *buf;
6812   struct stop_reply *stop_reply;
6813
6814  again:
6815
6816   status->kind = TARGET_WAITKIND_IGNORE;
6817   status->value.integer = 0;
6818
6819   stop_reply = queued_stop_reply (ptid);
6820   if (stop_reply != NULL)
6821     return process_stop_reply (stop_reply, status);
6822
6823   if (rs->cached_wait_status)
6824     /* Use the cached wait status, but only once.  */
6825     rs->cached_wait_status = 0;
6826   else
6827     {
6828       int ret;
6829       int is_notif;
6830       int forever = ((options & TARGET_WNOHANG) == 0
6831                      && wait_forever_enabled_p);
6832
6833       if (!rs->waiting_for_stop_reply)
6834         {
6835           status->kind = TARGET_WAITKIND_NO_RESUMED;
6836           return minus_one_ptid;
6837         }
6838
6839       if (!target_is_async_p ())
6840         {
6841           ofunc = signal (SIGINT, sync_remote_interrupt);
6842           /* If the user hit C-c before this packet, or between packets,
6843              pretend that it was hit right here.  */
6844           if (check_quit_flag ())
6845             {
6846               clear_quit_flag ();
6847               sync_remote_interrupt (SIGINT);
6848             }
6849         }
6850
6851       /* FIXME: cagney/1999-09-27: If we're in async mode we should
6852          _never_ wait for ever -> test on target_is_async_p().
6853          However, before we do that we need to ensure that the caller
6854          knows how to take the target into/out of async mode.  */
6855       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6856                                   forever, &is_notif);
6857
6858       if (!target_is_async_p ())
6859         signal (SIGINT, ofunc);
6860
6861       /* GDB gets a notification.  Return to core as this event is
6862          not interesting.  */
6863       if (ret != -1 && is_notif)
6864         return minus_one_ptid;
6865
6866       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6867         return minus_one_ptid;
6868     }
6869
6870   buf = rs->buf;
6871
6872   /* Assume that the target has acknowledged Ctrl-C unless we receive
6873      an 'F' or 'O' packet.  */
6874   if (buf[0] != 'F' && buf[0] != 'O')
6875     rs->ctrlc_pending_p = 0;
6876
6877   switch (buf[0])
6878     {
6879     case 'E':           /* Error of some sort.  */
6880       /* We're out of sync with the target now.  Did it continue or
6881          not?  Not is more likely, so report a stop.  */
6882       rs->waiting_for_stop_reply = 0;
6883
6884       warning (_("Remote failure reply: %s"), buf);
6885       status->kind = TARGET_WAITKIND_STOPPED;
6886       status->value.sig = GDB_SIGNAL_0;
6887       break;
6888     case 'F':           /* File-I/O request.  */
6889       remote_fileio_request (buf, rs->ctrlc_pending_p);
6890       rs->ctrlc_pending_p = 0;
6891       break;
6892     case 'N': case 'T': case 'S': case 'X': case 'W':
6893       {
6894         struct stop_reply *stop_reply;
6895
6896         /* There is a stop reply to handle.  */
6897         rs->waiting_for_stop_reply = 0;
6898
6899         stop_reply
6900           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6901                                                       rs->buf);
6902
6903         event_ptid = process_stop_reply (stop_reply, status);
6904         break;
6905       }
6906     case 'O':           /* Console output.  */
6907       remote_console_output (buf + 1);
6908       break;
6909     case '\0':
6910       if (rs->last_sent_signal != GDB_SIGNAL_0)
6911         {
6912           /* Zero length reply means that we tried 'S' or 'C' and the
6913              remote system doesn't support it.  */
6914           target_terminal_ours_for_output ();
6915           printf_filtered
6916             ("Can't send signals to this remote system.  %s not sent.\n",
6917              gdb_signal_to_name (rs->last_sent_signal));
6918           rs->last_sent_signal = GDB_SIGNAL_0;
6919           target_terminal_inferior ();
6920
6921           strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6922           putpkt ((char *) buf);
6923           break;
6924         }
6925       /* else fallthrough */
6926     default:
6927       warning (_("Invalid remote reply: %s"), buf);
6928       break;
6929     }
6930
6931   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
6932     return minus_one_ptid;
6933   else if (status->kind == TARGET_WAITKIND_IGNORE)
6934     {
6935       /* Nothing interesting happened.  If we're doing a non-blocking
6936          poll, we're done.  Otherwise, go back to waiting.  */
6937       if (options & TARGET_WNOHANG)
6938         return minus_one_ptid;
6939       else
6940         goto again;
6941     }
6942   else if (status->kind != TARGET_WAITKIND_EXITED
6943            && status->kind != TARGET_WAITKIND_SIGNALLED)
6944     {
6945       if (!ptid_equal (event_ptid, null_ptid))
6946         record_currthread (rs, event_ptid);
6947       else
6948         event_ptid = inferior_ptid;
6949     }
6950   else
6951     /* A process exit.  Invalidate our notion of current thread.  */
6952     record_currthread (rs, minus_one_ptid);
6953
6954   return event_ptid;
6955 }
6956
6957 /* Wait until the remote machine stops, then return, storing status in
6958    STATUS just as `wait' would.  */
6959
6960 static ptid_t
6961 remote_wait (struct target_ops *ops,
6962              ptid_t ptid, struct target_waitstatus *status, int options)
6963 {
6964   ptid_t event_ptid;
6965
6966   if (target_is_non_stop_p ())
6967     event_ptid = remote_wait_ns (ptid, status, options);
6968   else
6969     event_ptid = remote_wait_as (ptid, status, options);
6970
6971   if (target_is_async_p ())
6972     {
6973       /* If there are are events left in the queue tell the event loop
6974          to return here.  */
6975       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6976         mark_async_event_handler (remote_async_inferior_event_token);
6977     }
6978
6979   return event_ptid;
6980 }
6981
6982 /* Fetch a single register using a 'p' packet.  */
6983
6984 static int
6985 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6986 {
6987   struct remote_state *rs = get_remote_state ();
6988   char *buf, *p;
6989   char regp[MAX_REGISTER_SIZE];
6990   int i;
6991
6992   if (packet_support (PACKET_p) == PACKET_DISABLE)
6993     return 0;
6994
6995   if (reg->pnum == -1)
6996     return 0;
6997
6998   p = rs->buf;
6999   *p++ = 'p';
7000   p += hexnumstr (p, reg->pnum);
7001   *p++ = '\0';
7002   putpkt (rs->buf);
7003   getpkt (&rs->buf, &rs->buf_size, 0);
7004
7005   buf = rs->buf;
7006
7007   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7008     {
7009     case PACKET_OK:
7010       break;
7011     case PACKET_UNKNOWN:
7012       return 0;
7013     case PACKET_ERROR:
7014       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7015              gdbarch_register_name (get_regcache_arch (regcache), 
7016                                     reg->regnum), 
7017              buf);
7018     }
7019
7020   /* If this register is unfetchable, tell the regcache.  */
7021   if (buf[0] == 'x')
7022     {
7023       regcache_raw_supply (regcache, reg->regnum, NULL);
7024       return 1;
7025     }
7026
7027   /* Otherwise, parse and supply the value.  */
7028   p = buf;
7029   i = 0;
7030   while (p[0] != 0)
7031     {
7032       if (p[1] == 0)
7033         error (_("fetch_register_using_p: early buf termination"));
7034
7035       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7036       p += 2;
7037     }
7038   regcache_raw_supply (regcache, reg->regnum, regp);
7039   return 1;
7040 }
7041
7042 /* Fetch the registers included in the target's 'g' packet.  */
7043
7044 static int
7045 send_g_packet (void)
7046 {
7047   struct remote_state *rs = get_remote_state ();
7048   int buf_len;
7049
7050   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7051   remote_send (&rs->buf, &rs->buf_size);
7052
7053   /* We can get out of synch in various cases.  If the first character
7054      in the buffer is not a hex character, assume that has happened
7055      and try to fetch another packet to read.  */
7056   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7057          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7058          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7059          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
7060     {
7061       if (remote_debug)
7062         fprintf_unfiltered (gdb_stdlog,
7063                             "Bad register packet; fetching a new packet\n");
7064       getpkt (&rs->buf, &rs->buf_size, 0);
7065     }
7066
7067   buf_len = strlen (rs->buf);
7068
7069   /* Sanity check the received packet.  */
7070   if (buf_len % 2 != 0)
7071     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7072
7073   return buf_len / 2;
7074 }
7075
7076 static void
7077 process_g_packet (struct regcache *regcache)
7078 {
7079   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7080   struct remote_state *rs = get_remote_state ();
7081   struct remote_arch_state *rsa = get_remote_arch_state ();
7082   int i, buf_len;
7083   char *p;
7084   char *regs;
7085
7086   buf_len = strlen (rs->buf);
7087
7088   /* Further sanity checks, with knowledge of the architecture.  */
7089   if (buf_len > 2 * rsa->sizeof_g_packet)
7090     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7091
7092   /* Save the size of the packet sent to us by the target.  It is used
7093      as a heuristic when determining the max size of packets that the
7094      target can safely receive.  */
7095   if (rsa->actual_register_packet_size == 0)
7096     rsa->actual_register_packet_size = buf_len;
7097
7098   /* If this is smaller than we guessed the 'g' packet would be,
7099      update our records.  A 'g' reply that doesn't include a register's
7100      value implies either that the register is not available, or that
7101      the 'p' packet must be used.  */
7102   if (buf_len < 2 * rsa->sizeof_g_packet)
7103     {
7104       rsa->sizeof_g_packet = buf_len / 2;
7105
7106       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7107         {
7108           if (rsa->regs[i].pnum == -1)
7109             continue;
7110
7111           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7112             rsa->regs[i].in_g_packet = 0;
7113           else
7114             rsa->regs[i].in_g_packet = 1;
7115         }
7116     }
7117
7118   regs = (char *) alloca (rsa->sizeof_g_packet);
7119
7120   /* Unimplemented registers read as all bits zero.  */
7121   memset (regs, 0, rsa->sizeof_g_packet);
7122
7123   /* Reply describes registers byte by byte, each byte encoded as two
7124      hex characters.  Suck them all up, then supply them to the
7125      register cacheing/storage mechanism.  */
7126
7127   p = rs->buf;
7128   for (i = 0; i < rsa->sizeof_g_packet; i++)
7129     {
7130       if (p[0] == 0 || p[1] == 0)
7131         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
7132         internal_error (__FILE__, __LINE__,
7133                         _("unexpected end of 'g' packet reply"));
7134
7135       if (p[0] == 'x' && p[1] == 'x')
7136         regs[i] = 0;            /* 'x' */
7137       else
7138         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7139       p += 2;
7140     }
7141
7142   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7143     {
7144       struct packet_reg *r = &rsa->regs[i];
7145
7146       if (r->in_g_packet)
7147         {
7148           if (r->offset * 2 >= strlen (rs->buf))
7149             /* This shouldn't happen - we adjusted in_g_packet above.  */
7150             internal_error (__FILE__, __LINE__,
7151                             _("unexpected end of 'g' packet reply"));
7152           else if (rs->buf[r->offset * 2] == 'x')
7153             {
7154               gdb_assert (r->offset * 2 < strlen (rs->buf));
7155               /* The register isn't available, mark it as such (at
7156                  the same time setting the value to zero).  */
7157               regcache_raw_supply (regcache, r->regnum, NULL);
7158             }
7159           else
7160             regcache_raw_supply (regcache, r->regnum,
7161                                  regs + r->offset);
7162         }
7163     }
7164 }
7165
7166 static void
7167 fetch_registers_using_g (struct regcache *regcache)
7168 {
7169   send_g_packet ();
7170   process_g_packet (regcache);
7171 }
7172
7173 /* Make the remote selected traceframe match GDB's selected
7174    traceframe.  */
7175
7176 static void
7177 set_remote_traceframe (void)
7178 {
7179   int newnum;
7180   struct remote_state *rs = get_remote_state ();
7181
7182   if (rs->remote_traceframe_number == get_traceframe_number ())
7183     return;
7184
7185   /* Avoid recursion, remote_trace_find calls us again.  */
7186   rs->remote_traceframe_number = get_traceframe_number ();
7187
7188   newnum = target_trace_find (tfind_number,
7189                               get_traceframe_number (), 0, 0, NULL);
7190
7191   /* Should not happen.  If it does, all bets are off.  */
7192   if (newnum != get_traceframe_number ())
7193     warning (_("could not set remote traceframe"));
7194 }
7195
7196 static void
7197 remote_fetch_registers (struct target_ops *ops,
7198                         struct regcache *regcache, int regnum)
7199 {
7200   struct remote_arch_state *rsa = get_remote_arch_state ();
7201   int i;
7202
7203   set_remote_traceframe ();
7204   set_general_thread (inferior_ptid);
7205
7206   if (regnum >= 0)
7207     {
7208       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7209
7210       gdb_assert (reg != NULL);
7211
7212       /* If this register might be in the 'g' packet, try that first -
7213          we are likely to read more than one register.  If this is the
7214          first 'g' packet, we might be overly optimistic about its
7215          contents, so fall back to 'p'.  */
7216       if (reg->in_g_packet)
7217         {
7218           fetch_registers_using_g (regcache);
7219           if (reg->in_g_packet)
7220             return;
7221         }
7222
7223       if (fetch_register_using_p (regcache, reg))
7224         return;
7225
7226       /* This register is not available.  */
7227       regcache_raw_supply (regcache, reg->regnum, NULL);
7228
7229       return;
7230     }
7231
7232   fetch_registers_using_g (regcache);
7233
7234   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7235     if (!rsa->regs[i].in_g_packet)
7236       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7237         {
7238           /* This register is not available.  */
7239           regcache_raw_supply (regcache, i, NULL);
7240         }
7241 }
7242
7243 /* Prepare to store registers.  Since we may send them all (using a
7244    'G' request), we have to read out the ones we don't want to change
7245    first.  */
7246
7247 static void
7248 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7249 {
7250   struct remote_arch_state *rsa = get_remote_arch_state ();
7251   int i;
7252   gdb_byte buf[MAX_REGISTER_SIZE];
7253
7254   /* Make sure the entire registers array is valid.  */
7255   switch (packet_support (PACKET_P))
7256     {
7257     case PACKET_DISABLE:
7258     case PACKET_SUPPORT_UNKNOWN:
7259       /* Make sure all the necessary registers are cached.  */
7260       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7261         if (rsa->regs[i].in_g_packet)
7262           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7263       break;
7264     case PACKET_ENABLE:
7265       break;
7266     }
7267 }
7268
7269 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
7270    packet was not recognized.  */
7271
7272 static int
7273 store_register_using_P (const struct regcache *regcache, 
7274                         struct packet_reg *reg)
7275 {
7276   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7277   struct remote_state *rs = get_remote_state ();
7278   /* Try storing a single register.  */
7279   char *buf = rs->buf;
7280   gdb_byte regp[MAX_REGISTER_SIZE];
7281   char *p;
7282
7283   if (packet_support (PACKET_P) == PACKET_DISABLE)
7284     return 0;
7285
7286   if (reg->pnum == -1)
7287     return 0;
7288
7289   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7290   p = buf + strlen (buf);
7291   regcache_raw_collect (regcache, reg->regnum, regp);
7292   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7293   putpkt (rs->buf);
7294   getpkt (&rs->buf, &rs->buf_size, 0);
7295
7296   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7297     {
7298     case PACKET_OK:
7299       return 1;
7300     case PACKET_ERROR:
7301       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7302              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7303     case PACKET_UNKNOWN:
7304       return 0;
7305     default:
7306       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7307     }
7308 }
7309
7310 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7311    contents of the register cache buffer.  FIXME: ignores errors.  */
7312
7313 static void
7314 store_registers_using_G (const struct regcache *regcache)
7315 {
7316   struct remote_state *rs = get_remote_state ();
7317   struct remote_arch_state *rsa = get_remote_arch_state ();
7318   gdb_byte *regs;
7319   char *p;
7320
7321   /* Extract all the registers in the regcache copying them into a
7322      local buffer.  */
7323   {
7324     int i;
7325
7326     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7327     memset (regs, 0, rsa->sizeof_g_packet);
7328     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7329       {
7330         struct packet_reg *r = &rsa->regs[i];
7331
7332         if (r->in_g_packet)
7333           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7334       }
7335   }
7336
7337   /* Command describes registers byte by byte,
7338      each byte encoded as two hex characters.  */
7339   p = rs->buf;
7340   *p++ = 'G';
7341   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7342      updated.  */
7343   bin2hex (regs, p, rsa->sizeof_g_packet);
7344   putpkt (rs->buf);
7345   getpkt (&rs->buf, &rs->buf_size, 0);
7346   if (packet_check_result (rs->buf) == PACKET_ERROR)
7347     error (_("Could not write registers; remote failure reply '%s'"), 
7348            rs->buf);
7349 }
7350
7351 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7352    of the register cache buffer.  FIXME: ignores errors.  */
7353
7354 static void
7355 remote_store_registers (struct target_ops *ops,
7356                         struct regcache *regcache, int regnum)
7357 {
7358   struct remote_arch_state *rsa = get_remote_arch_state ();
7359   int i;
7360
7361   set_remote_traceframe ();
7362   set_general_thread (inferior_ptid);
7363
7364   if (regnum >= 0)
7365     {
7366       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7367
7368       gdb_assert (reg != NULL);
7369
7370       /* Always prefer to store registers using the 'P' packet if
7371          possible; we often change only a small number of registers.
7372          Sometimes we change a larger number; we'd need help from a
7373          higher layer to know to use 'G'.  */
7374       if (store_register_using_P (regcache, reg))
7375         return;
7376
7377       /* For now, don't complain if we have no way to write the
7378          register.  GDB loses track of unavailable registers too
7379          easily.  Some day, this may be an error.  We don't have
7380          any way to read the register, either...  */
7381       if (!reg->in_g_packet)
7382         return;
7383
7384       store_registers_using_G (regcache);
7385       return;
7386     }
7387
7388   store_registers_using_G (regcache);
7389
7390   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7391     if (!rsa->regs[i].in_g_packet)
7392       if (!store_register_using_P (regcache, &rsa->regs[i]))
7393         /* See above for why we do not issue an error here.  */
7394         continue;
7395 }
7396 \f
7397
7398 /* Return the number of hex digits in num.  */
7399
7400 static int
7401 hexnumlen (ULONGEST num)
7402 {
7403   int i;
7404
7405   for (i = 0; num != 0; i++)
7406     num >>= 4;
7407
7408   return max (i, 1);
7409 }
7410
7411 /* Set BUF to the minimum number of hex digits representing NUM.  */
7412
7413 static int
7414 hexnumstr (char *buf, ULONGEST num)
7415 {
7416   int len = hexnumlen (num);
7417
7418   return hexnumnstr (buf, num, len);
7419 }
7420
7421
7422 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
7423
7424 static int
7425 hexnumnstr (char *buf, ULONGEST num, int width)
7426 {
7427   int i;
7428
7429   buf[width] = '\0';
7430
7431   for (i = width - 1; i >= 0; i--)
7432     {
7433       buf[i] = "0123456789abcdef"[(num & 0xf)];
7434       num >>= 4;
7435     }
7436
7437   return width;
7438 }
7439
7440 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
7441
7442 static CORE_ADDR
7443 remote_address_masked (CORE_ADDR addr)
7444 {
7445   unsigned int address_size = remote_address_size;
7446
7447   /* If "remoteaddresssize" was not set, default to target address size.  */
7448   if (!address_size)
7449     address_size = gdbarch_addr_bit (target_gdbarch ());
7450
7451   if (address_size > 0
7452       && address_size < (sizeof (ULONGEST) * 8))
7453     {
7454       /* Only create a mask when that mask can safely be constructed
7455          in a ULONGEST variable.  */
7456       ULONGEST mask = 1;
7457
7458       mask = (mask << address_size) - 1;
7459       addr &= mask;
7460     }
7461   return addr;
7462 }
7463
7464 /* Determine whether the remote target supports binary downloading.
7465    This is accomplished by sending a no-op memory write of zero length
7466    to the target at the specified address. It does not suffice to send
7467    the whole packet, since many stubs strip the eighth bit and
7468    subsequently compute a wrong checksum, which causes real havoc with
7469    remote_write_bytes.
7470
7471    NOTE: This can still lose if the serial line is not eight-bit
7472    clean.  In cases like this, the user should clear "remote
7473    X-packet".  */
7474
7475 static void
7476 check_binary_download (CORE_ADDR addr)
7477 {
7478   struct remote_state *rs = get_remote_state ();
7479
7480   switch (packet_support (PACKET_X))
7481     {
7482     case PACKET_DISABLE:
7483       break;
7484     case PACKET_ENABLE:
7485       break;
7486     case PACKET_SUPPORT_UNKNOWN:
7487       {
7488         char *p;
7489
7490         p = rs->buf;
7491         *p++ = 'X';
7492         p += hexnumstr (p, (ULONGEST) addr);
7493         *p++ = ',';
7494         p += hexnumstr (p, (ULONGEST) 0);
7495         *p++ = ':';
7496         *p = '\0';
7497
7498         putpkt_binary (rs->buf, (int) (p - rs->buf));
7499         getpkt (&rs->buf, &rs->buf_size, 0);
7500
7501         if (rs->buf[0] == '\0')
7502           {
7503             if (remote_debug)
7504               fprintf_unfiltered (gdb_stdlog,
7505                                   "binary downloading NOT "
7506                                   "supported by target\n");
7507             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7508           }
7509         else
7510           {
7511             if (remote_debug)
7512               fprintf_unfiltered (gdb_stdlog,
7513                                   "binary downloading supported by target\n");
7514             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7515           }
7516         break;
7517       }
7518     }
7519 }
7520
7521 /* Helper function to resize the payload in order to try to get a good
7522    alignment.  We try to write an amount of data such that the next write will
7523    start on an address aligned on REMOTE_ALIGN_WRITES.  */
7524
7525 static int
7526 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7527 {
7528   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7529 }
7530
7531 /* Write memory data directly to the remote machine.
7532    This does not inform the data cache; the data cache uses this.
7533    HEADER is the starting part of the packet.
7534    MEMADDR is the address in the remote memory space.
7535    MYADDR is the address of the buffer in our space.
7536    LEN_UNITS is the number of addressable units to write.
7537    UNIT_SIZE is the length in bytes of an addressable unit.
7538    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7539    should send data as binary ('X'), or hex-encoded ('M').
7540
7541    The function creates packet of the form
7542        <HEADER><ADDRESS>,<LENGTH>:<DATA>
7543
7544    where encoding of <DATA> is terminated by PACKET_FORMAT.
7545
7546    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7547    are omitted.
7548
7549    Return the transferred status, error or OK (an
7550    'enum target_xfer_status' value).  Save the number of addressable units
7551    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
7552
7553    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7554    exchange between gdb and the stub could look like (?? in place of the
7555    checksum):
7556
7557    -> $m1000,4#??
7558    <- aaaabbbbccccdddd
7559
7560    -> $M1000,3:eeeeffffeeee#??
7561    <- OK
7562
7563    -> $m1000,4#??
7564    <- eeeeffffeeeedddd  */
7565
7566 static enum target_xfer_status
7567 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7568                         const gdb_byte *myaddr, ULONGEST len_units,
7569                         int unit_size, ULONGEST *xfered_len_units,
7570                         char packet_format, int use_length)
7571 {
7572   struct remote_state *rs = get_remote_state ();
7573   char *p;
7574   char *plen = NULL;
7575   int plenlen = 0;
7576   int todo_units;
7577   int units_written;
7578   int payload_capacity_bytes;
7579   int payload_length_bytes;
7580
7581   if (packet_format != 'X' && packet_format != 'M')
7582     internal_error (__FILE__, __LINE__,
7583                     _("remote_write_bytes_aux: bad packet format"));
7584
7585   if (len_units == 0)
7586     return TARGET_XFER_EOF;
7587
7588   payload_capacity_bytes = get_memory_write_packet_size ();
7589
7590   /* The packet buffer will be large enough for the payload;
7591      get_memory_packet_size ensures this.  */
7592   rs->buf[0] = '\0';
7593
7594   /* Compute the size of the actual payload by subtracting out the
7595      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
7596
7597   payload_capacity_bytes -= strlen ("$,:#NN");
7598   if (!use_length)
7599     /* The comma won't be used.  */
7600     payload_capacity_bytes += 1;
7601   payload_capacity_bytes -= strlen (header);
7602   payload_capacity_bytes -= hexnumlen (memaddr);
7603
7604   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
7605
7606   strcat (rs->buf, header);
7607   p = rs->buf + strlen (header);
7608
7609   /* Compute a best guess of the number of bytes actually transfered.  */
7610   if (packet_format == 'X')
7611     {
7612       /* Best guess at number of bytes that will fit.  */
7613       todo_units = min (len_units, payload_capacity_bytes / unit_size);
7614       if (use_length)
7615         payload_capacity_bytes -= hexnumlen (todo_units);
7616       todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7617     }
7618   else
7619     {
7620       /* Number of bytes that will fit.  */
7621       todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7622       if (use_length)
7623         payload_capacity_bytes -= hexnumlen (todo_units);
7624       todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7625     }
7626
7627   if (todo_units <= 0)
7628     internal_error (__FILE__, __LINE__,
7629                     _("minimum packet size too small to write data"));
7630
7631   /* If we already need another packet, then try to align the end
7632      of this packet to a useful boundary.  */
7633   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7634     todo_units = align_for_efficient_write (todo_units, memaddr);
7635
7636   /* Append "<memaddr>".  */
7637   memaddr = remote_address_masked (memaddr);
7638   p += hexnumstr (p, (ULONGEST) memaddr);
7639
7640   if (use_length)
7641     {
7642       /* Append ",".  */
7643       *p++ = ',';
7644
7645       /* Append the length and retain its location and size.  It may need to be
7646          adjusted once the packet body has been created.  */
7647       plen = p;
7648       plenlen = hexnumstr (p, (ULONGEST) todo_units);
7649       p += plenlen;
7650     }
7651
7652   /* Append ":".  */
7653   *p++ = ':';
7654   *p = '\0';
7655
7656   /* Append the packet body.  */
7657   if (packet_format == 'X')
7658     {
7659       /* Binary mode.  Send target system values byte by byte, in
7660          increasing byte addresses.  Only escape certain critical
7661          characters.  */
7662       payload_length_bytes =
7663           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7664                                 &units_written, payload_capacity_bytes);
7665
7666       /* If not all TODO units fit, then we'll need another packet.  Make
7667          a second try to keep the end of the packet aligned.  Don't do
7668          this if the packet is tiny.  */
7669       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7670         {
7671           int new_todo_units;
7672
7673           new_todo_units = align_for_efficient_write (units_written, memaddr);
7674
7675           if (new_todo_units != units_written)
7676             payload_length_bytes =
7677                 remote_escape_output (myaddr, new_todo_units, unit_size,
7678                                       (gdb_byte *) p, &units_written,
7679                                       payload_capacity_bytes);
7680         }
7681
7682       p += payload_length_bytes;
7683       if (use_length && units_written < todo_units)
7684         {
7685           /* Escape chars have filled up the buffer prematurely,
7686              and we have actually sent fewer units than planned.
7687              Fix-up the length field of the packet.  Use the same
7688              number of characters as before.  */
7689           plen += hexnumnstr (plen, (ULONGEST) units_written,
7690                               plenlen);
7691           *plen = ':';  /* overwrite \0 from hexnumnstr() */
7692         }
7693     }
7694   else
7695     {
7696       /* Normal mode: Send target system values byte by byte, in
7697          increasing byte addresses.  Each byte is encoded as a two hex
7698          value.  */
7699       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7700       units_written = todo_units;
7701     }
7702
7703   putpkt_binary (rs->buf, (int) (p - rs->buf));
7704   getpkt (&rs->buf, &rs->buf_size, 0);
7705
7706   if (rs->buf[0] == 'E')
7707     return TARGET_XFER_E_IO;
7708
7709   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7710      send fewer units than we'd planned.  */
7711   *xfered_len_units = (ULONGEST) units_written;
7712   return TARGET_XFER_OK;
7713 }
7714
7715 /* Write memory data directly to the remote machine.
7716    This does not inform the data cache; the data cache uses this.
7717    MEMADDR is the address in the remote memory space.
7718    MYADDR is the address of the buffer in our space.
7719    LEN is the number of bytes.
7720
7721    Return the transferred status, error or OK (an
7722    'enum target_xfer_status' value).  Save the number of bytes
7723    transferred in *XFERED_LEN.  Only transfer a single packet.  */
7724
7725 static enum target_xfer_status
7726 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7727                     int unit_size, ULONGEST *xfered_len)
7728 {
7729   char *packet_format = 0;
7730
7731   /* Check whether the target supports binary download.  */
7732   check_binary_download (memaddr);
7733
7734   switch (packet_support (PACKET_X))
7735     {
7736     case PACKET_ENABLE:
7737       packet_format = "X";
7738       break;
7739     case PACKET_DISABLE:
7740       packet_format = "M";
7741       break;
7742     case PACKET_SUPPORT_UNKNOWN:
7743       internal_error (__FILE__, __LINE__,
7744                       _("remote_write_bytes: bad internal state"));
7745     default:
7746       internal_error (__FILE__, __LINE__, _("bad switch"));
7747     }
7748
7749   return remote_write_bytes_aux (packet_format,
7750                                  memaddr, myaddr, len, unit_size, xfered_len,
7751                                  packet_format[0], 1);
7752 }
7753
7754 /* Read memory data directly from the remote machine.
7755    This does not use the data cache; the data cache uses this.
7756    MEMADDR is the address in the remote memory space.
7757    MYADDR is the address of the buffer in our space.
7758    LEN_UNITS is the number of addressable memory units to read..
7759    UNIT_SIZE is the length in bytes of an addressable unit.
7760
7761    Return the transferred status, error or OK (an
7762    'enum target_xfer_status' value).  Save the number of bytes
7763    transferred in *XFERED_LEN_UNITS.
7764
7765    See the comment of remote_write_bytes_aux for an example of
7766    memory read/write exchange between gdb and the stub.  */
7767
7768 static enum target_xfer_status
7769 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7770                      int unit_size, ULONGEST *xfered_len_units)
7771 {
7772   struct remote_state *rs = get_remote_state ();
7773   int buf_size_bytes;           /* Max size of packet output buffer.  */
7774   char *p;
7775   int todo_units;
7776   int decoded_bytes;
7777
7778   buf_size_bytes = get_memory_read_packet_size ();
7779   /* The packet buffer will be large enough for the payload;
7780      get_memory_packet_size ensures this.  */
7781
7782   /* Number of units that will fit.  */
7783   todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7784
7785   /* Construct "m"<memaddr>","<len>".  */
7786   memaddr = remote_address_masked (memaddr);
7787   p = rs->buf;
7788   *p++ = 'm';
7789   p += hexnumstr (p, (ULONGEST) memaddr);
7790   *p++ = ',';
7791   p += hexnumstr (p, (ULONGEST) todo_units);
7792   *p = '\0';
7793   putpkt (rs->buf);
7794   getpkt (&rs->buf, &rs->buf_size, 0);
7795   if (rs->buf[0] == 'E'
7796       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7797       && rs->buf[3] == '\0')
7798     return TARGET_XFER_E_IO;
7799   /* Reply describes memory byte by byte, each byte encoded as two hex
7800      characters.  */
7801   p = rs->buf;
7802   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7803   /* Return what we have.  Let higher layers handle partial reads.  */
7804   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7805   return TARGET_XFER_OK;
7806 }
7807
7808 /* Using the set of read-only target sections of remote, read live
7809    read-only memory.
7810
7811    For interface/parameters/return description see target.h,
7812    to_xfer_partial.  */
7813
7814 static enum target_xfer_status
7815 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7816                                    ULONGEST memaddr, ULONGEST len,
7817                                    int unit_size, ULONGEST *xfered_len)
7818 {
7819   struct target_section *secp;
7820   struct target_section_table *table;
7821
7822   secp = target_section_by_addr (ops, memaddr);
7823   if (secp != NULL
7824       && (bfd_get_section_flags (secp->the_bfd_section->owner,
7825                                  secp->the_bfd_section)
7826           & SEC_READONLY))
7827     {
7828       struct target_section *p;
7829       ULONGEST memend = memaddr + len;
7830
7831       table = target_get_section_table (ops);
7832
7833       for (p = table->sections; p < table->sections_end; p++)
7834         {
7835           if (memaddr >= p->addr)
7836             {
7837               if (memend <= p->endaddr)
7838                 {
7839                   /* Entire transfer is within this section.  */
7840                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7841                                               xfered_len);
7842                 }
7843               else if (memaddr >= p->endaddr)
7844                 {
7845                   /* This section ends before the transfer starts.  */
7846                   continue;
7847                 }
7848               else
7849                 {
7850                   /* This section overlaps the transfer.  Just do half.  */
7851                   len = p->endaddr - memaddr;
7852                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7853                                               xfered_len);
7854                 }
7855             }
7856         }
7857     }
7858
7859   return TARGET_XFER_EOF;
7860 }
7861
7862 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7863    first if the requested memory is unavailable in traceframe.
7864    Otherwise, fall back to remote_read_bytes_1.  */
7865
7866 static enum target_xfer_status
7867 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7868                    gdb_byte *myaddr, ULONGEST len, int unit_size,
7869                    ULONGEST *xfered_len)
7870 {
7871   if (len == 0)
7872     return TARGET_XFER_EOF;
7873
7874   if (get_traceframe_number () != -1)
7875     {
7876       VEC(mem_range_s) *available;
7877
7878       /* If we fail to get the set of available memory, then the
7879          target does not support querying traceframe info, and so we
7880          attempt reading from the traceframe anyway (assuming the
7881          target implements the old QTro packet then).  */
7882       if (traceframe_available_memory (&available, memaddr, len))
7883         {
7884           struct cleanup *old_chain;
7885
7886           old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7887
7888           if (VEC_empty (mem_range_s, available)
7889               || VEC_index (mem_range_s, available, 0)->start != memaddr)
7890             {
7891               enum target_xfer_status res;
7892
7893               /* Don't read into the traceframe's available
7894                  memory.  */
7895               if (!VEC_empty (mem_range_s, available))
7896                 {
7897                   LONGEST oldlen = len;
7898
7899                   len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7900                   gdb_assert (len <= oldlen);
7901                 }
7902
7903               do_cleanups (old_chain);
7904
7905               /* This goes through the topmost target again.  */
7906               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7907                                                        len, unit_size, xfered_len);
7908               if (res == TARGET_XFER_OK)
7909                 return TARGET_XFER_OK;
7910               else
7911                 {
7912                   /* No use trying further, we know some memory starting
7913                      at MEMADDR isn't available.  */
7914                   *xfered_len = len;
7915                   return TARGET_XFER_UNAVAILABLE;
7916                 }
7917             }
7918
7919           /* Don't try to read more than how much is available, in
7920              case the target implements the deprecated QTro packet to
7921              cater for older GDBs (the target's knowledge of read-only
7922              sections may be outdated by now).  */
7923           len = VEC_index (mem_range_s, available, 0)->length;
7924
7925           do_cleanups (old_chain);
7926         }
7927     }
7928
7929   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7930 }
7931
7932 \f
7933
7934 /* Sends a packet with content determined by the printf format string
7935    FORMAT and the remaining arguments, then gets the reply.  Returns
7936    whether the packet was a success, a failure, or unknown.  */
7937
7938 static enum packet_result remote_send_printf (const char *format, ...)
7939   ATTRIBUTE_PRINTF (1, 2);
7940
7941 static enum packet_result
7942 remote_send_printf (const char *format, ...)
7943 {
7944   struct remote_state *rs = get_remote_state ();
7945   int max_size = get_remote_packet_size ();
7946   va_list ap;
7947
7948   va_start (ap, format);
7949
7950   rs->buf[0] = '\0';
7951   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7952     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7953
7954   if (putpkt (rs->buf) < 0)
7955     error (_("Communication problem with target."));
7956
7957   rs->buf[0] = '\0';
7958   getpkt (&rs->buf, &rs->buf_size, 0);
7959
7960   return packet_check_result (rs->buf);
7961 }
7962
7963 static void
7964 restore_remote_timeout (void *p)
7965 {
7966   int value = *(int *)p;
7967
7968   remote_timeout = value;
7969 }
7970
7971 /* Flash writing can take quite some time.  We'll set
7972    effectively infinite timeout for flash operations.
7973    In future, we'll need to decide on a better approach.  */
7974 static const int remote_flash_timeout = 1000;
7975
7976 static void
7977 remote_flash_erase (struct target_ops *ops,
7978                     ULONGEST address, LONGEST length)
7979 {
7980   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7981   int saved_remote_timeout = remote_timeout;
7982   enum packet_result ret;
7983   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7984                                           &saved_remote_timeout);
7985
7986   remote_timeout = remote_flash_timeout;
7987
7988   ret = remote_send_printf ("vFlashErase:%s,%s",
7989                             phex (address, addr_size),
7990                             phex (length, 4));
7991   switch (ret)
7992     {
7993     case PACKET_UNKNOWN:
7994       error (_("Remote target does not support flash erase"));
7995     case PACKET_ERROR:
7996       error (_("Error erasing flash with vFlashErase packet"));
7997     default:
7998       break;
7999     }
8000
8001   do_cleanups (back_to);
8002 }
8003
8004 static enum target_xfer_status
8005 remote_flash_write (struct target_ops *ops, ULONGEST address,
8006                     ULONGEST length, ULONGEST *xfered_len,
8007                     const gdb_byte *data)
8008 {
8009   int saved_remote_timeout = remote_timeout;
8010   enum target_xfer_status ret;
8011   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8012                                           &saved_remote_timeout);
8013
8014   remote_timeout = remote_flash_timeout;
8015   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8016                                 xfered_len,'X', 0);
8017   do_cleanups (back_to);
8018
8019   return ret;
8020 }
8021
8022 static void
8023 remote_flash_done (struct target_ops *ops)
8024 {
8025   int saved_remote_timeout = remote_timeout;
8026   int ret;
8027   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8028                                           &saved_remote_timeout);
8029
8030   remote_timeout = remote_flash_timeout;
8031   ret = remote_send_printf ("vFlashDone");
8032   do_cleanups (back_to);
8033
8034   switch (ret)
8035     {
8036     case PACKET_UNKNOWN:
8037       error (_("Remote target does not support vFlashDone"));
8038     case PACKET_ERROR:
8039       error (_("Error finishing flash operation"));
8040     default:
8041       break;
8042     }
8043 }
8044
8045 static void
8046 remote_files_info (struct target_ops *ignore)
8047 {
8048   puts_filtered ("Debugging a target over a serial line.\n");
8049 }
8050 \f
8051 /* Stuff for dealing with the packets which are part of this protocol.
8052    See comment at top of file for details.  */
8053
8054 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8055    error to higher layers.  Called when a serial error is detected.
8056    The exception message is STRING, followed by a colon and a blank,
8057    the system error message for errno at function entry and final dot
8058    for output compatibility with throw_perror_with_name.  */
8059
8060 static void
8061 unpush_and_perror (const char *string)
8062 {
8063   int saved_errno = errno;
8064
8065   remote_unpush_target ();
8066   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8067                safe_strerror (saved_errno));
8068 }
8069
8070 /* Read a single character from the remote end.  */
8071
8072 static int
8073 readchar (int timeout)
8074 {
8075   int ch;
8076   struct remote_state *rs = get_remote_state ();
8077
8078   ch = serial_readchar (rs->remote_desc, timeout);
8079
8080   if (ch >= 0)
8081     return ch;
8082
8083   switch ((enum serial_rc) ch)
8084     {
8085     case SERIAL_EOF:
8086       remote_unpush_target ();
8087       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8088       /* no return */
8089     case SERIAL_ERROR:
8090       unpush_and_perror (_("Remote communication error.  "
8091                            "Target disconnected."));
8092       /* no return */
8093     case SERIAL_TIMEOUT:
8094       break;
8095     }
8096   return ch;
8097 }
8098
8099 /* Wrapper for serial_write that closes the target and throws if
8100    writing fails.  */
8101
8102 static void
8103 remote_serial_write (const char *str, int len)
8104 {
8105   struct remote_state *rs = get_remote_state ();
8106
8107   if (serial_write (rs->remote_desc, str, len))
8108     {
8109       unpush_and_perror (_("Remote communication error.  "
8110                            "Target disconnected."));
8111     }
8112 }
8113
8114 /* Send the command in *BUF to the remote machine, and read the reply
8115    into *BUF.  Report an error if we get an error reply.  Resize
8116    *BUF using xrealloc if necessary to hold the result, and update
8117    *SIZEOF_BUF.  */
8118
8119 static void
8120 remote_send (char **buf,
8121              long *sizeof_buf)
8122 {
8123   putpkt (*buf);
8124   getpkt (buf, sizeof_buf, 0);
8125
8126   if ((*buf)[0] == 'E')
8127     error (_("Remote failure reply: %s"), *buf);
8128 }
8129
8130 /* Return a pointer to an xmalloc'ed string representing an escaped
8131    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
8132    etc.  The caller is responsible for releasing the returned
8133    memory.  */
8134
8135 static char *
8136 escape_buffer (const char *buf, int n)
8137 {
8138   struct cleanup *old_chain;
8139   struct ui_file *stb;
8140   char *str;
8141
8142   stb = mem_fileopen ();
8143   old_chain = make_cleanup_ui_file_delete (stb);
8144
8145   fputstrn_unfiltered (buf, n, '\\', stb);
8146   str = ui_file_xstrdup (stb, NULL);
8147   do_cleanups (old_chain);
8148   return str;
8149 }
8150
8151 /* Display a null-terminated packet on stdout, for debugging, using C
8152    string notation.  */
8153
8154 static void
8155 print_packet (const char *buf)
8156 {
8157   puts_filtered ("\"");
8158   fputstr_filtered (buf, '"', gdb_stdout);
8159   puts_filtered ("\"");
8160 }
8161
8162 int
8163 putpkt (const char *buf)
8164 {
8165   return putpkt_binary (buf, strlen (buf));
8166 }
8167
8168 /* Send a packet to the remote machine, with error checking.  The data
8169    of the packet is in BUF.  The string in BUF can be at most
8170    get_remote_packet_size () - 5 to account for the $, # and checksum,
8171    and for a possible /0 if we are debugging (remote_debug) and want
8172    to print the sent packet as a string.  */
8173
8174 static int
8175 putpkt_binary (const char *buf, int cnt)
8176 {
8177   struct remote_state *rs = get_remote_state ();
8178   int i;
8179   unsigned char csum = 0;
8180   char *buf2 = (char *) xmalloc (cnt + 6);
8181   struct cleanup *old_chain = make_cleanup (xfree, buf2);
8182
8183   int ch;
8184   int tcount = 0;
8185   char *p;
8186   char *message;
8187
8188   /* Catch cases like trying to read memory or listing threads while
8189      we're waiting for a stop reply.  The remote server wouldn't be
8190      ready to handle this request, so we'd hang and timeout.  We don't
8191      have to worry about this in synchronous mode, because in that
8192      case it's not possible to issue a command while the target is
8193      running.  This is not a problem in non-stop mode, because in that
8194      case, the stub is always ready to process serial input.  */
8195   if (!target_is_non_stop_p ()
8196       && target_is_async_p ()
8197       && rs->waiting_for_stop_reply)
8198     {
8199       error (_("Cannot execute this command while the target is running.\n"
8200                "Use the \"interrupt\" command to stop the target\n"
8201                "and then try again."));
8202     }
8203
8204   /* We're sending out a new packet.  Make sure we don't look at a
8205      stale cached response.  */
8206   rs->cached_wait_status = 0;
8207
8208   /* Copy the packet into buffer BUF2, encapsulating it
8209      and giving it a checksum.  */
8210
8211   p = buf2;
8212   *p++ = '$';
8213
8214   for (i = 0; i < cnt; i++)
8215     {
8216       csum += buf[i];
8217       *p++ = buf[i];
8218     }
8219   *p++ = '#';
8220   *p++ = tohex ((csum >> 4) & 0xf);
8221   *p++ = tohex (csum & 0xf);
8222
8223   /* Send it over and over until we get a positive ack.  */
8224
8225   while (1)
8226     {
8227       int started_error_output = 0;
8228
8229       if (remote_debug)
8230         {
8231           struct cleanup *old_chain;
8232           char *str;
8233
8234           *p = '\0';
8235           str = escape_buffer (buf2, p - buf2);
8236           old_chain = make_cleanup (xfree, str);
8237           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8238           gdb_flush (gdb_stdlog);
8239           do_cleanups (old_chain);
8240         }
8241       remote_serial_write (buf2, p - buf2);
8242
8243       /* If this is a no acks version of the remote protocol, send the
8244          packet and move on.  */
8245       if (rs->noack_mode)
8246         break;
8247
8248       /* Read until either a timeout occurs (-2) or '+' is read.
8249          Handle any notification that arrives in the mean time.  */
8250       while (1)
8251         {
8252           ch = readchar (remote_timeout);
8253
8254           if (remote_debug)
8255             {
8256               switch (ch)
8257                 {
8258                 case '+':
8259                 case '-':
8260                 case SERIAL_TIMEOUT:
8261                 case '$':
8262                 case '%':
8263                   if (started_error_output)
8264                     {
8265                       putchar_unfiltered ('\n');
8266                       started_error_output = 0;
8267                     }
8268                 }
8269             }
8270
8271           switch (ch)
8272             {
8273             case '+':
8274               if (remote_debug)
8275                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8276               do_cleanups (old_chain);
8277               return 1;
8278             case '-':
8279               if (remote_debug)
8280                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8281               /* FALLTHROUGH */
8282             case SERIAL_TIMEOUT:
8283               tcount++;
8284               if (tcount > 3)
8285                 {
8286                   do_cleanups (old_chain);
8287                   return 0;
8288                 }
8289               break;            /* Retransmit buffer.  */
8290             case '$':
8291               {
8292                 if (remote_debug)
8293                   fprintf_unfiltered (gdb_stdlog,
8294                                       "Packet instead of Ack, ignoring it\n");
8295                 /* It's probably an old response sent because an ACK
8296                    was lost.  Gobble up the packet and ack it so it
8297                    doesn't get retransmitted when we resend this
8298                    packet.  */
8299                 skip_frame ();
8300                 remote_serial_write ("+", 1);
8301                 continue;       /* Now, go look for +.  */
8302               }
8303
8304             case '%':
8305               {
8306                 int val;
8307
8308                 /* If we got a notification, handle it, and go back to looking
8309                    for an ack.  */
8310                 /* We've found the start of a notification.  Now
8311                    collect the data.  */
8312                 val = read_frame (&rs->buf, &rs->buf_size);
8313                 if (val >= 0)
8314                   {
8315                     if (remote_debug)
8316                       {
8317                         struct cleanup *old_chain;
8318                         char *str;
8319
8320                         str = escape_buffer (rs->buf, val);
8321                         old_chain = make_cleanup (xfree, str);
8322                         fprintf_unfiltered (gdb_stdlog,
8323                                             "  Notification received: %s\n",
8324                                             str);
8325                         do_cleanups (old_chain);
8326                       }
8327                     handle_notification (rs->notif_state, rs->buf);
8328                     /* We're in sync now, rewait for the ack.  */
8329                     tcount = 0;
8330                   }
8331                 else
8332                   {
8333                     if (remote_debug)
8334                       {
8335                         if (!started_error_output)
8336                           {
8337                             started_error_output = 1;
8338                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8339                           }
8340                         fputc_unfiltered (ch & 0177, gdb_stdlog);
8341                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8342                       }
8343                   }
8344                 continue;
8345               }
8346               /* fall-through */
8347             default:
8348               if (remote_debug)
8349                 {
8350                   if (!started_error_output)
8351                     {
8352                       started_error_output = 1;
8353                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8354                     }
8355                   fputc_unfiltered (ch & 0177, gdb_stdlog);
8356                 }
8357               continue;
8358             }
8359           break;                /* Here to retransmit.  */
8360         }
8361
8362 #if 0
8363       /* This is wrong.  If doing a long backtrace, the user should be
8364          able to get out next time we call QUIT, without anything as
8365          violent as interrupt_query.  If we want to provide a way out of
8366          here without getting to the next QUIT, it should be based on
8367          hitting ^C twice as in remote_wait.  */
8368       if (quit_flag)
8369         {
8370           quit_flag = 0;
8371           interrupt_query ();
8372         }
8373 #endif
8374     }
8375
8376   do_cleanups (old_chain);
8377   return 0;
8378 }
8379
8380 /* Come here after finding the start of a frame when we expected an
8381    ack.  Do our best to discard the rest of this packet.  */
8382
8383 static void
8384 skip_frame (void)
8385 {
8386   int c;
8387
8388   while (1)
8389     {
8390       c = readchar (remote_timeout);
8391       switch (c)
8392         {
8393         case SERIAL_TIMEOUT:
8394           /* Nothing we can do.  */
8395           return;
8396         case '#':
8397           /* Discard the two bytes of checksum and stop.  */
8398           c = readchar (remote_timeout);
8399           if (c >= 0)
8400             c = readchar (remote_timeout);
8401
8402           return;
8403         case '*':               /* Run length encoding.  */
8404           /* Discard the repeat count.  */
8405           c = readchar (remote_timeout);
8406           if (c < 0)
8407             return;
8408           break;
8409         default:
8410           /* A regular character.  */
8411           break;
8412         }
8413     }
8414 }
8415
8416 /* Come here after finding the start of the frame.  Collect the rest
8417    into *BUF, verifying the checksum, length, and handling run-length
8418    compression.  NUL terminate the buffer.  If there is not enough room,
8419    expand *BUF using xrealloc.
8420
8421    Returns -1 on error, number of characters in buffer (ignoring the
8422    trailing NULL) on success. (could be extended to return one of the
8423    SERIAL status indications).  */
8424
8425 static long
8426 read_frame (char **buf_p,
8427             long *sizeof_buf)
8428 {
8429   unsigned char csum;
8430   long bc;
8431   int c;
8432   char *buf = *buf_p;
8433   struct remote_state *rs = get_remote_state ();
8434
8435   csum = 0;
8436   bc = 0;
8437
8438   while (1)
8439     {
8440       c = readchar (remote_timeout);
8441       switch (c)
8442         {
8443         case SERIAL_TIMEOUT:
8444           if (remote_debug)
8445             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8446           return -1;
8447         case '$':
8448           if (remote_debug)
8449             fputs_filtered ("Saw new packet start in middle of old one\n",
8450                             gdb_stdlog);
8451           return -1;            /* Start a new packet, count retries.  */
8452         case '#':
8453           {
8454             unsigned char pktcsum;
8455             int check_0 = 0;
8456             int check_1 = 0;
8457
8458             buf[bc] = '\0';
8459
8460             check_0 = readchar (remote_timeout);
8461             if (check_0 >= 0)
8462               check_1 = readchar (remote_timeout);
8463
8464             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8465               {
8466                 if (remote_debug)
8467                   fputs_filtered ("Timeout in checksum, retrying\n",
8468                                   gdb_stdlog);
8469                 return -1;
8470               }
8471             else if (check_0 < 0 || check_1 < 0)
8472               {
8473                 if (remote_debug)
8474                   fputs_filtered ("Communication error in checksum\n",
8475                                   gdb_stdlog);
8476                 return -1;
8477               }
8478
8479             /* Don't recompute the checksum; with no ack packets we
8480                don't have any way to indicate a packet retransmission
8481                is necessary.  */
8482             if (rs->noack_mode)
8483               return bc;
8484
8485             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8486             if (csum == pktcsum)
8487               return bc;
8488
8489             if (remote_debug)
8490               {
8491                 struct cleanup *old_chain;
8492                 char *str;
8493
8494                 str = escape_buffer (buf, bc);
8495                 old_chain = make_cleanup (xfree, str);
8496                 fprintf_unfiltered (gdb_stdlog,
8497                                     "Bad checksum, sentsum=0x%x, "
8498                                     "csum=0x%x, buf=%s\n",
8499                                     pktcsum, csum, str);
8500                 do_cleanups (old_chain);
8501               }
8502             /* Number of characters in buffer ignoring trailing
8503                NULL.  */
8504             return -1;
8505           }
8506         case '*':               /* Run length encoding.  */
8507           {
8508             int repeat;
8509
8510             csum += c;
8511             c = readchar (remote_timeout);
8512             csum += c;
8513             repeat = c - ' ' + 3;       /* Compute repeat count.  */
8514
8515             /* The character before ``*'' is repeated.  */
8516
8517             if (repeat > 0 && repeat <= 255 && bc > 0)
8518               {
8519                 if (bc + repeat - 1 >= *sizeof_buf - 1)
8520                   {
8521                     /* Make some more room in the buffer.  */
8522                     *sizeof_buf += repeat;
8523                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8524                     buf = *buf_p;
8525                   }
8526
8527                 memset (&buf[bc], buf[bc - 1], repeat);
8528                 bc += repeat;
8529                 continue;
8530               }
8531
8532             buf[bc] = '\0';
8533             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8534             return -1;
8535           }
8536         default:
8537           if (bc >= *sizeof_buf - 1)
8538             {
8539               /* Make some more room in the buffer.  */
8540               *sizeof_buf *= 2;
8541               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8542               buf = *buf_p;
8543             }
8544
8545           buf[bc++] = c;
8546           csum += c;
8547           continue;
8548         }
8549     }
8550 }
8551
8552 /* Read a packet from the remote machine, with error checking, and
8553    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8554    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8555    rather than timing out; this is used (in synchronous mode) to wait
8556    for a target that is is executing user code to stop.  */
8557 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8558    don't have to change all the calls to getpkt to deal with the
8559    return value, because at the moment I don't know what the right
8560    thing to do it for those.  */
8561 void
8562 getpkt (char **buf,
8563         long *sizeof_buf,
8564         int forever)
8565 {
8566   int timed_out;
8567
8568   timed_out = getpkt_sane (buf, sizeof_buf, forever);
8569 }
8570
8571
8572 /* Read a packet from the remote machine, with error checking, and
8573    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8574    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8575    rather than timing out; this is used (in synchronous mode) to wait
8576    for a target that is is executing user code to stop.  If FOREVER ==
8577    0, this function is allowed to time out gracefully and return an
8578    indication of this to the caller.  Otherwise return the number of
8579    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
8580    enough reason to return to the caller.  *IS_NOTIF is an output
8581    boolean that indicates whether *BUF holds a notification or not
8582    (a regular packet).  */
8583
8584 static int
8585 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8586                         int expecting_notif, int *is_notif)
8587 {
8588   struct remote_state *rs = get_remote_state ();
8589   int c;
8590   int tries;
8591   int timeout;
8592   int val = -1;
8593
8594   /* We're reading a new response.  Make sure we don't look at a
8595      previously cached response.  */
8596   rs->cached_wait_status = 0;
8597
8598   strcpy (*buf, "timeout");
8599
8600   if (forever)
8601     timeout = watchdog > 0 ? watchdog : -1;
8602   else if (expecting_notif)
8603     timeout = 0; /* There should already be a char in the buffer.  If
8604                     not, bail out.  */
8605   else
8606     timeout = remote_timeout;
8607
8608 #define MAX_TRIES 3
8609
8610   /* Process any number of notifications, and then return when
8611      we get a packet.  */
8612   for (;;)
8613     {
8614       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8615          times.  */
8616       for (tries = 1; tries <= MAX_TRIES; tries++)
8617         {
8618           /* This can loop forever if the remote side sends us
8619              characters continuously, but if it pauses, we'll get
8620              SERIAL_TIMEOUT from readchar because of timeout.  Then
8621              we'll count that as a retry.
8622
8623              Note that even when forever is set, we will only wait
8624              forever prior to the start of a packet.  After that, we
8625              expect characters to arrive at a brisk pace.  They should
8626              show up within remote_timeout intervals.  */
8627           do
8628             c = readchar (timeout);
8629           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8630
8631           if (c == SERIAL_TIMEOUT)
8632             {
8633               if (expecting_notif)
8634                 return -1; /* Don't complain, it's normal to not get
8635                               anything in this case.  */
8636
8637               if (forever)      /* Watchdog went off?  Kill the target.  */
8638                 {
8639                   QUIT;
8640                   remote_unpush_target ();
8641                   throw_error (TARGET_CLOSE_ERROR,
8642                                _("Watchdog timeout has expired.  "
8643                                  "Target detached."));
8644                 }
8645               if (remote_debug)
8646                 fputs_filtered ("Timed out.\n", gdb_stdlog);
8647             }
8648           else
8649             {
8650               /* We've found the start of a packet or notification.
8651                  Now collect the data.  */
8652               val = read_frame (buf, sizeof_buf);
8653               if (val >= 0)
8654                 break;
8655             }
8656
8657           remote_serial_write ("-", 1);
8658         }
8659
8660       if (tries > MAX_TRIES)
8661         {
8662           /* We have tried hard enough, and just can't receive the
8663              packet/notification.  Give up.  */
8664           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8665
8666           /* Skip the ack char if we're in no-ack mode.  */
8667           if (!rs->noack_mode)
8668             remote_serial_write ("+", 1);
8669           return -1;
8670         }
8671
8672       /* If we got an ordinary packet, return that to our caller.  */
8673       if (c == '$')
8674         {
8675           if (remote_debug)
8676             {
8677              struct cleanup *old_chain;
8678              char *str;
8679
8680              str = escape_buffer (*buf, val);
8681              old_chain = make_cleanup (xfree, str);
8682              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8683              do_cleanups (old_chain);
8684             }
8685
8686           /* Skip the ack char if we're in no-ack mode.  */
8687           if (!rs->noack_mode)
8688             remote_serial_write ("+", 1);
8689           if (is_notif != NULL)
8690             *is_notif = 0;
8691           return val;
8692         }
8693
8694        /* If we got a notification, handle it, and go back to looking
8695          for a packet.  */
8696       else
8697         {
8698           gdb_assert (c == '%');
8699
8700           if (remote_debug)
8701             {
8702               struct cleanup *old_chain;
8703               char *str;
8704
8705               str = escape_buffer (*buf, val);
8706               old_chain = make_cleanup (xfree, str);
8707               fprintf_unfiltered (gdb_stdlog,
8708                                   "  Notification received: %s\n",
8709                                   str);
8710               do_cleanups (old_chain);
8711             }
8712           if (is_notif != NULL)
8713             *is_notif = 1;
8714
8715           handle_notification (rs->notif_state, *buf);
8716
8717           /* Notifications require no acknowledgement.  */
8718
8719           if (expecting_notif)
8720             return val;
8721         }
8722     }
8723 }
8724
8725 static int
8726 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8727 {
8728   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8729 }
8730
8731 static int
8732 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8733                       int *is_notif)
8734 {
8735   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8736                                  is_notif);
8737 }
8738
8739 /* Check whether EVENT is a fork event for the process specified
8740    by the pid passed in DATA, and if it is, kill the fork child.  */
8741
8742 static int
8743 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8744                             QUEUE_ITER (stop_reply_p) *iter,
8745                             stop_reply_p event,
8746                             void *data)
8747 {
8748   struct queue_iter_param *param = (struct queue_iter_param *) data;
8749   int parent_pid = *(int *) param->input;
8750
8751   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8752     {
8753       struct remote_state *rs = get_remote_state ();
8754       int child_pid = ptid_get_pid (event->ws.value.related_pid);
8755       int res;
8756
8757       res = remote_vkill (child_pid, rs);
8758       if (res != 0)
8759         error (_("Can't kill fork child process %d"), child_pid);
8760     }
8761
8762   return 1;
8763 }
8764
8765 /* Kill any new fork children of process PID that haven't been
8766    processed by follow_fork.  */
8767
8768 static void
8769 kill_new_fork_children (int pid, struct remote_state *rs)
8770 {
8771   struct thread_info *thread;
8772   struct notif_client *notif = &notif_client_stop;
8773   struct queue_iter_param param;
8774
8775   /* Kill the fork child threads of any threads in process PID
8776      that are stopped at a fork event.  */
8777   ALL_NON_EXITED_THREADS (thread)
8778     {
8779       struct target_waitstatus *ws = &thread->pending_follow;
8780
8781       if (is_pending_fork_parent (ws, pid, thread->ptid))
8782         {
8783           struct remote_state *rs = get_remote_state ();
8784           int child_pid = ptid_get_pid (ws->value.related_pid);
8785           int res;
8786
8787           res = remote_vkill (child_pid, rs);
8788           if (res != 0)
8789             error (_("Can't kill fork child process %d"), child_pid);
8790         }
8791     }
8792
8793   /* Check for any pending fork events (not reported or processed yet)
8794      in process PID and kill those fork child threads as well.  */
8795   remote_notif_get_pending_events (notif);
8796   param.input = &pid;
8797   param.output = NULL;
8798   QUEUE_iterate (stop_reply_p, stop_reply_queue,
8799                  kill_child_of_pending_fork, &param);
8800 }
8801
8802 \f
8803 /* Target hook to kill the current inferior.  */
8804
8805 static void
8806 remote_kill (struct target_ops *ops)
8807 {
8808   int res = -1;
8809   int pid = ptid_get_pid (inferior_ptid);
8810   struct remote_state *rs = get_remote_state ();
8811
8812   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
8813     {
8814       /* If we're stopped while forking and we haven't followed yet,
8815          kill the child task.  We need to do this before killing the
8816          parent task because if this is a vfork then the parent will
8817          be sleeping.  */
8818       kill_new_fork_children (pid, rs);
8819
8820       res = remote_vkill (pid, rs);
8821       if (res == 0)
8822         {
8823           target_mourn_inferior ();
8824           return;
8825         }
8826     }
8827
8828   /* If we are in 'target remote' mode and we are killing the only
8829      inferior, then we will tell gdbserver to exit and unpush the
8830      target.  */
8831   if (res == -1 && !remote_multi_process_p (rs)
8832       && number_of_live_inferiors () == 1)
8833     {
8834       remote_kill_k ();
8835
8836       /* We've killed the remote end, we get to mourn it.  If we are
8837          not in extended mode, mourning the inferior also unpushes
8838          remote_ops from the target stack, which closes the remote
8839          connection.  */
8840       target_mourn_inferior ();
8841
8842       return;
8843     }
8844
8845   error (_("Can't kill process"));
8846 }
8847
8848 /* Send a kill request to the target using the 'vKill' packet.  */
8849
8850 static int
8851 remote_vkill (int pid, struct remote_state *rs)
8852 {
8853   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8854     return -1;
8855
8856   /* Tell the remote target to detach.  */
8857   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8858   putpkt (rs->buf);
8859   getpkt (&rs->buf, &rs->buf_size, 0);
8860
8861   switch (packet_ok (rs->buf,
8862                      &remote_protocol_packets[PACKET_vKill]))
8863     {
8864     case PACKET_OK:
8865       return 0;
8866     case PACKET_ERROR:
8867       return 1;
8868     case PACKET_UNKNOWN:
8869       return -1;
8870     default:
8871       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8872     }
8873 }
8874
8875 /* Send a kill request to the target using the 'k' packet.  */
8876
8877 static void
8878 remote_kill_k (void)
8879 {
8880   /* Catch errors so the user can quit from gdb even when we
8881      aren't on speaking terms with the remote system.  */
8882   TRY
8883     {
8884       putpkt ("k");
8885     }
8886   CATCH (ex, RETURN_MASK_ERROR)
8887     {
8888       if (ex.error == TARGET_CLOSE_ERROR)
8889         {
8890           /* If we got an (EOF) error that caused the target
8891              to go away, then we're done, that's what we wanted.
8892              "k" is susceptible to cause a premature EOF, given
8893              that the remote server isn't actually required to
8894              reply to "k", and it can happen that it doesn't
8895              even get to reply ACK to the "k".  */
8896           return;
8897         }
8898
8899       /* Otherwise, something went wrong.  We didn't actually kill
8900          the target.  Just propagate the exception, and let the
8901          user or higher layers decide what to do.  */
8902       throw_exception (ex);
8903     }
8904   END_CATCH
8905 }
8906
8907 static void
8908 remote_mourn (struct target_ops *target)
8909 {
8910   struct remote_state *rs = get_remote_state ();
8911
8912   /* In 'target remote' mode with one inferior, we close the connection.  */
8913   if (!rs->extended && number_of_live_inferiors () <= 1)
8914     {
8915       unpush_target (target);
8916
8917       /* remote_close takes care of doing most of the clean up.  */
8918       generic_mourn_inferior ();
8919       return;
8920     }
8921
8922   /* In case we got here due to an error, but we're going to stay
8923      connected.  */
8924   rs->waiting_for_stop_reply = 0;
8925
8926   /* If the current general thread belonged to the process we just
8927      detached from or has exited, the remote side current general
8928      thread becomes undefined.  Considering a case like this:
8929
8930      - We just got here due to a detach.
8931      - The process that we're detaching from happens to immediately
8932        report a global breakpoint being hit in non-stop mode, in the
8933        same thread we had selected before.
8934      - GDB attaches to this process again.
8935      - This event happens to be the next event we handle.
8936
8937      GDB would consider that the current general thread didn't need to
8938      be set on the stub side (with Hg), since for all it knew,
8939      GENERAL_THREAD hadn't changed.
8940
8941      Notice that although in all-stop mode, the remote server always
8942      sets the current thread to the thread reporting the stop event,
8943      that doesn't happen in non-stop mode; in non-stop, the stub *must
8944      not* change the current thread when reporting a breakpoint hit,
8945      due to the decoupling of event reporting and event handling.
8946
8947      To keep things simple, we always invalidate our notion of the
8948      current thread.  */
8949   record_currthread (rs, minus_one_ptid);
8950
8951   /* Call common code to mark the inferior as not running.  */
8952   generic_mourn_inferior ();
8953
8954   if (!have_inferiors ())
8955     {
8956       if (!remote_multi_process_p (rs))
8957         {
8958           /* Check whether the target is running now - some remote stubs
8959              automatically restart after kill.  */
8960           putpkt ("?");
8961           getpkt (&rs->buf, &rs->buf_size, 0);
8962
8963           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8964             {
8965               /* Assume that the target has been restarted.  Set
8966                  inferior_ptid so that bits of core GDB realizes
8967                  there's something here, e.g., so that the user can
8968                  say "kill" again.  */
8969               inferior_ptid = magic_null_ptid;
8970             }
8971         }
8972     }
8973 }
8974
8975 static int
8976 extended_remote_supports_disable_randomization (struct target_ops *self)
8977 {
8978   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8979 }
8980
8981 static void
8982 extended_remote_disable_randomization (int val)
8983 {
8984   struct remote_state *rs = get_remote_state ();
8985   char *reply;
8986
8987   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8988              val);
8989   putpkt (rs->buf);
8990   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8991   if (*reply == '\0')
8992     error (_("Target does not support QDisableRandomization."));
8993   if (strcmp (reply, "OK") != 0)
8994     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8995 }
8996
8997 static int
8998 extended_remote_run (char *args)
8999 {
9000   struct remote_state *rs = get_remote_state ();
9001   int len;
9002   const char *remote_exec_file = get_remote_exec_file ();
9003
9004   /* If the user has disabled vRun support, or we have detected that
9005      support is not available, do not try it.  */
9006   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9007     return -1;
9008
9009   strcpy (rs->buf, "vRun;");
9010   len = strlen (rs->buf);
9011
9012   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9013     error (_("Remote file name too long for run packet"));
9014   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9015                       strlen (remote_exec_file));
9016
9017   gdb_assert (args != NULL);
9018   if (*args)
9019     {
9020       struct cleanup *back_to;
9021       int i;
9022       char **argv;
9023
9024       argv = gdb_buildargv (args);
9025       back_to = make_cleanup_freeargv (argv);
9026       for (i = 0; argv[i] != NULL; i++)
9027         {
9028           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9029             error (_("Argument list too long for run packet"));
9030           rs->buf[len++] = ';';
9031           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9032                               strlen (argv[i]));
9033         }
9034       do_cleanups (back_to);
9035     }
9036
9037   rs->buf[len++] = '\0';
9038
9039   putpkt (rs->buf);
9040   getpkt (&rs->buf, &rs->buf_size, 0);
9041
9042   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9043     {
9044     case PACKET_OK:
9045       /* We have a wait response.  All is well.  */
9046       return 0;
9047     case PACKET_UNKNOWN:
9048       return -1;
9049     case PACKET_ERROR:
9050       if (remote_exec_file[0] == '\0')
9051         error (_("Running the default executable on the remote target failed; "
9052                  "try \"set remote exec-file\"?"));
9053       else
9054         error (_("Running \"%s\" on the remote target failed"),
9055                remote_exec_file);
9056     default:
9057       gdb_assert_not_reached (_("bad switch"));
9058     }
9059 }
9060
9061 /* In the extended protocol we want to be able to do things like
9062    "run" and have them basically work as expected.  So we need
9063    a special create_inferior function.  We support changing the
9064    executable file and the command line arguments, but not the
9065    environment.  */
9066
9067 static void
9068 extended_remote_create_inferior (struct target_ops *ops,
9069                                  char *exec_file, char *args,
9070                                  char **env, int from_tty)
9071 {
9072   int run_worked;
9073   char *stop_reply;
9074   struct remote_state *rs = get_remote_state ();
9075   const char *remote_exec_file = get_remote_exec_file ();
9076
9077   /* If running asynchronously, register the target file descriptor
9078      with the event loop.  */
9079   if (target_can_async_p ())
9080     target_async (1);
9081
9082   /* Disable address space randomization if requested (and supported).  */
9083   if (extended_remote_supports_disable_randomization (ops))
9084     extended_remote_disable_randomization (disable_randomization);
9085
9086   /* Now restart the remote server.  */
9087   run_worked = extended_remote_run (args) != -1;
9088   if (!run_worked)
9089     {
9090       /* vRun was not supported.  Fail if we need it to do what the
9091          user requested.  */
9092       if (remote_exec_file[0])
9093         error (_("Remote target does not support \"set remote exec-file\""));
9094       if (args[0])
9095         error (_("Remote target does not support \"set args\" or run <ARGS>"));
9096
9097       /* Fall back to "R".  */
9098       extended_remote_restart ();
9099     }
9100
9101   if (!have_inferiors ())
9102     {
9103       /* Clean up from the last time we ran, before we mark the target
9104          running again.  This will mark breakpoints uninserted, and
9105          get_offsets may insert breakpoints.  */
9106       init_thread_list ();
9107       init_wait_for_inferior ();
9108     }
9109
9110   /* vRun's success return is a stop reply.  */
9111   stop_reply = run_worked ? rs->buf : NULL;
9112   add_current_inferior_and_thread (stop_reply);
9113
9114   /* Get updated offsets, if the stub uses qOffsets.  */
9115   get_offsets ();
9116 }
9117 \f
9118
9119 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
9120    the list of conditions (in agent expression bytecode format), if any, the
9121    target needs to evaluate.  The output is placed into the packet buffer
9122    started from BUF and ended at BUF_END.  */
9123
9124 static int
9125 remote_add_target_side_condition (struct gdbarch *gdbarch,
9126                                   struct bp_target_info *bp_tgt, char *buf,
9127                                   char *buf_end)
9128 {
9129   struct agent_expr *aexpr = NULL;
9130   int i, ix;
9131   char *pkt;
9132   char *buf_start = buf;
9133
9134   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9135     return 0;
9136
9137   buf += strlen (buf);
9138   xsnprintf (buf, buf_end - buf, "%s", ";");
9139   buf++;
9140
9141   /* Send conditions to the target and free the vector.  */
9142   for (ix = 0;
9143        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9144        ix++)
9145     {
9146       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9147       buf += strlen (buf);
9148       for (i = 0; i < aexpr->len; ++i)
9149         buf = pack_hex_byte (buf, aexpr->buf[i]);
9150       *buf = '\0';
9151     }
9152   return 0;
9153 }
9154
9155 static void
9156 remote_add_target_side_commands (struct gdbarch *gdbarch,
9157                                  struct bp_target_info *bp_tgt, char *buf)
9158 {
9159   struct agent_expr *aexpr = NULL;
9160   int i, ix;
9161
9162   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9163     return;
9164
9165   buf += strlen (buf);
9166
9167   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9168   buf += strlen (buf);
9169
9170   /* Concatenate all the agent expressions that are commands into the
9171      cmds parameter.  */
9172   for (ix = 0;
9173        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9174        ix++)
9175     {
9176       sprintf (buf, "X%x,", aexpr->len);
9177       buf += strlen (buf);
9178       for (i = 0; i < aexpr->len; ++i)
9179         buf = pack_hex_byte (buf, aexpr->buf[i]);
9180       *buf = '\0';
9181     }
9182 }
9183
9184 /* Insert a breakpoint.  On targets that have software breakpoint
9185    support, we ask the remote target to do the work; on targets
9186    which don't, we insert a traditional memory breakpoint.  */
9187
9188 static int
9189 remote_insert_breakpoint (struct target_ops *ops,
9190                           struct gdbarch *gdbarch,
9191                           struct bp_target_info *bp_tgt)
9192 {
9193   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9194      If it succeeds, then set the support to PACKET_ENABLE.  If it
9195      fails, and the user has explicitly requested the Z support then
9196      report an error, otherwise, mark it disabled and go on.  */
9197
9198   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9199     {
9200       CORE_ADDR addr = bp_tgt->reqstd_address;
9201       struct remote_state *rs;
9202       char *p, *endbuf;
9203       int bpsize;
9204       struct condition_list *cond = NULL;
9205
9206       /* Make sure the remote is pointing at the right process, if
9207          necessary.  */
9208       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9209         set_general_process ();
9210
9211       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9212
9213       rs = get_remote_state ();
9214       p = rs->buf;
9215       endbuf = rs->buf + get_remote_packet_size ();
9216
9217       *(p++) = 'Z';
9218       *(p++) = '0';
9219       *(p++) = ',';
9220       addr = (ULONGEST) remote_address_masked (addr);
9221       p += hexnumstr (p, addr);
9222       xsnprintf (p, endbuf - p, ",%d", bpsize);
9223
9224       if (remote_supports_cond_breakpoints (ops))
9225         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9226
9227       if (remote_can_run_breakpoint_commands (ops))
9228         remote_add_target_side_commands (gdbarch, bp_tgt, p);
9229
9230       putpkt (rs->buf);
9231       getpkt (&rs->buf, &rs->buf_size, 0);
9232
9233       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9234         {
9235         case PACKET_ERROR:
9236           return -1;
9237         case PACKET_OK:
9238           bp_tgt->placed_address = addr;
9239           bp_tgt->placed_size = bpsize;
9240           return 0;
9241         case PACKET_UNKNOWN:
9242           break;
9243         }
9244     }
9245
9246   /* If this breakpoint has target-side commands but this stub doesn't
9247      support Z0 packets, throw error.  */
9248   if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9249     throw_error (NOT_SUPPORTED_ERROR, _("\
9250 Target doesn't support breakpoints that have target side commands."));
9251
9252   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9253 }
9254
9255 static int
9256 remote_remove_breakpoint (struct target_ops *ops,
9257                           struct gdbarch *gdbarch,
9258                           struct bp_target_info *bp_tgt)
9259 {
9260   CORE_ADDR addr = bp_tgt->placed_address;
9261   struct remote_state *rs = get_remote_state ();
9262
9263   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9264     {
9265       char *p = rs->buf;
9266       char *endbuf = rs->buf + get_remote_packet_size ();
9267
9268       /* Make sure the remote is pointing at the right process, if
9269          necessary.  */
9270       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9271         set_general_process ();
9272
9273       *(p++) = 'z';
9274       *(p++) = '0';
9275       *(p++) = ',';
9276
9277       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9278       p += hexnumstr (p, addr);
9279       xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9280
9281       putpkt (rs->buf);
9282       getpkt (&rs->buf, &rs->buf_size, 0);
9283
9284       return (rs->buf[0] == 'E');
9285     }
9286
9287   return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9288 }
9289
9290 static enum Z_packet_type
9291 watchpoint_to_Z_packet (int type)
9292 {
9293   switch (type)
9294     {
9295     case hw_write:
9296       return Z_PACKET_WRITE_WP;
9297       break;
9298     case hw_read:
9299       return Z_PACKET_READ_WP;
9300       break;
9301     case hw_access:
9302       return Z_PACKET_ACCESS_WP;
9303       break;
9304     default:
9305       internal_error (__FILE__, __LINE__,
9306                       _("hw_bp_to_z: bad watchpoint type %d"), type);
9307     }
9308 }
9309
9310 static int
9311 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9312                           enum target_hw_bp_type type, struct expression *cond)
9313 {
9314   struct remote_state *rs = get_remote_state ();
9315   char *endbuf = rs->buf + get_remote_packet_size ();
9316   char *p;
9317   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9318
9319   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9320     return 1;
9321
9322   /* Make sure the remote is pointing at the right process, if
9323      necessary.  */
9324   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9325     set_general_process ();
9326
9327   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9328   p = strchr (rs->buf, '\0');
9329   addr = remote_address_masked (addr);
9330   p += hexnumstr (p, (ULONGEST) addr);
9331   xsnprintf (p, endbuf - p, ",%x", len);
9332
9333   putpkt (rs->buf);
9334   getpkt (&rs->buf, &rs->buf_size, 0);
9335
9336   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9337     {
9338     case PACKET_ERROR:
9339       return -1;
9340     case PACKET_UNKNOWN:
9341       return 1;
9342     case PACKET_OK:
9343       return 0;
9344     }
9345   internal_error (__FILE__, __LINE__,
9346                   _("remote_insert_watchpoint: reached end of function"));
9347 }
9348
9349 static int
9350 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9351                                      CORE_ADDR start, int length)
9352 {
9353   CORE_ADDR diff = remote_address_masked (addr - start);
9354
9355   return diff < length;
9356 }
9357
9358
9359 static int
9360 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9361                           enum target_hw_bp_type type, struct expression *cond)
9362 {
9363   struct remote_state *rs = get_remote_state ();
9364   char *endbuf = rs->buf + get_remote_packet_size ();
9365   char *p;
9366   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9367
9368   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9369     return -1;
9370
9371   /* Make sure the remote is pointing at the right process, if
9372      necessary.  */
9373   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9374     set_general_process ();
9375
9376   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9377   p = strchr (rs->buf, '\0');
9378   addr = remote_address_masked (addr);
9379   p += hexnumstr (p, (ULONGEST) addr);
9380   xsnprintf (p, endbuf - p, ",%x", len);
9381   putpkt (rs->buf);
9382   getpkt (&rs->buf, &rs->buf_size, 0);
9383
9384   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9385     {
9386     case PACKET_ERROR:
9387     case PACKET_UNKNOWN:
9388       return -1;
9389     case PACKET_OK:
9390       return 0;
9391     }
9392   internal_error (__FILE__, __LINE__,
9393                   _("remote_remove_watchpoint: reached end of function"));
9394 }
9395
9396
9397 int remote_hw_watchpoint_limit = -1;
9398 int remote_hw_watchpoint_length_limit = -1;
9399 int remote_hw_breakpoint_limit = -1;
9400
9401 static int
9402 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9403                                     CORE_ADDR addr, int len)
9404 {
9405   if (remote_hw_watchpoint_length_limit == 0)
9406     return 0;
9407   else if (remote_hw_watchpoint_length_limit < 0)
9408     return 1;
9409   else if (len <= remote_hw_watchpoint_length_limit)
9410     return 1;
9411   else
9412     return 0;
9413 }
9414
9415 static int
9416 remote_check_watch_resources (struct target_ops *self,
9417                               enum bptype type, int cnt, int ot)
9418 {
9419   if (type == bp_hardware_breakpoint)
9420     {
9421       if (remote_hw_breakpoint_limit == 0)
9422         return 0;
9423       else if (remote_hw_breakpoint_limit < 0)
9424         return 1;
9425       else if (cnt <= remote_hw_breakpoint_limit)
9426         return 1;
9427     }
9428   else
9429     {
9430       if (remote_hw_watchpoint_limit == 0)
9431         return 0;
9432       else if (remote_hw_watchpoint_limit < 0)
9433         return 1;
9434       else if (ot)
9435         return -1;
9436       else if (cnt <= remote_hw_watchpoint_limit)
9437         return 1;
9438     }
9439   return -1;
9440 }
9441
9442 /* The to_stopped_by_sw_breakpoint method of target remote.  */
9443
9444 static int
9445 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9446 {
9447   struct thread_info *thread = inferior_thread ();
9448
9449   return (thread->priv != NULL
9450           && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9451 }
9452
9453 /* The to_supports_stopped_by_sw_breakpoint method of target
9454    remote.  */
9455
9456 static int
9457 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9458 {
9459   struct remote_state *rs = get_remote_state ();
9460
9461   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9462 }
9463
9464 /* The to_stopped_by_hw_breakpoint method of target remote.  */
9465
9466 static int
9467 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9468 {
9469   struct thread_info *thread = inferior_thread ();
9470
9471   return (thread->priv != NULL
9472           && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9473 }
9474
9475 /* The to_supports_stopped_by_hw_breakpoint method of target
9476    remote.  */
9477
9478 static int
9479 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9480 {
9481   struct remote_state *rs = get_remote_state ();
9482
9483   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9484 }
9485
9486 static int
9487 remote_stopped_by_watchpoint (struct target_ops *ops)
9488 {
9489   struct thread_info *thread = inferior_thread ();
9490
9491   return (thread->priv != NULL
9492           && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9493 }
9494
9495 static int
9496 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9497 {
9498   struct thread_info *thread = inferior_thread ();
9499
9500   if (thread->priv != NULL
9501       && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9502     {
9503       *addr_p = thread->priv->watch_data_address;
9504       return 1;
9505     }
9506
9507   return 0;
9508 }
9509
9510
9511 static int
9512 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9513                              struct bp_target_info *bp_tgt)
9514 {
9515   CORE_ADDR addr = bp_tgt->reqstd_address;
9516   struct remote_state *rs;
9517   char *p, *endbuf;
9518   char *message;
9519   int bpsize;
9520
9521   /* The length field should be set to the size of a breakpoint
9522      instruction, even though we aren't inserting one ourselves.  */
9523
9524   gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9525
9526   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9527     return -1;
9528
9529   /* Make sure the remote is pointing at the right process, if
9530      necessary.  */
9531   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9532     set_general_process ();
9533
9534   rs = get_remote_state ();
9535   p = rs->buf;
9536   endbuf = rs->buf + get_remote_packet_size ();
9537
9538   *(p++) = 'Z';
9539   *(p++) = '1';
9540   *(p++) = ',';
9541
9542   addr = remote_address_masked (addr);
9543   p += hexnumstr (p, (ULONGEST) addr);
9544   xsnprintf (p, endbuf - p, ",%x", bpsize);
9545
9546   if (remote_supports_cond_breakpoints (self))
9547     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9548
9549   if (remote_can_run_breakpoint_commands (self))
9550     remote_add_target_side_commands (gdbarch, bp_tgt, p);
9551
9552   putpkt (rs->buf);
9553   getpkt (&rs->buf, &rs->buf_size, 0);
9554
9555   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9556     {
9557     case PACKET_ERROR:
9558       if (rs->buf[1] == '.')
9559         {
9560           message = strchr (rs->buf + 2, '.');
9561           if (message)
9562             error (_("Remote failure reply: %s"), message + 1);
9563         }
9564       return -1;
9565     case PACKET_UNKNOWN:
9566       return -1;
9567     case PACKET_OK:
9568       bp_tgt->placed_address = addr;
9569       bp_tgt->placed_size = bpsize;
9570       return 0;
9571     }
9572   internal_error (__FILE__, __LINE__,
9573                   _("remote_insert_hw_breakpoint: reached end of function"));
9574 }
9575
9576
9577 static int
9578 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9579                              struct bp_target_info *bp_tgt)
9580 {
9581   CORE_ADDR addr;
9582   struct remote_state *rs = get_remote_state ();
9583   char *p = rs->buf;
9584   char *endbuf = rs->buf + get_remote_packet_size ();
9585
9586   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9587     return -1;
9588
9589   /* Make sure the remote is pointing at the right process, if
9590      necessary.  */
9591   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9592     set_general_process ();
9593
9594   *(p++) = 'z';
9595   *(p++) = '1';
9596   *(p++) = ',';
9597
9598   addr = remote_address_masked (bp_tgt->placed_address);
9599   p += hexnumstr (p, (ULONGEST) addr);
9600   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);
9601
9602   putpkt (rs->buf);
9603   getpkt (&rs->buf, &rs->buf_size, 0);
9604
9605   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9606     {
9607     case PACKET_ERROR:
9608     case PACKET_UNKNOWN:
9609       return -1;
9610     case PACKET_OK:
9611       return 0;
9612     }
9613   internal_error (__FILE__, __LINE__,
9614                   _("remote_remove_hw_breakpoint: reached end of function"));
9615 }
9616
9617 /* Verify memory using the "qCRC:" request.  */
9618
9619 static int
9620 remote_verify_memory (struct target_ops *ops,
9621                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9622 {
9623   struct remote_state *rs = get_remote_state ();
9624   unsigned long host_crc, target_crc;
9625   char *tmp;
9626
9627   /* It doesn't make sense to use qCRC if the remote target is
9628      connected but not running.  */
9629   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9630     {
9631       enum packet_result result;
9632
9633       /* Make sure the remote is pointing at the right process.  */
9634       set_general_process ();
9635
9636       /* FIXME: assumes lma can fit into long.  */
9637       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9638                  (long) lma, (long) size);
9639       putpkt (rs->buf);
9640
9641       /* Be clever; compute the host_crc before waiting for target
9642          reply.  */
9643       host_crc = xcrc32 (data, size, 0xffffffff);
9644
9645       getpkt (&rs->buf, &rs->buf_size, 0);
9646
9647       result = packet_ok (rs->buf,
9648                           &remote_protocol_packets[PACKET_qCRC]);
9649       if (result == PACKET_ERROR)
9650         return -1;
9651       else if (result == PACKET_OK)
9652         {
9653           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9654             target_crc = target_crc * 16 + fromhex (*tmp);
9655
9656           return (host_crc == target_crc);
9657         }
9658     }
9659
9660   return simple_verify_memory (ops, data, lma, size);
9661 }
9662
9663 /* compare-sections command
9664
9665    With no arguments, compares each loadable section in the exec bfd
9666    with the same memory range on the target, and reports mismatches.
9667    Useful for verifying the image on the target against the exec file.  */
9668
9669 static void
9670 compare_sections_command (char *args, int from_tty)
9671 {
9672   asection *s;
9673   struct cleanup *old_chain;
9674   gdb_byte *sectdata;
9675   const char *sectname;
9676   bfd_size_type size;
9677   bfd_vma lma;
9678   int matched = 0;
9679   int mismatched = 0;
9680   int res;
9681   int read_only = 0;
9682
9683   if (!exec_bfd)
9684     error (_("command cannot be used without an exec file"));
9685
9686   /* Make sure the remote is pointing at the right process.  */
9687   set_general_process ();
9688
9689   if (args != NULL && strcmp (args, "-r") == 0)
9690     {
9691       read_only = 1;
9692       args = NULL;
9693     }
9694
9695   for (s = exec_bfd->sections; s; s = s->next)
9696     {
9697       if (!(s->flags & SEC_LOAD))
9698         continue;               /* Skip non-loadable section.  */
9699
9700       if (read_only && (s->flags & SEC_READONLY) == 0)
9701         continue;               /* Skip writeable sections */
9702
9703       size = bfd_get_section_size (s);
9704       if (size == 0)
9705         continue;               /* Skip zero-length section.  */
9706
9707       sectname = bfd_get_section_name (exec_bfd, s);
9708       if (args && strcmp (args, sectname) != 0)
9709         continue;               /* Not the section selected by user.  */
9710
9711       matched = 1;              /* Do this section.  */
9712       lma = s->lma;
9713
9714       sectdata = (gdb_byte *) xmalloc (size);
9715       old_chain = make_cleanup (xfree, sectdata);
9716       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9717
9718       res = target_verify_memory (sectdata, lma, size);
9719
9720       if (res == -1)
9721         error (_("target memory fault, section %s, range %s -- %s"), sectname,
9722                paddress (target_gdbarch (), lma),
9723                paddress (target_gdbarch (), lma + size));
9724
9725       printf_filtered ("Section %s, range %s -- %s: ", sectname,
9726                        paddress (target_gdbarch (), lma),
9727                        paddress (target_gdbarch (), lma + size));
9728       if (res)
9729         printf_filtered ("matched.\n");
9730       else
9731         {
9732           printf_filtered ("MIS-MATCHED!\n");
9733           mismatched++;
9734         }
9735
9736       do_cleanups (old_chain);
9737     }
9738   if (mismatched > 0)
9739     warning (_("One or more sections of the target image does not match\n\
9740 the loaded file\n"));
9741   if (args && !matched)
9742     printf_filtered (_("No loaded section named '%s'.\n"), args);
9743 }
9744
9745 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9746    into remote target.  The number of bytes written to the remote
9747    target is returned, or -1 for error.  */
9748
9749 static enum target_xfer_status
9750 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9751                     const char *annex, const gdb_byte *writebuf, 
9752                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9753                     struct packet_config *packet)
9754 {
9755   int i, buf_len;
9756   ULONGEST n;
9757   struct remote_state *rs = get_remote_state ();
9758   int max_size = get_memory_write_packet_size (); 
9759
9760   if (packet->support == PACKET_DISABLE)
9761     return TARGET_XFER_E_IO;
9762
9763   /* Insert header.  */
9764   i = snprintf (rs->buf, max_size, 
9765                 "qXfer:%s:write:%s:%s:",
9766                 object_name, annex ? annex : "",
9767                 phex_nz (offset, sizeof offset));
9768   max_size -= (i + 1);
9769
9770   /* Escape as much data as fits into rs->buf.  */
9771   buf_len = remote_escape_output 
9772     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9773
9774   if (putpkt_binary (rs->buf, i + buf_len) < 0
9775       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9776       || packet_ok (rs->buf, packet) != PACKET_OK)
9777     return TARGET_XFER_E_IO;
9778
9779   unpack_varlen_hex (rs->buf, &n);
9780
9781   *xfered_len = n;
9782   return TARGET_XFER_OK;
9783 }
9784
9785 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9786    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9787    number of bytes read is returned, or 0 for EOF, or -1 for error.
9788    The number of bytes read may be less than LEN without indicating an
9789    EOF.  PACKET is checked and updated to indicate whether the remote
9790    target supports this object.  */
9791
9792 static enum target_xfer_status
9793 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9794                    const char *annex,
9795                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9796                    ULONGEST *xfered_len,
9797                    struct packet_config *packet)
9798 {
9799   struct remote_state *rs = get_remote_state ();
9800   LONGEST i, n, packet_len;
9801
9802   if (packet->support == PACKET_DISABLE)
9803     return TARGET_XFER_E_IO;
9804
9805   /* Check whether we've cached an end-of-object packet that matches
9806      this request.  */
9807   if (rs->finished_object)
9808     {
9809       if (strcmp (object_name, rs->finished_object) == 0
9810           && strcmp (annex ? annex : "", rs->finished_annex) == 0
9811           && offset == rs->finished_offset)
9812         return TARGET_XFER_EOF;
9813
9814
9815       /* Otherwise, we're now reading something different.  Discard
9816          the cache.  */
9817       xfree (rs->finished_object);
9818       xfree (rs->finished_annex);
9819       rs->finished_object = NULL;
9820       rs->finished_annex = NULL;
9821     }
9822
9823   /* Request only enough to fit in a single packet.  The actual data
9824      may not, since we don't know how much of it will need to be escaped;
9825      the target is free to respond with slightly less data.  We subtract
9826      five to account for the response type and the protocol frame.  */
9827   n = min (get_remote_packet_size () - 5, len);
9828   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9829             object_name, annex ? annex : "",
9830             phex_nz (offset, sizeof offset),
9831             phex_nz (n, sizeof n));
9832   i = putpkt (rs->buf);
9833   if (i < 0)
9834     return TARGET_XFER_E_IO;
9835
9836   rs->buf[0] = '\0';
9837   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9838   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9839     return TARGET_XFER_E_IO;
9840
9841   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9842     error (_("Unknown remote qXfer reply: %s"), rs->buf);
9843
9844   /* 'm' means there is (or at least might be) more data after this
9845      batch.  That does not make sense unless there's at least one byte
9846      of data in this reply.  */
9847   if (rs->buf[0] == 'm' && packet_len == 1)
9848     error (_("Remote qXfer reply contained no data."));
9849
9850   /* Got some data.  */
9851   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9852                              packet_len - 1, readbuf, n);
9853
9854   /* 'l' is an EOF marker, possibly including a final block of data,
9855      or possibly empty.  If we have the final block of a non-empty
9856      object, record this fact to bypass a subsequent partial read.  */
9857   if (rs->buf[0] == 'l' && offset + i > 0)
9858     {
9859       rs->finished_object = xstrdup (object_name);
9860       rs->finished_annex = xstrdup (annex ? annex : "");
9861       rs->finished_offset = offset + i;
9862     }
9863
9864   if (i == 0)
9865     return TARGET_XFER_EOF;
9866   else
9867     {
9868       *xfered_len = i;
9869       return TARGET_XFER_OK;
9870     }
9871 }
9872
9873 static enum target_xfer_status
9874 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9875                      const char *annex, gdb_byte *readbuf,
9876                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9877                      ULONGEST *xfered_len)
9878 {
9879   struct remote_state *rs;
9880   int i;
9881   char *p2;
9882   char query_type;
9883   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9884
9885   set_remote_traceframe ();
9886   set_general_thread (inferior_ptid);
9887
9888   rs = get_remote_state ();
9889
9890   /* Handle memory using the standard memory routines.  */
9891   if (object == TARGET_OBJECT_MEMORY)
9892     {
9893       /* If the remote target is connected but not running, we should
9894          pass this request down to a lower stratum (e.g. the executable
9895          file).  */
9896       if (!target_has_execution)
9897         return TARGET_XFER_EOF;
9898
9899       if (writebuf != NULL)
9900         return remote_write_bytes (offset, writebuf, len, unit_size,
9901                                    xfered_len);
9902       else
9903         return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9904                                   xfered_len);
9905     }
9906
9907   /* Handle SPU memory using qxfer packets.  */
9908   if (object == TARGET_OBJECT_SPU)
9909     {
9910       if (readbuf)
9911         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9912                                   xfered_len, &remote_protocol_packets
9913                                   [PACKET_qXfer_spu_read]);
9914       else
9915         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9916                                    xfered_len, &remote_protocol_packets
9917                                    [PACKET_qXfer_spu_write]);
9918     }
9919
9920   /* Handle extra signal info using qxfer packets.  */
9921   if (object == TARGET_OBJECT_SIGNAL_INFO)
9922     {
9923       if (readbuf)
9924         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9925                                   xfered_len, &remote_protocol_packets
9926                                   [PACKET_qXfer_siginfo_read]);
9927       else
9928         return remote_write_qxfer (ops, "siginfo", annex,
9929                                    writebuf, offset, len, xfered_len,
9930                                    &remote_protocol_packets
9931                                    [PACKET_qXfer_siginfo_write]);
9932     }
9933
9934   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9935     {
9936       if (readbuf)
9937         return remote_read_qxfer (ops, "statictrace", annex,
9938                                   readbuf, offset, len, xfered_len,
9939                                   &remote_protocol_packets
9940                                   [PACKET_qXfer_statictrace_read]);
9941       else
9942         return TARGET_XFER_E_IO;
9943     }
9944
9945   /* Only handle flash writes.  */
9946   if (writebuf != NULL)
9947     {
9948       LONGEST xfered;
9949
9950       switch (object)
9951         {
9952         case TARGET_OBJECT_FLASH:
9953           return remote_flash_write (ops, offset, len, xfered_len,
9954                                      writebuf);
9955
9956         default:
9957           return TARGET_XFER_E_IO;
9958         }
9959     }
9960
9961   /* Map pre-existing objects onto letters.  DO NOT do this for new
9962      objects!!!  Instead specify new query packets.  */
9963   switch (object)
9964     {
9965     case TARGET_OBJECT_AVR:
9966       query_type = 'R';
9967       break;
9968
9969     case TARGET_OBJECT_AUXV:
9970       gdb_assert (annex == NULL);
9971       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9972                                 xfered_len,
9973                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
9974
9975     case TARGET_OBJECT_AVAILABLE_FEATURES:
9976       return remote_read_qxfer
9977         (ops, "features", annex, readbuf, offset, len, xfered_len,
9978          &remote_protocol_packets[PACKET_qXfer_features]);
9979
9980     case TARGET_OBJECT_LIBRARIES:
9981       return remote_read_qxfer
9982         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9983          &remote_protocol_packets[PACKET_qXfer_libraries]);
9984
9985     case TARGET_OBJECT_LIBRARIES_SVR4:
9986       return remote_read_qxfer
9987         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9988          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9989
9990     case TARGET_OBJECT_MEMORY_MAP:
9991       gdb_assert (annex == NULL);
9992       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9993                                  xfered_len,
9994                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9995
9996     case TARGET_OBJECT_OSDATA:
9997       /* Should only get here if we're connected.  */
9998       gdb_assert (rs->remote_desc);
9999       return remote_read_qxfer
10000         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10001         &remote_protocol_packets[PACKET_qXfer_osdata]);
10002
10003     case TARGET_OBJECT_THREADS:
10004       gdb_assert (annex == NULL);
10005       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10006                                 xfered_len,
10007                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10008
10009     case TARGET_OBJECT_TRACEFRAME_INFO:
10010       gdb_assert (annex == NULL);
10011       return remote_read_qxfer
10012         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10013          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10014
10015     case TARGET_OBJECT_FDPIC:
10016       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10017                                 xfered_len,
10018                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10019
10020     case TARGET_OBJECT_OPENVMS_UIB:
10021       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10022                                 xfered_len,
10023                                 &remote_protocol_packets[PACKET_qXfer_uib]);
10024
10025     case TARGET_OBJECT_BTRACE:
10026       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10027                                 xfered_len,
10028         &remote_protocol_packets[PACKET_qXfer_btrace]);
10029
10030     case TARGET_OBJECT_BTRACE_CONF:
10031       return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10032                                 len, xfered_len,
10033         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10034
10035     case TARGET_OBJECT_EXEC_FILE:
10036       return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10037                                 len, xfered_len,
10038         &remote_protocol_packets[PACKET_qXfer_exec_file]);
10039
10040     default:
10041       return TARGET_XFER_E_IO;
10042     }
10043
10044   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
10045      large enough let the caller deal with it.  */
10046   if (len < get_remote_packet_size ())
10047     return TARGET_XFER_E_IO;
10048   len = get_remote_packet_size ();
10049
10050   /* Except for querying the minimum buffer size, target must be open.  */
10051   if (!rs->remote_desc)
10052     error (_("remote query is only available after target open"));
10053
10054   gdb_assert (annex != NULL);
10055   gdb_assert (readbuf != NULL);
10056
10057   p2 = rs->buf;
10058   *p2++ = 'q';
10059   *p2++ = query_type;
10060
10061   /* We used one buffer char for the remote protocol q command and
10062      another for the query type.  As the remote protocol encapsulation
10063      uses 4 chars plus one extra in case we are debugging
10064      (remote_debug), we have PBUFZIZ - 7 left to pack the query
10065      string.  */
10066   i = 0;
10067   while (annex[i] && (i < (get_remote_packet_size () - 8)))
10068     {
10069       /* Bad caller may have sent forbidden characters.  */
10070       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10071       *p2++ = annex[i];
10072       i++;
10073     }
10074   *p2 = '\0';
10075   gdb_assert (annex[i] == '\0');
10076
10077   i = putpkt (rs->buf);
10078   if (i < 0)
10079     return TARGET_XFER_E_IO;
10080
10081   getpkt (&rs->buf, &rs->buf_size, 0);
10082   strcpy ((char *) readbuf, rs->buf);
10083
10084   *xfered_len = strlen ((char *) readbuf);
10085   return TARGET_XFER_OK;
10086 }
10087
10088 static int
10089 remote_search_memory (struct target_ops* ops,
10090                       CORE_ADDR start_addr, ULONGEST search_space_len,
10091                       const gdb_byte *pattern, ULONGEST pattern_len,
10092                       CORE_ADDR *found_addrp)
10093 {
10094   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10095   struct remote_state *rs = get_remote_state ();
10096   int max_size = get_memory_write_packet_size ();
10097   struct packet_config *packet =
10098     &remote_protocol_packets[PACKET_qSearch_memory];
10099   /* Number of packet bytes used to encode the pattern;
10100      this could be more than PATTERN_LEN due to escape characters.  */
10101   int escaped_pattern_len;
10102   /* Amount of pattern that was encodable in the packet.  */
10103   int used_pattern_len;
10104   int i;
10105   int found;
10106   ULONGEST found_addr;
10107
10108   /* Don't go to the target if we don't have to.
10109      This is done before checking packet->support to avoid the possibility that
10110      a success for this edge case means the facility works in general.  */
10111   if (pattern_len > search_space_len)
10112     return 0;
10113   if (pattern_len == 0)
10114     {
10115       *found_addrp = start_addr;
10116       return 1;
10117     }
10118
10119   /* If we already know the packet isn't supported, fall back to the simple
10120      way of searching memory.  */
10121
10122   if (packet_config_support (packet) == PACKET_DISABLE)
10123     {
10124       /* Target doesn't provided special support, fall back and use the
10125          standard support (copy memory and do the search here).  */
10126       return simple_search_memory (ops, start_addr, search_space_len,
10127                                    pattern, pattern_len, found_addrp);
10128     }
10129
10130   /* Make sure the remote is pointing at the right process.  */
10131   set_general_process ();
10132
10133   /* Insert header.  */
10134   i = snprintf (rs->buf, max_size, 
10135                 "qSearch:memory:%s;%s;",
10136                 phex_nz (start_addr, addr_size),
10137                 phex_nz (search_space_len, sizeof (search_space_len)));
10138   max_size -= (i + 1);
10139
10140   /* Escape as much data as fits into rs->buf.  */
10141   escaped_pattern_len =
10142     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10143                           &used_pattern_len, max_size);
10144
10145   /* Bail if the pattern is too large.  */
10146   if (used_pattern_len != pattern_len)
10147     error (_("Pattern is too large to transmit to remote target."));
10148
10149   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10150       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10151       || packet_ok (rs->buf, packet) != PACKET_OK)
10152     {
10153       /* The request may not have worked because the command is not
10154          supported.  If so, fall back to the simple way.  */
10155       if (packet->support == PACKET_DISABLE)
10156         {
10157           return simple_search_memory (ops, start_addr, search_space_len,
10158                                        pattern, pattern_len, found_addrp);
10159         }
10160       return -1;
10161     }
10162
10163   if (rs->buf[0] == '0')
10164     found = 0;
10165   else if (rs->buf[0] == '1')
10166     {
10167       found = 1;
10168       if (rs->buf[1] != ',')
10169         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10170       unpack_varlen_hex (rs->buf + 2, &found_addr);
10171       *found_addrp = found_addr;
10172     }
10173   else
10174     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10175
10176   return found;
10177 }
10178
10179 static void
10180 remote_rcmd (struct target_ops *self, const char *command,
10181              struct ui_file *outbuf)
10182 {
10183   struct remote_state *rs = get_remote_state ();
10184   char *p = rs->buf;
10185
10186   if (!rs->remote_desc)
10187     error (_("remote rcmd is only available after target open"));
10188
10189   /* Send a NULL command across as an empty command.  */
10190   if (command == NULL)
10191     command = "";
10192
10193   /* The query prefix.  */
10194   strcpy (rs->buf, "qRcmd,");
10195   p = strchr (rs->buf, '\0');
10196
10197   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10198       > get_remote_packet_size ())
10199     error (_("\"monitor\" command ``%s'' is too long."), command);
10200
10201   /* Encode the actual command.  */
10202   bin2hex ((const gdb_byte *) command, p, strlen (command));
10203
10204   if (putpkt (rs->buf) < 0)
10205     error (_("Communication problem with target."));
10206
10207   /* get/display the response */
10208   while (1)
10209     {
10210       char *buf;
10211
10212       /* XXX - see also remote_get_noisy_reply().  */
10213       QUIT;                     /* Allow user to bail out with ^C.  */
10214       rs->buf[0] = '\0';
10215       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10216         { 
10217           /* Timeout.  Continue to (try to) read responses.
10218              This is better than stopping with an error, assuming the stub
10219              is still executing the (long) monitor command.
10220              If needed, the user can interrupt gdb using C-c, obtaining
10221              an effect similar to stop on timeout.  */
10222           continue;
10223         }
10224       buf = rs->buf;
10225       if (buf[0] == '\0')
10226         error (_("Target does not support this command."));
10227       if (buf[0] == 'O' && buf[1] != 'K')
10228         {
10229           remote_console_output (buf + 1); /* 'O' message from stub.  */
10230           continue;
10231         }
10232       if (strcmp (buf, "OK") == 0)
10233         break;
10234       if (strlen (buf) == 3 && buf[0] == 'E'
10235           && isdigit (buf[1]) && isdigit (buf[2]))
10236         {
10237           error (_("Protocol error with Rcmd"));
10238         }
10239       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10240         {
10241           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10242
10243           fputc_unfiltered (c, outbuf);
10244         }
10245       break;
10246     }
10247 }
10248
10249 static VEC(mem_region_s) *
10250 remote_memory_map (struct target_ops *ops)
10251 {
10252   VEC(mem_region_s) *result = NULL;
10253   char *text = target_read_stralloc (&current_target,
10254                                      TARGET_OBJECT_MEMORY_MAP, NULL);
10255
10256   if (text)
10257     {
10258       struct cleanup *back_to = make_cleanup (xfree, text);
10259
10260       result = parse_memory_map (text);
10261       do_cleanups (back_to);
10262     }
10263
10264   return result;
10265 }
10266
10267 static void
10268 packet_command (char *args, int from_tty)
10269 {
10270   struct remote_state *rs = get_remote_state ();
10271
10272   if (!rs->remote_desc)
10273     error (_("command can only be used with remote target"));
10274
10275   if (!args)
10276     error (_("remote-packet command requires packet text as argument"));
10277
10278   puts_filtered ("sending: ");
10279   print_packet (args);
10280   puts_filtered ("\n");
10281   putpkt (args);
10282
10283   getpkt (&rs->buf, &rs->buf_size, 0);
10284   puts_filtered ("received: ");
10285   print_packet (rs->buf);
10286   puts_filtered ("\n");
10287 }
10288
10289 #if 0
10290 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10291
10292 static void display_thread_info (struct gdb_ext_thread_info *info);
10293
10294 static void threadset_test_cmd (char *cmd, int tty);
10295
10296 static void threadalive_test (char *cmd, int tty);
10297
10298 static void threadlist_test_cmd (char *cmd, int tty);
10299
10300 int get_and_display_threadinfo (threadref *ref);
10301
10302 static void threadinfo_test_cmd (char *cmd, int tty);
10303
10304 static int thread_display_step (threadref *ref, void *context);
10305
10306 static void threadlist_update_test_cmd (char *cmd, int tty);
10307
10308 static void init_remote_threadtests (void);
10309
10310 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
10311
10312 static void
10313 threadset_test_cmd (char *cmd, int tty)
10314 {
10315   int sample_thread = SAMPLE_THREAD;
10316
10317   printf_filtered (_("Remote threadset test\n"));
10318   set_general_thread (sample_thread);
10319 }
10320
10321
10322 static void
10323 threadalive_test (char *cmd, int tty)
10324 {
10325   int sample_thread = SAMPLE_THREAD;
10326   int pid = ptid_get_pid (inferior_ptid);
10327   ptid_t ptid = ptid_build (pid, sample_thread, 0);
10328
10329   if (remote_thread_alive (ptid))
10330     printf_filtered ("PASS: Thread alive test\n");
10331   else
10332     printf_filtered ("FAIL: Thread alive test\n");
10333 }
10334
10335 void output_threadid (char *title, threadref *ref);
10336
10337 void
10338 output_threadid (char *title, threadref *ref)
10339 {
10340   char hexid[20];
10341
10342   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
10343   hexid[16] = 0;
10344   printf_filtered ("%s  %s\n", title, (&hexid[0]));
10345 }
10346
10347 static void
10348 threadlist_test_cmd (char *cmd, int tty)
10349 {
10350   int startflag = 1;
10351   threadref nextthread;
10352   int done, result_count;
10353   threadref threadlist[3];
10354
10355   printf_filtered ("Remote Threadlist test\n");
10356   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10357                               &result_count, &threadlist[0]))
10358     printf_filtered ("FAIL: threadlist test\n");
10359   else
10360     {
10361       threadref *scan = threadlist;
10362       threadref *limit = scan + result_count;
10363
10364       while (scan < limit)
10365         output_threadid (" thread ", scan++);
10366     }
10367 }
10368
10369 void
10370 display_thread_info (struct gdb_ext_thread_info *info)
10371 {
10372   output_threadid ("Threadid: ", &info->threadid);
10373   printf_filtered ("Name: %s\n ", info->shortname);
10374   printf_filtered ("State: %s\n", info->display);
10375   printf_filtered ("other: %s\n\n", info->more_display);
10376 }
10377
10378 int
10379 get_and_display_threadinfo (threadref *ref)
10380 {
10381   int result;
10382   int set;
10383   struct gdb_ext_thread_info threadinfo;
10384
10385   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10386     | TAG_MOREDISPLAY | TAG_DISPLAY;
10387   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10388     display_thread_info (&threadinfo);
10389   return result;
10390 }
10391
10392 static void
10393 threadinfo_test_cmd (char *cmd, int tty)
10394 {
10395   int athread = SAMPLE_THREAD;
10396   threadref thread;
10397   int set;
10398
10399   int_to_threadref (&thread, athread);
10400   printf_filtered ("Remote Threadinfo test\n");
10401   if (!get_and_display_threadinfo (&thread))
10402     printf_filtered ("FAIL cannot get thread info\n");
10403 }
10404
10405 static int
10406 thread_display_step (threadref *ref, void *context)
10407 {
10408   /* output_threadid(" threadstep ",ref); *//* simple test */
10409   return get_and_display_threadinfo (ref);
10410 }
10411
10412 static void
10413 threadlist_update_test_cmd (char *cmd, int tty)
10414 {
10415   printf_filtered ("Remote Threadlist update test\n");
10416   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10417 }
10418
10419 static void
10420 init_remote_threadtests (void)
10421 {
10422   add_com ("tlist", class_obscure, threadlist_test_cmd,
10423            _("Fetch and print the remote list of "
10424              "thread identifiers, one pkt only"));
10425   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10426            _("Fetch and display info about one thread"));
10427   add_com ("tset", class_obscure, threadset_test_cmd,
10428            _("Test setting to a different thread"));
10429   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10430            _("Iterate through updating all remote thread info"));
10431   add_com ("talive", class_obscure, threadalive_test,
10432            _(" Remote thread alive test "));
10433 }
10434
10435 #endif /* 0 */
10436
10437 /* Convert a thread ID to a string.  Returns the string in a static
10438    buffer.  */
10439
10440 static char *
10441 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10442 {
10443   static char buf[64];
10444   struct remote_state *rs = get_remote_state ();
10445
10446   if (ptid_equal (ptid, null_ptid))
10447     return normal_pid_to_str (ptid);
10448   else if (ptid_is_pid (ptid))
10449     {
10450       /* Printing an inferior target id.  */
10451
10452       /* When multi-process extensions are off, there's no way in the
10453          remote protocol to know the remote process id, if there's any
10454          at all.  There's one exception --- when we're connected with
10455          target extended-remote, and we manually attached to a process
10456          with "attach PID".  We don't record anywhere a flag that
10457          allows us to distinguish that case from the case of
10458          connecting with extended-remote and the stub already being
10459          attached to a process, and reporting yes to qAttached, hence
10460          no smart special casing here.  */
10461       if (!remote_multi_process_p (rs))
10462         {
10463           xsnprintf (buf, sizeof buf, "Remote target");
10464           return buf;
10465         }
10466
10467       return normal_pid_to_str (ptid);
10468     }
10469   else
10470     {
10471       if (ptid_equal (magic_null_ptid, ptid))
10472         xsnprintf (buf, sizeof buf, "Thread <main>");
10473       else if (remote_multi_process_p (rs))
10474         if (ptid_get_lwp (ptid) == 0)
10475           return normal_pid_to_str (ptid);
10476         else
10477           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10478                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
10479       else
10480         xsnprintf (buf, sizeof buf, "Thread %ld",
10481                    ptid_get_lwp (ptid));
10482       return buf;
10483     }
10484 }
10485
10486 /* Get the address of the thread local variable in OBJFILE which is
10487    stored at OFFSET within the thread local storage for thread PTID.  */
10488
10489 static CORE_ADDR
10490 remote_get_thread_local_address (struct target_ops *ops,
10491                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10492 {
10493   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10494     {
10495       struct remote_state *rs = get_remote_state ();
10496       char *p = rs->buf;
10497       char *endp = rs->buf + get_remote_packet_size ();
10498       enum packet_result result;
10499
10500       strcpy (p, "qGetTLSAddr:");
10501       p += strlen (p);
10502       p = write_ptid (p, endp, ptid);
10503       *p++ = ',';
10504       p += hexnumstr (p, offset);
10505       *p++ = ',';
10506       p += hexnumstr (p, lm);
10507       *p++ = '\0';
10508
10509       putpkt (rs->buf);
10510       getpkt (&rs->buf, &rs->buf_size, 0);
10511       result = packet_ok (rs->buf,
10512                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
10513       if (result == PACKET_OK)
10514         {
10515           ULONGEST result;
10516
10517           unpack_varlen_hex (rs->buf, &result);
10518           return result;
10519         }
10520       else if (result == PACKET_UNKNOWN)
10521         throw_error (TLS_GENERIC_ERROR,
10522                      _("Remote target doesn't support qGetTLSAddr packet"));
10523       else
10524         throw_error (TLS_GENERIC_ERROR,
10525                      _("Remote target failed to process qGetTLSAddr request"));
10526     }
10527   else
10528     throw_error (TLS_GENERIC_ERROR,
10529                  _("TLS not supported or disabled on this target"));
10530   /* Not reached.  */
10531   return 0;
10532 }
10533
10534 /* Provide thread local base, i.e. Thread Information Block address.
10535    Returns 1 if ptid is found and thread_local_base is non zero.  */
10536
10537 static int
10538 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10539 {
10540   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10541     {
10542       struct remote_state *rs = get_remote_state ();
10543       char *p = rs->buf;
10544       char *endp = rs->buf + get_remote_packet_size ();
10545       enum packet_result result;
10546
10547       strcpy (p, "qGetTIBAddr:");
10548       p += strlen (p);
10549       p = write_ptid (p, endp, ptid);
10550       *p++ = '\0';
10551
10552       putpkt (rs->buf);
10553       getpkt (&rs->buf, &rs->buf_size, 0);
10554       result = packet_ok (rs->buf,
10555                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
10556       if (result == PACKET_OK)
10557         {
10558           ULONGEST result;
10559
10560           unpack_varlen_hex (rs->buf, &result);
10561           if (addr)
10562             *addr = (CORE_ADDR) result;
10563           return 1;
10564         }
10565       else if (result == PACKET_UNKNOWN)
10566         error (_("Remote target doesn't support qGetTIBAddr packet"));
10567       else
10568         error (_("Remote target failed to process qGetTIBAddr request"));
10569     }
10570   else
10571     error (_("qGetTIBAddr not supported or disabled on this target"));
10572   /* Not reached.  */
10573   return 0;
10574 }
10575
10576 /* Support for inferring a target description based on the current
10577    architecture and the size of a 'g' packet.  While the 'g' packet
10578    can have any size (since optional registers can be left off the
10579    end), some sizes are easily recognizable given knowledge of the
10580    approximate architecture.  */
10581
10582 struct remote_g_packet_guess
10583 {
10584   int bytes;
10585   const struct target_desc *tdesc;
10586 };
10587 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10588 DEF_VEC_O(remote_g_packet_guess_s);
10589
10590 struct remote_g_packet_data
10591 {
10592   VEC(remote_g_packet_guess_s) *guesses;
10593 };
10594
10595 static struct gdbarch_data *remote_g_packet_data_handle;
10596
10597 static void *
10598 remote_g_packet_data_init (struct obstack *obstack)
10599 {
10600   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10601 }
10602
10603 void
10604 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10605                                 const struct target_desc *tdesc)
10606 {
10607   struct remote_g_packet_data *data
10608     = ((struct remote_g_packet_data *)
10609        gdbarch_data (gdbarch, remote_g_packet_data_handle));
10610   struct remote_g_packet_guess new_guess, *guess;
10611   int ix;
10612
10613   gdb_assert (tdesc != NULL);
10614
10615   for (ix = 0;
10616        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10617        ix++)
10618     if (guess->bytes == bytes)
10619       internal_error (__FILE__, __LINE__,
10620                       _("Duplicate g packet description added for size %d"),
10621                       bytes);
10622
10623   new_guess.bytes = bytes;
10624   new_guess.tdesc = tdesc;
10625   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10626 }
10627
10628 /* Return 1 if remote_read_description would do anything on this target
10629    and architecture, 0 otherwise.  */
10630
10631 static int
10632 remote_read_description_p (struct target_ops *target)
10633 {
10634   struct remote_g_packet_data *data
10635     = ((struct remote_g_packet_data *)
10636        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10637
10638   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10639     return 1;
10640
10641   return 0;
10642 }
10643
10644 static const struct target_desc *
10645 remote_read_description (struct target_ops *target)
10646 {
10647   struct remote_g_packet_data *data
10648     = ((struct remote_g_packet_data *)
10649        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10650
10651   /* Do not try this during initial connection, when we do not know
10652      whether there is a running but stopped thread.  */
10653   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10654     return target->beneath->to_read_description (target->beneath);
10655
10656   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10657     {
10658       struct remote_g_packet_guess *guess;
10659       int ix;
10660       int bytes = send_g_packet ();
10661
10662       for (ix = 0;
10663            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10664            ix++)
10665         if (guess->bytes == bytes)
10666           return guess->tdesc;
10667
10668       /* We discard the g packet.  A minor optimization would be to
10669          hold on to it, and fill the register cache once we have selected
10670          an architecture, but it's too tricky to do safely.  */
10671     }
10672
10673   return target->beneath->to_read_description (target->beneath);
10674 }
10675
10676 /* Remote file transfer support.  This is host-initiated I/O, not
10677    target-initiated; for target-initiated, see remote-fileio.c.  */
10678
10679 /* If *LEFT is at least the length of STRING, copy STRING to
10680    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10681    decrease *LEFT.  Otherwise raise an error.  */
10682
10683 static void
10684 remote_buffer_add_string (char **buffer, int *left, char *string)
10685 {
10686   int len = strlen (string);
10687
10688   if (len > *left)
10689     error (_("Packet too long for target."));
10690
10691   memcpy (*buffer, string, len);
10692   *buffer += len;
10693   *left -= len;
10694
10695   /* NUL-terminate the buffer as a convenience, if there is
10696      room.  */
10697   if (*left)
10698     **buffer = '\0';
10699 }
10700
10701 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10702    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10703    decrease *LEFT.  Otherwise raise an error.  */
10704
10705 static void
10706 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10707                          int len)
10708 {
10709   if (2 * len > *left)
10710     error (_("Packet too long for target."));
10711
10712   bin2hex (bytes, *buffer, len);
10713   *buffer += 2 * len;
10714   *left -= 2 * len;
10715
10716   /* NUL-terminate the buffer as a convenience, if there is
10717      room.  */
10718   if (*left)
10719     **buffer = '\0';
10720 }
10721
10722 /* If *LEFT is large enough, convert VALUE to hex and add it to
10723    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10724    decrease *LEFT.  Otherwise raise an error.  */
10725
10726 static void
10727 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10728 {
10729   int len = hexnumlen (value);
10730
10731   if (len > *left)
10732     error (_("Packet too long for target."));
10733
10734   hexnumstr (*buffer, value);
10735   *buffer += len;
10736   *left -= len;
10737
10738   /* NUL-terminate the buffer as a convenience, if there is
10739      room.  */
10740   if (*left)
10741     **buffer = '\0';
10742 }
10743
10744 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
10745    value, *REMOTE_ERRNO to the remote error number or zero if none
10746    was included, and *ATTACHMENT to point to the start of the annex
10747    if any.  The length of the packet isn't needed here; there may
10748    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10749
10750    Return 0 if the packet could be parsed, -1 if it could not.  If
10751    -1 is returned, the other variables may not be initialized.  */
10752
10753 static int
10754 remote_hostio_parse_result (char *buffer, int *retcode,
10755                             int *remote_errno, char **attachment)
10756 {
10757   char *p, *p2;
10758
10759   *remote_errno = 0;
10760   *attachment = NULL;
10761
10762   if (buffer[0] != 'F')
10763     return -1;
10764
10765   errno = 0;
10766   *retcode = strtol (&buffer[1], &p, 16);
10767   if (errno != 0 || p == &buffer[1])
10768     return -1;
10769
10770   /* Check for ",errno".  */
10771   if (*p == ',')
10772     {
10773       errno = 0;
10774       *remote_errno = strtol (p + 1, &p2, 16);
10775       if (errno != 0 || p + 1 == p2)
10776         return -1;
10777       p = p2;
10778     }
10779
10780   /* Check for ";attachment".  If there is no attachment, the
10781      packet should end here.  */
10782   if (*p == ';')
10783     {
10784       *attachment = p + 1;
10785       return 0;
10786     }
10787   else if (*p == '\0')
10788     return 0;
10789   else
10790     return -1;
10791 }
10792
10793 /* Send a prepared I/O packet to the target and read its response.
10794    The prepared packet is in the global RS->BUF before this function
10795    is called, and the answer is there when we return.
10796
10797    COMMAND_BYTES is the length of the request to send, which may include
10798    binary data.  WHICH_PACKET is the packet configuration to check
10799    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
10800    is set to the error number and -1 is returned.  Otherwise the value
10801    returned by the function is returned.
10802
10803    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10804    attachment is expected; an error will be reported if there's a
10805    mismatch.  If one is found, *ATTACHMENT will be set to point into
10806    the packet buffer and *ATTACHMENT_LEN will be set to the
10807    attachment's length.  */
10808
10809 static int
10810 remote_hostio_send_command (int command_bytes, int which_packet,
10811                             int *remote_errno, char **attachment,
10812                             int *attachment_len)
10813 {
10814   struct remote_state *rs = get_remote_state ();
10815   int ret, bytes_read;
10816   char *attachment_tmp;
10817
10818   if (!rs->remote_desc
10819       || packet_support (which_packet) == PACKET_DISABLE)
10820     {
10821       *remote_errno = FILEIO_ENOSYS;
10822       return -1;
10823     }
10824
10825   putpkt_binary (rs->buf, command_bytes);
10826   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10827
10828   /* If it timed out, something is wrong.  Don't try to parse the
10829      buffer.  */
10830   if (bytes_read < 0)
10831     {
10832       *remote_errno = FILEIO_EINVAL;
10833       return -1;
10834     }
10835
10836   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10837     {
10838     case PACKET_ERROR:
10839       *remote_errno = FILEIO_EINVAL;
10840       return -1;
10841     case PACKET_UNKNOWN:
10842       *remote_errno = FILEIO_ENOSYS;
10843       return -1;
10844     case PACKET_OK:
10845       break;
10846     }
10847
10848   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10849                                   &attachment_tmp))
10850     {
10851       *remote_errno = FILEIO_EINVAL;
10852       return -1;
10853     }
10854
10855   /* Make sure we saw an attachment if and only if we expected one.  */
10856   if ((attachment_tmp == NULL && attachment != NULL)
10857       || (attachment_tmp != NULL && attachment == NULL))
10858     {
10859       *remote_errno = FILEIO_EINVAL;
10860       return -1;
10861     }
10862
10863   /* If an attachment was found, it must point into the packet buffer;
10864      work out how many bytes there were.  */
10865   if (attachment_tmp != NULL)
10866     {
10867       *attachment = attachment_tmp;
10868       *attachment_len = bytes_read - (*attachment - rs->buf);
10869     }
10870
10871   return ret;
10872 }
10873
10874 /* Invalidate the readahead cache.  */
10875
10876 static void
10877 readahead_cache_invalidate (void)
10878 {
10879   struct remote_state *rs = get_remote_state ();
10880
10881   rs->readahead_cache.fd = -1;
10882 }
10883
10884 /* Invalidate the readahead cache if it is holding data for FD.  */
10885
10886 static void
10887 readahead_cache_invalidate_fd (int fd)
10888 {
10889   struct remote_state *rs = get_remote_state ();
10890
10891   if (rs->readahead_cache.fd == fd)
10892     rs->readahead_cache.fd = -1;
10893 }
10894
10895 /* Set the filesystem remote_hostio functions that take FILENAME
10896    arguments will use.  Return 0 on success, or -1 if an error
10897    occurs (and set *REMOTE_ERRNO).  */
10898
10899 static int
10900 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10901 {
10902   struct remote_state *rs = get_remote_state ();
10903   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10904   char *p = rs->buf;
10905   int left = get_remote_packet_size () - 1;
10906   char arg[9];
10907   int ret;
10908
10909   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10910     return 0;
10911
10912   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10913     return 0;
10914
10915   remote_buffer_add_string (&p, &left, "vFile:setfs:");
10916
10917   xsnprintf (arg, sizeof (arg), "%x", required_pid);
10918   remote_buffer_add_string (&p, &left, arg);
10919
10920   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10921                                     remote_errno, NULL, NULL);
10922
10923   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10924     return 0;
10925
10926   if (ret == 0)
10927     rs->fs_pid = required_pid;
10928
10929   return ret;
10930 }
10931
10932 /* Implementation of to_fileio_open.  */
10933
10934 static int
10935 remote_hostio_open (struct target_ops *self,
10936                     struct inferior *inf, const char *filename,
10937                     int flags, int mode, int warn_if_slow,
10938                     int *remote_errno)
10939 {
10940   struct remote_state *rs = get_remote_state ();
10941   char *p = rs->buf;
10942   int left = get_remote_packet_size () - 1;
10943
10944   if (warn_if_slow)
10945     {
10946       static int warning_issued = 0;
10947
10948       printf_unfiltered (_("Reading %s from remote target...\n"),
10949                          filename);
10950
10951       if (!warning_issued)
10952         {
10953           warning (_("File transfers from remote targets can be slow."
10954                      " Use \"set sysroot\" to access files locally"
10955                      " instead."));
10956           warning_issued = 1;
10957         }
10958     }
10959
10960   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10961     return -1;
10962
10963   remote_buffer_add_string (&p, &left, "vFile:open:");
10964
10965   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10966                            strlen (filename));
10967   remote_buffer_add_string (&p, &left, ",");
10968
10969   remote_buffer_add_int (&p, &left, flags);
10970   remote_buffer_add_string (&p, &left, ",");
10971
10972   remote_buffer_add_int (&p, &left, mode);
10973
10974   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10975                                      remote_errno, NULL, NULL);
10976 }
10977
10978 /* Implementation of to_fileio_pwrite.  */
10979
10980 static int
10981 remote_hostio_pwrite (struct target_ops *self,
10982                       int fd, const gdb_byte *write_buf, int len,
10983                       ULONGEST offset, int *remote_errno)
10984 {
10985   struct remote_state *rs = get_remote_state ();
10986   char *p = rs->buf;
10987   int left = get_remote_packet_size ();
10988   int out_len;
10989
10990   readahead_cache_invalidate_fd (fd);
10991
10992   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10993
10994   remote_buffer_add_int (&p, &left, fd);
10995   remote_buffer_add_string (&p, &left, ",");
10996
10997   remote_buffer_add_int (&p, &left, offset);
10998   remote_buffer_add_string (&p, &left, ",");
10999
11000   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11001                              get_remote_packet_size () - (p - rs->buf));
11002
11003   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11004                                      remote_errno, NULL, NULL);
11005 }
11006
11007 /* Helper for the implementation of to_fileio_pread.  Read the file
11008    from the remote side with vFile:pread.  */
11009
11010 static int
11011 remote_hostio_pread_vFile (struct target_ops *self,
11012                            int fd, gdb_byte *read_buf, int len,
11013                            ULONGEST offset, int *remote_errno)
11014 {
11015   struct remote_state *rs = get_remote_state ();
11016   char *p = rs->buf;
11017   char *attachment;
11018   int left = get_remote_packet_size ();
11019   int ret, attachment_len;
11020   int read_len;
11021
11022   remote_buffer_add_string (&p, &left, "vFile:pread:");
11023
11024   remote_buffer_add_int (&p, &left, fd);
11025   remote_buffer_add_string (&p, &left, ",");
11026
11027   remote_buffer_add_int (&p, &left, len);
11028   remote_buffer_add_string (&p, &left, ",");
11029
11030   remote_buffer_add_int (&p, &left, offset);
11031
11032   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11033                                     remote_errno, &attachment,
11034                                     &attachment_len);
11035
11036   if (ret < 0)
11037     return ret;
11038
11039   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11040                                     read_buf, len);
11041   if (read_len != ret)
11042     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11043
11044   return ret;
11045 }
11046
11047 /* Serve pread from the readahead cache.  Returns number of bytes
11048    read, or 0 if the request can't be served from the cache.  */
11049
11050 static int
11051 remote_hostio_pread_from_cache (struct remote_state *rs,
11052                                 int fd, gdb_byte *read_buf, size_t len,
11053                                 ULONGEST offset)
11054 {
11055   struct readahead_cache *cache = &rs->readahead_cache;
11056
11057   if (cache->fd == fd
11058       && cache->offset <= offset
11059       && offset < cache->offset + cache->bufsize)
11060     {
11061       ULONGEST max = cache->offset + cache->bufsize;
11062
11063       if (offset + len > max)
11064         len = max - offset;
11065
11066       memcpy (read_buf, cache->buf + offset - cache->offset, len);
11067       return len;
11068     }
11069
11070   return 0;
11071 }
11072
11073 /* Implementation of to_fileio_pread.  */
11074
11075 static int
11076 remote_hostio_pread (struct target_ops *self,
11077                      int fd, gdb_byte *read_buf, int len,
11078                      ULONGEST offset, int *remote_errno)
11079 {
11080   int ret;
11081   struct remote_state *rs = get_remote_state ();
11082   struct readahead_cache *cache = &rs->readahead_cache;
11083
11084   ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11085   if (ret > 0)
11086     {
11087       cache->hit_count++;
11088
11089       if (remote_debug)
11090         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11091                             pulongest (cache->hit_count));
11092       return ret;
11093     }
11094
11095   cache->miss_count++;
11096   if (remote_debug)
11097     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11098                         pulongest (cache->miss_count));
11099
11100   cache->fd = fd;
11101   cache->offset = offset;
11102   cache->bufsize = get_remote_packet_size ();
11103   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11104
11105   ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11106                                    cache->offset, remote_errno);
11107   if (ret <= 0)
11108     {
11109       readahead_cache_invalidate_fd (fd);
11110       return ret;
11111     }
11112
11113   cache->bufsize = ret;
11114   return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11115 }
11116
11117 /* Implementation of to_fileio_close.  */
11118
11119 static int
11120 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11121 {
11122   struct remote_state *rs = get_remote_state ();
11123   char *p = rs->buf;
11124   int left = get_remote_packet_size () - 1;
11125
11126   readahead_cache_invalidate_fd (fd);
11127
11128   remote_buffer_add_string (&p, &left, "vFile:close:");
11129
11130   remote_buffer_add_int (&p, &left, fd);
11131
11132   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11133                                      remote_errno, NULL, NULL);
11134 }
11135
11136 /* Implementation of to_fileio_unlink.  */
11137
11138 static int
11139 remote_hostio_unlink (struct target_ops *self,
11140                       struct inferior *inf, const char *filename,
11141                       int *remote_errno)
11142 {
11143   struct remote_state *rs = get_remote_state ();
11144   char *p = rs->buf;
11145   int left = get_remote_packet_size () - 1;
11146
11147   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11148     return -1;
11149
11150   remote_buffer_add_string (&p, &left, "vFile:unlink:");
11151
11152   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11153                            strlen (filename));
11154
11155   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11156                                      remote_errno, NULL, NULL);
11157 }
11158
11159 /* Implementation of to_fileio_readlink.  */
11160
11161 static char *
11162 remote_hostio_readlink (struct target_ops *self,
11163                         struct inferior *inf, const char *filename,
11164                         int *remote_errno)
11165 {
11166   struct remote_state *rs = get_remote_state ();
11167   char *p = rs->buf;
11168   char *attachment;
11169   int left = get_remote_packet_size ();
11170   int len, attachment_len;
11171   int read_len;
11172   char *ret;
11173
11174   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11175     return NULL;
11176
11177   remote_buffer_add_string (&p, &left, "vFile:readlink:");
11178
11179   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11180                            strlen (filename));
11181
11182   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11183                                     remote_errno, &attachment,
11184                                     &attachment_len);
11185
11186   if (len < 0)
11187     return NULL;
11188
11189   ret = (char *) xmalloc (len + 1);
11190
11191   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11192                                     (gdb_byte *) ret, len);
11193   if (read_len != len)
11194     error (_("Readlink returned %d, but %d bytes."), len, read_len);
11195
11196   ret[len] = '\0';
11197   return ret;
11198 }
11199
11200 /* Implementation of to_fileio_fstat.  */
11201
11202 static int
11203 remote_hostio_fstat (struct target_ops *self,
11204                      int fd, struct stat *st,
11205                      int *remote_errno)
11206 {
11207   struct remote_state *rs = get_remote_state ();
11208   char *p = rs->buf;
11209   int left = get_remote_packet_size ();
11210   int attachment_len, ret;
11211   char *attachment;
11212   struct fio_stat fst;
11213   int read_len;
11214
11215   remote_buffer_add_string (&p, &left, "vFile:fstat:");
11216
11217   remote_buffer_add_int (&p, &left, fd);
11218
11219   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11220                                     remote_errno, &attachment,
11221                                     &attachment_len);
11222   if (ret < 0)
11223     {
11224       if (*remote_errno != FILEIO_ENOSYS)
11225         return ret;
11226
11227       /* Strictly we should return -1, ENOSYS here, but when
11228          "set sysroot remote:" was implemented in August 2008
11229          BFD's need for a stat function was sidestepped with
11230          this hack.  This was not remedied until March 2015
11231          so we retain the previous behavior to avoid breaking
11232          compatibility.
11233
11234          Note that the memset is a March 2015 addition; older
11235          GDBs set st_size *and nothing else* so the structure
11236          would have garbage in all other fields.  This might
11237          break something but retaining the previous behavior
11238          here would be just too wrong.  */
11239
11240       memset (st, 0, sizeof (struct stat));
11241       st->st_size = INT_MAX;
11242       return 0;
11243     }
11244
11245   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11246                                     (gdb_byte *) &fst, sizeof (fst));
11247
11248   if (read_len != ret)
11249     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11250
11251   if (read_len != sizeof (fst))
11252     error (_("vFile:fstat returned %d bytes, but expecting %d."),
11253            read_len, (int) sizeof (fst));
11254
11255   remote_fileio_to_host_stat (&fst, st);
11256
11257   return 0;
11258 }
11259
11260 /* Implementation of to_filesystem_is_local.  */
11261
11262 static int
11263 remote_filesystem_is_local (struct target_ops *self)
11264 {
11265   /* Valgrind GDB presents itself as a remote target but works
11266      on the local filesystem: it does not implement remote get
11267      and users are not expected to set a sysroot.  To handle
11268      this case we treat the remote filesystem as local if the
11269      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11270      does not support vFile:open.  */
11271   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11272     {
11273       enum packet_support ps = packet_support (PACKET_vFile_open);
11274
11275       if (ps == PACKET_SUPPORT_UNKNOWN)
11276         {
11277           int fd, remote_errno;
11278
11279           /* Try opening a file to probe support.  The supplied
11280              filename is irrelevant, we only care about whether
11281              the stub recognizes the packet or not.  */
11282           fd = remote_hostio_open (self, NULL, "just probing",
11283                                    FILEIO_O_RDONLY, 0700, 0,
11284                                    &remote_errno);
11285
11286           if (fd >= 0)
11287             remote_hostio_close (self, fd, &remote_errno);
11288
11289           ps = packet_support (PACKET_vFile_open);
11290         }
11291
11292       if (ps == PACKET_DISABLE)
11293         {
11294           static int warning_issued = 0;
11295
11296           if (!warning_issued)
11297             {
11298               warning (_("remote target does not support file"
11299                          " transfer, attempting to access files"
11300                          " from local filesystem."));
11301               warning_issued = 1;
11302             }
11303
11304           return 1;
11305         }
11306     }
11307
11308   return 0;
11309 }
11310
11311 static int
11312 remote_fileio_errno_to_host (int errnum)
11313 {
11314   switch (errnum)
11315     {
11316       case FILEIO_EPERM:
11317         return EPERM;
11318       case FILEIO_ENOENT:
11319         return ENOENT;
11320       case FILEIO_EINTR:
11321         return EINTR;
11322       case FILEIO_EIO:
11323         return EIO;
11324       case FILEIO_EBADF:
11325         return EBADF;
11326       case FILEIO_EACCES:
11327         return EACCES;
11328       case FILEIO_EFAULT:
11329         return EFAULT;
11330       case FILEIO_EBUSY:
11331         return EBUSY;
11332       case FILEIO_EEXIST:
11333         return EEXIST;
11334       case FILEIO_ENODEV:
11335         return ENODEV;
11336       case FILEIO_ENOTDIR:
11337         return ENOTDIR;
11338       case FILEIO_EISDIR:
11339         return EISDIR;
11340       case FILEIO_EINVAL:
11341         return EINVAL;
11342       case FILEIO_ENFILE:
11343         return ENFILE;
11344       case FILEIO_EMFILE:
11345         return EMFILE;
11346       case FILEIO_EFBIG:
11347         return EFBIG;
11348       case FILEIO_ENOSPC:
11349         return ENOSPC;
11350       case FILEIO_ESPIPE:
11351         return ESPIPE;
11352       case FILEIO_EROFS:
11353         return EROFS;
11354       case FILEIO_ENOSYS:
11355         return ENOSYS;
11356       case FILEIO_ENAMETOOLONG:
11357         return ENAMETOOLONG;
11358     }
11359   return -1;
11360 }
11361
11362 static char *
11363 remote_hostio_error (int errnum)
11364 {
11365   int host_error = remote_fileio_errno_to_host (errnum);
11366
11367   if (host_error == -1)
11368     error (_("Unknown remote I/O error %d"), errnum);
11369   else
11370     error (_("Remote I/O error: %s"), safe_strerror (host_error));
11371 }
11372
11373 static void
11374 remote_hostio_close_cleanup (void *opaque)
11375 {
11376   int fd = *(int *) opaque;
11377   int remote_errno;
11378
11379   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11380 }
11381
11382 void
11383 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11384 {
11385   struct cleanup *back_to, *close_cleanup;
11386   int retcode, fd, remote_errno, bytes, io_size;
11387   FILE *file;
11388   gdb_byte *buffer;
11389   int bytes_in_buffer;
11390   int saw_eof;
11391   ULONGEST offset;
11392   struct remote_state *rs = get_remote_state ();
11393
11394   if (!rs->remote_desc)
11395     error (_("command can only be used with remote target"));
11396
11397   file = gdb_fopen_cloexec (local_file, "rb");
11398   if (file == NULL)
11399     perror_with_name (local_file);
11400   back_to = make_cleanup_fclose (file);
11401
11402   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11403                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11404                                          | FILEIO_O_TRUNC),
11405                            0700, 0, &remote_errno);
11406   if (fd == -1)
11407     remote_hostio_error (remote_errno);
11408
11409   /* Send up to this many bytes at once.  They won't all fit in the
11410      remote packet limit, so we'll transfer slightly fewer.  */
11411   io_size = get_remote_packet_size ();
11412   buffer = (gdb_byte *) xmalloc (io_size);
11413   make_cleanup (xfree, buffer);
11414
11415   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11416
11417   bytes_in_buffer = 0;
11418   saw_eof = 0;
11419   offset = 0;
11420   while (bytes_in_buffer || !saw_eof)
11421     {
11422       if (!saw_eof)
11423         {
11424           bytes = fread (buffer + bytes_in_buffer, 1,
11425                          io_size - bytes_in_buffer,
11426                          file);
11427           if (bytes == 0)
11428             {
11429               if (ferror (file))
11430                 error (_("Error reading %s."), local_file);
11431               else
11432                 {
11433                   /* EOF.  Unless there is something still in the
11434                      buffer from the last iteration, we are done.  */
11435                   saw_eof = 1;
11436                   if (bytes_in_buffer == 0)
11437                     break;
11438                 }
11439             }
11440         }
11441       else
11442         bytes = 0;
11443
11444       bytes += bytes_in_buffer;
11445       bytes_in_buffer = 0;
11446
11447       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11448                                       fd, buffer, bytes,
11449                                       offset, &remote_errno);
11450
11451       if (retcode < 0)
11452         remote_hostio_error (remote_errno);
11453       else if (retcode == 0)
11454         error (_("Remote write of %d bytes returned 0!"), bytes);
11455       else if (retcode < bytes)
11456         {
11457           /* Short write.  Save the rest of the read data for the next
11458              write.  */
11459           bytes_in_buffer = bytes - retcode;
11460           memmove (buffer, buffer + retcode, bytes_in_buffer);
11461         }
11462
11463       offset += retcode;
11464     }
11465
11466   discard_cleanups (close_cleanup);
11467   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11468     remote_hostio_error (remote_errno);
11469
11470   if (from_tty)
11471     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11472   do_cleanups (back_to);
11473 }
11474
11475 void
11476 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11477 {
11478   struct cleanup *back_to, *close_cleanup;
11479   int fd, remote_errno, bytes, io_size;
11480   FILE *file;
11481   gdb_byte *buffer;
11482   ULONGEST offset;
11483   struct remote_state *rs = get_remote_state ();
11484
11485   if (!rs->remote_desc)
11486     error (_("command can only be used with remote target"));
11487
11488   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11489                            remote_file, FILEIO_O_RDONLY, 0, 0,
11490                            &remote_errno);
11491   if (fd == -1)
11492     remote_hostio_error (remote_errno);
11493
11494   file = gdb_fopen_cloexec (local_file, "wb");
11495   if (file == NULL)
11496     perror_with_name (local_file);
11497   back_to = make_cleanup_fclose (file);
11498
11499   /* Send up to this many bytes at once.  They won't all fit in the
11500      remote packet limit, so we'll transfer slightly fewer.  */
11501   io_size = get_remote_packet_size ();
11502   buffer = (gdb_byte *) xmalloc (io_size);
11503   make_cleanup (xfree, buffer);
11504
11505   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11506
11507   offset = 0;
11508   while (1)
11509     {
11510       bytes = remote_hostio_pread (find_target_at (process_stratum),
11511                                    fd, buffer, io_size, offset, &remote_errno);
11512       if (bytes == 0)
11513         /* Success, but no bytes, means end-of-file.  */
11514         break;
11515       if (bytes == -1)
11516         remote_hostio_error (remote_errno);
11517
11518       offset += bytes;
11519
11520       bytes = fwrite (buffer, 1, bytes, file);
11521       if (bytes == 0)
11522         perror_with_name (local_file);
11523     }
11524
11525   discard_cleanups (close_cleanup);
11526   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11527     remote_hostio_error (remote_errno);
11528
11529   if (from_tty)
11530     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11531   do_cleanups (back_to);
11532 }
11533
11534 void
11535 remote_file_delete (const char *remote_file, int from_tty)
11536 {
11537   int retcode, remote_errno;
11538   struct remote_state *rs = get_remote_state ();
11539
11540   if (!rs->remote_desc)
11541     error (_("command can only be used with remote target"));
11542
11543   retcode = remote_hostio_unlink (find_target_at (process_stratum),
11544                                   NULL, remote_file, &remote_errno);
11545   if (retcode == -1)
11546     remote_hostio_error (remote_errno);
11547
11548   if (from_tty)
11549     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11550 }
11551
11552 static void
11553 remote_put_command (char *args, int from_tty)
11554 {
11555   struct cleanup *back_to;
11556   char **argv;
11557
11558   if (args == NULL)
11559     error_no_arg (_("file to put"));
11560
11561   argv = gdb_buildargv (args);
11562   back_to = make_cleanup_freeargv (argv);
11563   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11564     error (_("Invalid parameters to remote put"));
11565
11566   remote_file_put (argv[0], argv[1], from_tty);
11567
11568   do_cleanups (back_to);
11569 }
11570
11571 static void
11572 remote_get_command (char *args, int from_tty)
11573 {
11574   struct cleanup *back_to;
11575   char **argv;
11576
11577   if (args == NULL)
11578     error_no_arg (_("file to get"));
11579
11580   argv = gdb_buildargv (args);
11581   back_to = make_cleanup_freeargv (argv);
11582   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11583     error (_("Invalid parameters to remote get"));
11584
11585   remote_file_get (argv[0], argv[1], from_tty);
11586
11587   do_cleanups (back_to);
11588 }
11589
11590 static void
11591 remote_delete_command (char *args, int from_tty)
11592 {
11593   struct cleanup *back_to;
11594   char **argv;
11595
11596   if (args == NULL)
11597     error_no_arg (_("file to delete"));
11598
11599   argv = gdb_buildargv (args);
11600   back_to = make_cleanup_freeargv (argv);
11601   if (argv[0] == NULL || argv[1] != NULL)
11602     error (_("Invalid parameters to remote delete"));
11603
11604   remote_file_delete (argv[0], from_tty);
11605
11606   do_cleanups (back_to);
11607 }
11608
11609 static void
11610 remote_command (char *args, int from_tty)
11611 {
11612   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11613 }
11614
11615 static int
11616 remote_can_execute_reverse (struct target_ops *self)
11617 {
11618   if (packet_support (PACKET_bs) == PACKET_ENABLE
11619       || packet_support (PACKET_bc) == PACKET_ENABLE)
11620     return 1;
11621   else
11622     return 0;
11623 }
11624
11625 static int
11626 remote_supports_non_stop (struct target_ops *self)
11627 {
11628   return 1;
11629 }
11630
11631 static int
11632 remote_supports_disable_randomization (struct target_ops *self)
11633 {
11634   /* Only supported in extended mode.  */
11635   return 0;
11636 }
11637
11638 static int
11639 remote_supports_multi_process (struct target_ops *self)
11640 {
11641   struct remote_state *rs = get_remote_state ();
11642
11643   return remote_multi_process_p (rs);
11644 }
11645
11646 static int
11647 remote_supports_cond_tracepoints (void)
11648 {
11649   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11650 }
11651
11652 static int
11653 remote_supports_cond_breakpoints (struct target_ops *self)
11654 {
11655   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11656 }
11657
11658 static int
11659 remote_supports_fast_tracepoints (void)
11660 {
11661   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11662 }
11663
11664 static int
11665 remote_supports_static_tracepoints (void)
11666 {
11667   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11668 }
11669
11670 static int
11671 remote_supports_install_in_trace (void)
11672 {
11673   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11674 }
11675
11676 static int
11677 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11678 {
11679   return (packet_support (PACKET_EnableDisableTracepoints_feature)
11680           == PACKET_ENABLE);
11681 }
11682
11683 static int
11684 remote_supports_string_tracing (struct target_ops *self)
11685 {
11686   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11687 }
11688
11689 static int
11690 remote_can_run_breakpoint_commands (struct target_ops *self)
11691 {
11692   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11693 }
11694
11695 static void
11696 remote_trace_init (struct target_ops *self)
11697 {
11698   putpkt ("QTinit");
11699   remote_get_noisy_reply (&target_buf, &target_buf_size);
11700   if (strcmp (target_buf, "OK") != 0)
11701     error (_("Target does not support this command."));
11702 }
11703
11704 static void free_actions_list (char **actions_list);
11705 static void free_actions_list_cleanup_wrapper (void *);
11706 static void
11707 free_actions_list_cleanup_wrapper (void *al)
11708 {
11709   free_actions_list ((char **) al);
11710 }
11711
11712 static void
11713 free_actions_list (char **actions_list)
11714 {
11715   int ndx;
11716
11717   if (actions_list == 0)
11718     return;
11719
11720   for (ndx = 0; actions_list[ndx]; ndx++)
11721     xfree (actions_list[ndx]);
11722
11723   xfree (actions_list);
11724 }
11725
11726 /* Recursive routine to walk through command list including loops, and
11727    download packets for each command.  */
11728
11729 static void
11730 remote_download_command_source (int num, ULONGEST addr,
11731                                 struct command_line *cmds)
11732 {
11733   struct remote_state *rs = get_remote_state ();
11734   struct command_line *cmd;
11735
11736   for (cmd = cmds; cmd; cmd = cmd->next)
11737     {
11738       QUIT;     /* Allow user to bail out with ^C.  */
11739       strcpy (rs->buf, "QTDPsrc:");
11740       encode_source_string (num, addr, "cmd", cmd->line,
11741                             rs->buf + strlen (rs->buf),
11742                             rs->buf_size - strlen (rs->buf));
11743       putpkt (rs->buf);
11744       remote_get_noisy_reply (&target_buf, &target_buf_size);
11745       if (strcmp (target_buf, "OK"))
11746         warning (_("Target does not support source download."));
11747
11748       if (cmd->control_type == while_control
11749           || cmd->control_type == while_stepping_control)
11750         {
11751           remote_download_command_source (num, addr, *cmd->body_list);
11752
11753           QUIT; /* Allow user to bail out with ^C.  */
11754           strcpy (rs->buf, "QTDPsrc:");
11755           encode_source_string (num, addr, "cmd", "end",
11756                                 rs->buf + strlen (rs->buf),
11757                                 rs->buf_size - strlen (rs->buf));
11758           putpkt (rs->buf);
11759           remote_get_noisy_reply (&target_buf, &target_buf_size);
11760           if (strcmp (target_buf, "OK"))
11761             warning (_("Target does not support source download."));
11762         }
11763     }
11764 }
11765
11766 static void
11767 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11768 {
11769 #define BUF_SIZE 2048
11770
11771   CORE_ADDR tpaddr;
11772   char addrbuf[40];
11773   char buf[BUF_SIZE];
11774   char **tdp_actions;
11775   char **stepping_actions;
11776   int ndx;
11777   struct cleanup *old_chain = NULL;
11778   struct agent_expr *aexpr;
11779   struct cleanup *aexpr_chain = NULL;
11780   char *pkt;
11781   struct breakpoint *b = loc->owner;
11782   struct tracepoint *t = (struct tracepoint *) b;
11783
11784   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11785   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11786                             tdp_actions);
11787   (void) make_cleanup (free_actions_list_cleanup_wrapper,
11788                        stepping_actions);
11789
11790   tpaddr = loc->address;
11791   sprintf_vma (addrbuf, tpaddr);
11792   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11793              addrbuf, /* address */
11794              (b->enable_state == bp_enabled ? 'E' : 'D'),
11795              t->step_count, t->pass_count);
11796   /* Fast tracepoints are mostly handled by the target, but we can
11797      tell the target how big of an instruction block should be moved
11798      around.  */
11799   if (b->type == bp_fast_tracepoint)
11800     {
11801       /* Only test for support at download time; we may not know
11802          target capabilities at definition time.  */
11803       if (remote_supports_fast_tracepoints ())
11804         {
11805           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11806                                                 NULL))
11807             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11808                        gdb_insn_length (loc->gdbarch, tpaddr));
11809           else
11810             /* If it passed validation at definition but fails now,
11811                something is very wrong.  */
11812             internal_error (__FILE__, __LINE__,
11813                             _("Fast tracepoint not "
11814                               "valid during download"));
11815         }
11816       else
11817         /* Fast tracepoints are functionally identical to regular
11818            tracepoints, so don't take lack of support as a reason to
11819            give up on the trace run.  */
11820         warning (_("Target does not support fast tracepoints, "
11821                    "downloading %d as regular tracepoint"), b->number);
11822     }
11823   else if (b->type == bp_static_tracepoint)
11824     {
11825       /* Only test for support at download time; we may not know
11826          target capabilities at definition time.  */
11827       if (remote_supports_static_tracepoints ())
11828         {
11829           struct static_tracepoint_marker marker;
11830
11831           if (target_static_tracepoint_marker_at (tpaddr, &marker))
11832             strcat (buf, ":S");
11833           else
11834             error (_("Static tracepoint not valid during download"));
11835         }
11836       else
11837         /* Fast tracepoints are functionally identical to regular
11838            tracepoints, so don't take lack of support as a reason
11839            to give up on the trace run.  */
11840         error (_("Target does not support static tracepoints"));
11841     }
11842   /* If the tracepoint has a conditional, make it into an agent
11843      expression and append to the definition.  */
11844   if (loc->cond)
11845     {
11846       /* Only test support at download time, we may not know target
11847          capabilities at definition time.  */
11848       if (remote_supports_cond_tracepoints ())
11849         {
11850           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11851           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11852           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11853                      aexpr->len);
11854           pkt = buf + strlen (buf);
11855           for (ndx = 0; ndx < aexpr->len; ++ndx)
11856             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11857           *pkt = '\0';
11858           do_cleanups (aexpr_chain);
11859         }
11860       else
11861         warning (_("Target does not support conditional tracepoints, "
11862                    "ignoring tp %d cond"), b->number);
11863     }
11864
11865   if (b->commands || *default_collect)
11866     strcat (buf, "-");
11867   putpkt (buf);
11868   remote_get_noisy_reply (&target_buf, &target_buf_size);
11869   if (strcmp (target_buf, "OK"))
11870     error (_("Target does not support tracepoints."));
11871
11872   /* do_single_steps (t); */
11873   if (tdp_actions)
11874     {
11875       for (ndx = 0; tdp_actions[ndx]; ndx++)
11876         {
11877           QUIT; /* Allow user to bail out with ^C.  */
11878           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11879                      b->number, addrbuf, /* address */
11880                      tdp_actions[ndx],
11881                      ((tdp_actions[ndx + 1] || stepping_actions)
11882                       ? '-' : 0));
11883           putpkt (buf);
11884           remote_get_noisy_reply (&target_buf,
11885                                   &target_buf_size);
11886           if (strcmp (target_buf, "OK"))
11887             error (_("Error on target while setting tracepoints."));
11888         }
11889     }
11890   if (stepping_actions)
11891     {
11892       for (ndx = 0; stepping_actions[ndx]; ndx++)
11893         {
11894           QUIT; /* Allow user to bail out with ^C.  */
11895           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11896                      b->number, addrbuf, /* address */
11897                      ((ndx == 0) ? "S" : ""),
11898                      stepping_actions[ndx],
11899                      (stepping_actions[ndx + 1] ? "-" : ""));
11900           putpkt (buf);
11901           remote_get_noisy_reply (&target_buf,
11902                                   &target_buf_size);
11903           if (strcmp (target_buf, "OK"))
11904             error (_("Error on target while setting tracepoints."));
11905         }
11906     }
11907
11908   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11909     {
11910       if (b->location != NULL)
11911         {
11912           strcpy (buf, "QTDPsrc:");
11913           encode_source_string (b->number, loc->address, "at",
11914                                 event_location_to_string (b->location),
11915                                 buf + strlen (buf), 2048 - strlen (buf));
11916           putpkt (buf);
11917           remote_get_noisy_reply (&target_buf, &target_buf_size);
11918           if (strcmp (target_buf, "OK"))
11919             warning (_("Target does not support source download."));
11920         }
11921       if (b->cond_string)
11922         {
11923           strcpy (buf, "QTDPsrc:");
11924           encode_source_string (b->number, loc->address,
11925                                 "cond", b->cond_string, buf + strlen (buf),
11926                                 2048 - strlen (buf));
11927           putpkt (buf);
11928           remote_get_noisy_reply (&target_buf, &target_buf_size);
11929           if (strcmp (target_buf, "OK"))
11930             warning (_("Target does not support source download."));
11931         }
11932       remote_download_command_source (b->number, loc->address,
11933                                       breakpoint_commands (b));
11934     }
11935
11936   do_cleanups (old_chain);
11937 }
11938
11939 static int
11940 remote_can_download_tracepoint (struct target_ops *self)
11941 {
11942   struct remote_state *rs = get_remote_state ();
11943   struct trace_status *ts;
11944   int status;
11945
11946   /* Don't try to install tracepoints until we've relocated our
11947      symbols, and fetched and merged the target's tracepoint list with
11948      ours.  */
11949   if (rs->starting_up)
11950     return 0;
11951
11952   ts = current_trace_status ();
11953   status = remote_get_trace_status (self, ts);
11954
11955   if (status == -1 || !ts->running_known || !ts->running)
11956     return 0;
11957
11958   /* If we are in a tracing experiment, but remote stub doesn't support
11959      installing tracepoint in trace, we have to return.  */
11960   if (!remote_supports_install_in_trace ())
11961     return 0;
11962
11963   return 1;
11964 }
11965
11966
11967 static void
11968 remote_download_trace_state_variable (struct target_ops *self,
11969                                       struct trace_state_variable *tsv)
11970 {
11971   struct remote_state *rs = get_remote_state ();
11972   char *p;
11973
11974   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11975              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11976              tsv->builtin);
11977   p = rs->buf + strlen (rs->buf);
11978   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11979     error (_("Trace state variable name too long for tsv definition packet"));
11980   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11981   *p++ = '\0';
11982   putpkt (rs->buf);
11983   remote_get_noisy_reply (&target_buf, &target_buf_size);
11984   if (*target_buf == '\0')
11985     error (_("Target does not support this command."));
11986   if (strcmp (target_buf, "OK") != 0)
11987     error (_("Error on target while downloading trace state variable."));
11988 }
11989
11990 static void
11991 remote_enable_tracepoint (struct target_ops *self,
11992                           struct bp_location *location)
11993 {
11994   struct remote_state *rs = get_remote_state ();
11995   char addr_buf[40];
11996
11997   sprintf_vma (addr_buf, location->address);
11998   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11999              location->owner->number, addr_buf);
12000   putpkt (rs->buf);
12001   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12002   if (*rs->buf == '\0')
12003     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12004   if (strcmp (rs->buf, "OK") != 0)
12005     error (_("Error on target while enabling tracepoint."));
12006 }
12007
12008 static void
12009 remote_disable_tracepoint (struct target_ops *self,
12010                            struct bp_location *location)
12011 {
12012   struct remote_state *rs = get_remote_state ();
12013   char addr_buf[40];
12014
12015   sprintf_vma (addr_buf, location->address);
12016   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12017              location->owner->number, addr_buf);
12018   putpkt (rs->buf);
12019   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12020   if (*rs->buf == '\0')
12021     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12022   if (strcmp (rs->buf, "OK") != 0)
12023     error (_("Error on target while disabling tracepoint."));
12024 }
12025
12026 static void
12027 remote_trace_set_readonly_regions (struct target_ops *self)
12028 {
12029   asection *s;
12030   bfd *abfd = NULL;
12031   bfd_size_type size;
12032   bfd_vma vma;
12033   int anysecs = 0;
12034   int offset = 0;
12035
12036   if (!exec_bfd)
12037     return;                     /* No information to give.  */
12038
12039   strcpy (target_buf, "QTro");
12040   offset = strlen (target_buf);
12041   for (s = exec_bfd->sections; s; s = s->next)
12042     {
12043       char tmp1[40], tmp2[40];
12044       int sec_length;
12045
12046       if ((s->flags & SEC_LOAD) == 0 ||
12047       /*  (s->flags & SEC_CODE) == 0 || */
12048           (s->flags & SEC_READONLY) == 0)
12049         continue;
12050
12051       anysecs = 1;
12052       vma = bfd_get_section_vma (abfd, s);
12053       size = bfd_get_section_size (s);
12054       sprintf_vma (tmp1, vma);
12055       sprintf_vma (tmp2, vma + size);
12056       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12057       if (offset + sec_length + 1 > target_buf_size)
12058         {
12059           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12060             warning (_("\
12061 Too many sections for read-only sections definition packet."));
12062           break;
12063         }
12064       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12065                  tmp1, tmp2);
12066       offset += sec_length;
12067     }
12068   if (anysecs)
12069     {
12070       putpkt (target_buf);
12071       getpkt (&target_buf, &target_buf_size, 0);
12072     }
12073 }
12074
12075 static void
12076 remote_trace_start (struct target_ops *self)
12077 {
12078   putpkt ("QTStart");
12079   remote_get_noisy_reply (&target_buf, &target_buf_size);
12080   if (*target_buf == '\0')
12081     error (_("Target does not support this command."));
12082   if (strcmp (target_buf, "OK") != 0)
12083     error (_("Bogus reply from target: %s"), target_buf);
12084 }
12085
12086 static int
12087 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12088 {
12089   /* Initialize it just to avoid a GCC false warning.  */
12090   char *p = NULL;
12091   /* FIXME we need to get register block size some other way.  */
12092   extern int trace_regblock_size;
12093   enum packet_result result;
12094
12095   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12096     return -1;
12097
12098   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12099
12100   putpkt ("qTStatus");
12101
12102   TRY
12103     {
12104       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12105     }
12106   CATCH (ex, RETURN_MASK_ERROR)
12107     {
12108       if (ex.error != TARGET_CLOSE_ERROR)
12109         {
12110           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12111           return -1;
12112         }
12113       throw_exception (ex);
12114     }
12115   END_CATCH
12116
12117   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12118
12119   /* If the remote target doesn't do tracing, flag it.  */
12120   if (result == PACKET_UNKNOWN)
12121     return -1;
12122
12123   /* We're working with a live target.  */
12124   ts->filename = NULL;
12125
12126   if (*p++ != 'T')
12127     error (_("Bogus trace status reply from target: %s"), target_buf);
12128
12129   /* Function 'parse_trace_status' sets default value of each field of
12130      'ts' at first, so we don't have to do it here.  */
12131   parse_trace_status (p, ts);
12132
12133   return ts->running;
12134 }
12135
12136 static void
12137 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12138                               struct uploaded_tp *utp)
12139 {
12140   struct remote_state *rs = get_remote_state ();
12141   char *reply;
12142   struct bp_location *loc;
12143   struct tracepoint *tp = (struct tracepoint *) bp;
12144   size_t size = get_remote_packet_size ();
12145
12146   if (tp)
12147     {
12148       tp->base.hit_count = 0;
12149       tp->traceframe_usage = 0;
12150       for (loc = tp->base.loc; loc; loc = loc->next)
12151         {
12152           /* If the tracepoint was never downloaded, don't go asking for
12153              any status.  */
12154           if (tp->number_on_target == 0)
12155             continue;
12156           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12157                      phex_nz (loc->address, 0));
12158           putpkt (rs->buf);
12159           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12160           if (reply && *reply)
12161             {
12162               if (*reply == 'V')
12163                 parse_tracepoint_status (reply + 1, bp, utp);
12164             }
12165         }
12166     }
12167   else if (utp)
12168     {
12169       utp->hit_count = 0;
12170       utp->traceframe_usage = 0;
12171       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12172                  phex_nz (utp->addr, 0));
12173       putpkt (rs->buf);
12174       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12175       if (reply && *reply)
12176         {
12177           if (*reply == 'V')
12178             parse_tracepoint_status (reply + 1, bp, utp);
12179         }
12180     }
12181 }
12182
12183 static void
12184 remote_trace_stop (struct target_ops *self)
12185 {
12186   putpkt ("QTStop");
12187   remote_get_noisy_reply (&target_buf, &target_buf_size);
12188   if (*target_buf == '\0')
12189     error (_("Target does not support this command."));
12190   if (strcmp (target_buf, "OK") != 0)
12191     error (_("Bogus reply from target: %s"), target_buf);
12192 }
12193
12194 static int
12195 remote_trace_find (struct target_ops *self,
12196                    enum trace_find_type type, int num,
12197                    CORE_ADDR addr1, CORE_ADDR addr2,
12198                    int *tpp)
12199 {
12200   struct remote_state *rs = get_remote_state ();
12201   char *endbuf = rs->buf + get_remote_packet_size ();
12202   char *p, *reply;
12203   int target_frameno = -1, target_tracept = -1;
12204
12205   /* Lookups other than by absolute frame number depend on the current
12206      trace selected, so make sure it is correct on the remote end
12207      first.  */
12208   if (type != tfind_number)
12209     set_remote_traceframe ();
12210
12211   p = rs->buf;
12212   strcpy (p, "QTFrame:");
12213   p = strchr (p, '\0');
12214   switch (type)
12215     {
12216     case tfind_number:
12217       xsnprintf (p, endbuf - p, "%x", num);
12218       break;
12219     case tfind_pc:
12220       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12221       break;
12222     case tfind_tp:
12223       xsnprintf (p, endbuf - p, "tdp:%x", num);
12224       break;
12225     case tfind_range:
12226       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12227                  phex_nz (addr2, 0));
12228       break;
12229     case tfind_outside:
12230       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12231                  phex_nz (addr2, 0));
12232       break;
12233     default:
12234       error (_("Unknown trace find type %d"), type);
12235     }
12236
12237   putpkt (rs->buf);
12238   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12239   if (*reply == '\0')
12240     error (_("Target does not support this command."));
12241
12242   while (reply && *reply)
12243     switch (*reply)
12244       {
12245       case 'F':
12246         p = ++reply;
12247         target_frameno = (int) strtol (p, &reply, 16);
12248         if (reply == p)
12249           error (_("Unable to parse trace frame number"));
12250         /* Don't update our remote traceframe number cache on failure
12251            to select a remote traceframe.  */
12252         if (target_frameno == -1)
12253           return -1;
12254         break;
12255       case 'T':
12256         p = ++reply;
12257         target_tracept = (int) strtol (p, &reply, 16);
12258         if (reply == p)
12259           error (_("Unable to parse tracepoint number"));
12260         break;
12261       case 'O':         /* "OK"? */
12262         if (reply[1] == 'K' && reply[2] == '\0')
12263           reply += 2;
12264         else
12265           error (_("Bogus reply from target: %s"), reply);
12266         break;
12267       default:
12268         error (_("Bogus reply from target: %s"), reply);
12269       }
12270   if (tpp)
12271     *tpp = target_tracept;
12272
12273   rs->remote_traceframe_number = target_frameno;
12274   return target_frameno;
12275 }
12276
12277 static int
12278 remote_get_trace_state_variable_value (struct target_ops *self,
12279                                        int tsvnum, LONGEST *val)
12280 {
12281   struct remote_state *rs = get_remote_state ();
12282   char *reply;
12283   ULONGEST uval;
12284
12285   set_remote_traceframe ();
12286
12287   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12288   putpkt (rs->buf);
12289   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12290   if (reply && *reply)
12291     {
12292       if (*reply == 'V')
12293         {
12294           unpack_varlen_hex (reply + 1, &uval);
12295           *val = (LONGEST) uval;
12296           return 1;
12297         }
12298     }
12299   return 0;
12300 }
12301
12302 static int
12303 remote_save_trace_data (struct target_ops *self, const char *filename)
12304 {
12305   struct remote_state *rs = get_remote_state ();
12306   char *p, *reply;
12307
12308   p = rs->buf;
12309   strcpy (p, "QTSave:");
12310   p += strlen (p);
12311   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12312     error (_("Remote file name too long for trace save packet"));
12313   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12314   *p++ = '\0';
12315   putpkt (rs->buf);
12316   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12317   if (*reply == '\0')
12318     error (_("Target does not support this command."));
12319   if (strcmp (reply, "OK") != 0)
12320     error (_("Bogus reply from target: %s"), reply);
12321   return 0;
12322 }
12323
12324 /* This is basically a memory transfer, but needs to be its own packet
12325    because we don't know how the target actually organizes its trace
12326    memory, plus we want to be able to ask for as much as possible, but
12327    not be unhappy if we don't get as much as we ask for.  */
12328
12329 static LONGEST
12330 remote_get_raw_trace_data (struct target_ops *self,
12331                            gdb_byte *buf, ULONGEST offset, LONGEST len)
12332 {
12333   struct remote_state *rs = get_remote_state ();
12334   char *reply;
12335   char *p;
12336   int rslt;
12337
12338   p = rs->buf;
12339   strcpy (p, "qTBuffer:");
12340   p += strlen (p);
12341   p += hexnumstr (p, offset);
12342   *p++ = ',';
12343   p += hexnumstr (p, len);
12344   *p++ = '\0';
12345
12346   putpkt (rs->buf);
12347   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12348   if (reply && *reply)
12349     {
12350       /* 'l' by itself means we're at the end of the buffer and
12351          there is nothing more to get.  */
12352       if (*reply == 'l')
12353         return 0;
12354
12355       /* Convert the reply into binary.  Limit the number of bytes to
12356          convert according to our passed-in buffer size, rather than
12357          what was returned in the packet; if the target is
12358          unexpectedly generous and gives us a bigger reply than we
12359          asked for, we don't want to crash.  */
12360       rslt = hex2bin (target_buf, buf, len);
12361       return rslt;
12362     }
12363
12364   /* Something went wrong, flag as an error.  */
12365   return -1;
12366 }
12367
12368 static void
12369 remote_set_disconnected_tracing (struct target_ops *self, int val)
12370 {
12371   struct remote_state *rs = get_remote_state ();
12372
12373   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12374     {
12375       char *reply;
12376
12377       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12378       putpkt (rs->buf);
12379       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12380       if (*reply == '\0')
12381         error (_("Target does not support this command."));
12382       if (strcmp (reply, "OK") != 0)
12383         error (_("Bogus reply from target: %s"), reply);
12384     }
12385   else if (val)
12386     warning (_("Target does not support disconnected tracing."));
12387 }
12388
12389 static int
12390 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12391 {
12392   struct thread_info *info = find_thread_ptid (ptid);
12393
12394   if (info && info->priv)
12395     return info->priv->core;
12396   return -1;
12397 }
12398
12399 static void
12400 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12401 {
12402   struct remote_state *rs = get_remote_state ();
12403   char *reply;
12404
12405   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12406   putpkt (rs->buf);
12407   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12408   if (*reply == '\0')
12409     error (_("Target does not support this command."));
12410   if (strcmp (reply, "OK") != 0)
12411     error (_("Bogus reply from target: %s"), reply);
12412 }
12413
12414 static struct traceframe_info *
12415 remote_traceframe_info (struct target_ops *self)
12416 {
12417   char *text;
12418
12419   text = target_read_stralloc (&current_target,
12420                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12421   if (text != NULL)
12422     {
12423       struct traceframe_info *info;
12424       struct cleanup *back_to = make_cleanup (xfree, text);
12425
12426       info = parse_traceframe_info (text);
12427       do_cleanups (back_to);
12428       return info;
12429     }
12430
12431   return NULL;
12432 }
12433
12434 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
12435    instruction on which a fast tracepoint may be placed.  Returns -1
12436    if the packet is not supported, and 0 if the minimum instruction
12437    length is unknown.  */
12438
12439 static int
12440 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12441 {
12442   struct remote_state *rs = get_remote_state ();
12443   char *reply;
12444
12445   /* If we're not debugging a process yet, the IPA can't be
12446      loaded.  */
12447   if (!target_has_execution)
12448     return 0;
12449
12450   /* Make sure the remote is pointing at the right process.  */
12451   set_general_process ();
12452
12453   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12454   putpkt (rs->buf);
12455   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12456   if (*reply == '\0')
12457     return -1;
12458   else
12459     {
12460       ULONGEST min_insn_len;
12461
12462       unpack_varlen_hex (reply, &min_insn_len);
12463
12464       return (int) min_insn_len;
12465     }
12466 }
12467
12468 static void
12469 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12470 {
12471   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12472     {
12473       struct remote_state *rs = get_remote_state ();
12474       char *buf = rs->buf;
12475       char *endbuf = rs->buf + get_remote_packet_size ();
12476       enum packet_result result;
12477
12478       gdb_assert (val >= 0 || val == -1);
12479       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12480       /* Send -1 as literal "-1" to avoid host size dependency.  */
12481       if (val < 0)
12482         {
12483           *buf++ = '-';
12484           buf += hexnumstr (buf, (ULONGEST) -val);
12485         }
12486       else
12487         buf += hexnumstr (buf, (ULONGEST) val);
12488
12489       putpkt (rs->buf);
12490       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12491       result = packet_ok (rs->buf,
12492                   &remote_protocol_packets[PACKET_QTBuffer_size]);
12493
12494       if (result != PACKET_OK)
12495         warning (_("Bogus reply from target: %s"), rs->buf);
12496     }
12497 }
12498
12499 static int
12500 remote_set_trace_notes (struct target_ops *self,
12501                         const char *user, const char *notes,
12502                         const char *stop_notes)
12503 {
12504   struct remote_state *rs = get_remote_state ();
12505   char *reply;
12506   char *buf = rs->buf;
12507   char *endbuf = rs->buf + get_remote_packet_size ();
12508   int nbytes;
12509
12510   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12511   if (user)
12512     {
12513       buf += xsnprintf (buf, endbuf - buf, "user:");
12514       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12515       buf += 2 * nbytes;
12516       *buf++ = ';';
12517     }
12518   if (notes)
12519     {
12520       buf += xsnprintf (buf, endbuf - buf, "notes:");
12521       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12522       buf += 2 * nbytes;
12523       *buf++ = ';';
12524     }
12525   if (stop_notes)
12526     {
12527       buf += xsnprintf (buf, endbuf - buf, "tstop:");
12528       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12529       buf += 2 * nbytes;
12530       *buf++ = ';';
12531     }
12532   /* Ensure the buffer is terminated.  */
12533   *buf = '\0';
12534
12535   putpkt (rs->buf);
12536   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12537   if (*reply == '\0')
12538     return 0;
12539
12540   if (strcmp (reply, "OK") != 0)
12541     error (_("Bogus reply from target: %s"), reply);
12542
12543   return 1;
12544 }
12545
12546 static int
12547 remote_use_agent (struct target_ops *self, int use)
12548 {
12549   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12550     {
12551       struct remote_state *rs = get_remote_state ();
12552
12553       /* If the stub supports QAgent.  */
12554       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12555       putpkt (rs->buf);
12556       getpkt (&rs->buf, &rs->buf_size, 0);
12557
12558       if (strcmp (rs->buf, "OK") == 0)
12559         {
12560           use_agent = use;
12561           return 1;
12562         }
12563     }
12564
12565   return 0;
12566 }
12567
12568 static int
12569 remote_can_use_agent (struct target_ops *self)
12570 {
12571   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12572 }
12573
12574 struct btrace_target_info
12575 {
12576   /* The ptid of the traced thread.  */
12577   ptid_t ptid;
12578
12579   /* The obtained branch trace configuration.  */
12580   struct btrace_config conf;
12581 };
12582
12583 /* Reset our idea of our target's btrace configuration.  */
12584
12585 static void
12586 remote_btrace_reset (void)
12587 {
12588   struct remote_state *rs = get_remote_state ();
12589
12590   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12591 }
12592
12593 /* Check whether the target supports branch tracing.  */
12594
12595 static int
12596 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12597 {
12598   if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12599     return 0;
12600   if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12601     return 0;
12602
12603   switch (format)
12604     {
12605       case BTRACE_FORMAT_NONE:
12606         return 0;
12607
12608       case BTRACE_FORMAT_BTS:
12609         return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12610
12611       case BTRACE_FORMAT_PT:
12612         /* The trace is decoded on the host.  Even if our target supports it,
12613            we still need to have libipt to decode the trace.  */
12614 #if defined (HAVE_LIBIPT)
12615         return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12616 #else /* !defined (HAVE_LIBIPT)  */
12617         return 0;
12618 #endif /* !defined (HAVE_LIBIPT)  */
12619     }
12620
12621   internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12622 }
12623
12624 /* Synchronize the configuration with the target.  */
12625
12626 static void
12627 btrace_sync_conf (const struct btrace_config *conf)
12628 {
12629   struct packet_config *packet;
12630   struct remote_state *rs;
12631   char *buf, *pos, *endbuf;
12632
12633   rs = get_remote_state ();
12634   buf = rs->buf;
12635   endbuf = buf + get_remote_packet_size ();
12636
12637   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12638   if (packet_config_support (packet) == PACKET_ENABLE
12639       && conf->bts.size != rs->btrace_config.bts.size)
12640     {
12641       pos = buf;
12642       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12643                         conf->bts.size);
12644
12645       putpkt (buf);
12646       getpkt (&buf, &rs->buf_size, 0);
12647
12648       if (packet_ok (buf, packet) == PACKET_ERROR)
12649         {
12650           if (buf[0] == 'E' && buf[1] == '.')
12651             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12652           else
12653             error (_("Failed to configure the BTS buffer size."));
12654         }
12655
12656       rs->btrace_config.bts.size = conf->bts.size;
12657     }
12658
12659   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12660   if (packet_config_support (packet) == PACKET_ENABLE
12661       && conf->pt.size != rs->btrace_config.pt.size)
12662     {
12663       pos = buf;
12664       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12665                         conf->pt.size);
12666
12667       putpkt (buf);
12668       getpkt (&buf, &rs->buf_size, 0);
12669
12670       if (packet_ok (buf, packet) == PACKET_ERROR)
12671         {
12672           if (buf[0] == 'E' && buf[1] == '.')
12673             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12674           else
12675             error (_("Failed to configure the trace buffer size."));
12676         }
12677
12678       rs->btrace_config.pt.size = conf->pt.size;
12679     }
12680 }
12681
12682 /* Read the current thread's btrace configuration from the target and
12683    store it into CONF.  */
12684
12685 static void
12686 btrace_read_config (struct btrace_config *conf)
12687 {
12688   char *xml;
12689
12690   xml = target_read_stralloc (&current_target,
12691                               TARGET_OBJECT_BTRACE_CONF, "");
12692   if (xml != NULL)
12693     {
12694       struct cleanup *cleanup;
12695
12696       cleanup = make_cleanup (xfree, xml);
12697       parse_xml_btrace_conf (conf, xml);
12698       do_cleanups (cleanup);
12699     }
12700 }
12701
12702 /* Enable branch tracing.  */
12703
12704 static struct btrace_target_info *
12705 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12706                       const struct btrace_config *conf)
12707 {
12708   struct btrace_target_info *tinfo = NULL;
12709   struct packet_config *packet = NULL;
12710   struct remote_state *rs = get_remote_state ();
12711   char *buf = rs->buf;
12712   char *endbuf = rs->buf + get_remote_packet_size ();
12713
12714   switch (conf->format)
12715     {
12716       case BTRACE_FORMAT_BTS:
12717         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12718         break;
12719
12720       case BTRACE_FORMAT_PT:
12721         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12722         break;
12723     }
12724
12725   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12726     error (_("Target does not support branch tracing."));
12727
12728   btrace_sync_conf (conf);
12729
12730   set_general_thread (ptid);
12731
12732   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12733   putpkt (rs->buf);
12734   getpkt (&rs->buf, &rs->buf_size, 0);
12735
12736   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12737     {
12738       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12739         error (_("Could not enable branch tracing for %s: %s"),
12740                target_pid_to_str (ptid), rs->buf + 2);
12741       else
12742         error (_("Could not enable branch tracing for %s."),
12743                target_pid_to_str (ptid));
12744     }
12745
12746   tinfo = XCNEW (struct btrace_target_info);
12747   tinfo->ptid = ptid;
12748
12749   /* If we fail to read the configuration, we lose some information, but the
12750      tracing itself is not impacted.  */
12751   TRY
12752     {
12753       btrace_read_config (&tinfo->conf);
12754     }
12755   CATCH (err, RETURN_MASK_ERROR)
12756     {
12757       if (err.message != NULL)
12758         warning ("%s", err.message);
12759     }
12760   END_CATCH
12761
12762   return tinfo;
12763 }
12764
12765 /* Disable branch tracing.  */
12766
12767 static void
12768 remote_disable_btrace (struct target_ops *self,
12769                        struct btrace_target_info *tinfo)
12770 {
12771   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12772   struct remote_state *rs = get_remote_state ();
12773   char *buf = rs->buf;
12774   char *endbuf = rs->buf + get_remote_packet_size ();
12775
12776   if (packet_config_support (packet) != PACKET_ENABLE)
12777     error (_("Target does not support branch tracing."));
12778
12779   set_general_thread (tinfo->ptid);
12780
12781   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12782   putpkt (rs->buf);
12783   getpkt (&rs->buf, &rs->buf_size, 0);
12784
12785   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12786     {
12787       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12788         error (_("Could not disable branch tracing for %s: %s"),
12789                target_pid_to_str (tinfo->ptid), rs->buf + 2);
12790       else
12791         error (_("Could not disable branch tracing for %s."),
12792                target_pid_to_str (tinfo->ptid));
12793     }
12794
12795   xfree (tinfo);
12796 }
12797
12798 /* Teardown branch tracing.  */
12799
12800 static void
12801 remote_teardown_btrace (struct target_ops *self,
12802                         struct btrace_target_info *tinfo)
12803 {
12804   /* We must not talk to the target during teardown.  */
12805   xfree (tinfo);
12806 }
12807
12808 /* Read the branch trace.  */
12809
12810 static enum btrace_error
12811 remote_read_btrace (struct target_ops *self,
12812                     struct btrace_data *btrace,
12813                     struct btrace_target_info *tinfo,
12814                     enum btrace_read_type type)
12815 {
12816   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12817   struct remote_state *rs = get_remote_state ();
12818   struct cleanup *cleanup;
12819   const char *annex;
12820   char *xml;
12821
12822   if (packet_config_support (packet) != PACKET_ENABLE)
12823     error (_("Target does not support branch tracing."));
12824
12825 #if !defined(HAVE_LIBEXPAT)
12826   error (_("Cannot process branch tracing result. XML parsing not supported."));
12827 #endif
12828
12829   switch (type)
12830     {
12831     case BTRACE_READ_ALL:
12832       annex = "all";
12833       break;
12834     case BTRACE_READ_NEW:
12835       annex = "new";
12836       break;
12837     case BTRACE_READ_DELTA:
12838       annex = "delta";
12839       break;
12840     default:
12841       internal_error (__FILE__, __LINE__,
12842                       _("Bad branch tracing read type: %u."),
12843                       (unsigned int) type);
12844     }
12845
12846   xml = target_read_stralloc (&current_target,
12847                               TARGET_OBJECT_BTRACE, annex);
12848   if (xml == NULL)
12849     return BTRACE_ERR_UNKNOWN;
12850
12851   cleanup = make_cleanup (xfree, xml);
12852   parse_xml_btrace (btrace, xml);
12853   do_cleanups (cleanup);
12854
12855   return BTRACE_ERR_NONE;
12856 }
12857
12858 static const struct btrace_config *
12859 remote_btrace_conf (struct target_ops *self,
12860                     const struct btrace_target_info *tinfo)
12861 {
12862   return &tinfo->conf;
12863 }
12864
12865 static int
12866 remote_augmented_libraries_svr4_read (struct target_ops *self)
12867 {
12868   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12869           == PACKET_ENABLE);
12870 }
12871
12872 /* Implementation of to_load.  */
12873
12874 static void
12875 remote_load (struct target_ops *self, const char *name, int from_tty)
12876 {
12877   generic_load (name, from_tty);
12878 }
12879
12880 /* Accepts an integer PID; returns a string representing a file that
12881    can be opened on the remote side to get the symbols for the child
12882    process.  Returns NULL if the operation is not supported.  */
12883
12884 static char *
12885 remote_pid_to_exec_file (struct target_ops *self, int pid)
12886 {
12887   static char *filename = NULL;
12888   struct inferior *inf;
12889   char *annex = NULL;
12890
12891   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12892     return NULL;
12893
12894   if (filename != NULL)
12895     xfree (filename);
12896
12897   inf = find_inferior_pid (pid);
12898   if (inf == NULL)
12899     internal_error (__FILE__, __LINE__,
12900                     _("not currently attached to process %d"), pid);
12901
12902   if (!inf->fake_pid_p)
12903     {
12904       const int annex_size = 9;
12905
12906       annex = (char *) alloca (annex_size);
12907       xsnprintf (annex, annex_size, "%x", pid);
12908     }
12909
12910   filename = target_read_stralloc (&current_target,
12911                                    TARGET_OBJECT_EXEC_FILE, annex);
12912
12913   return filename;
12914 }
12915
12916 /* Implement the to_can_do_single_step target_ops method.  */
12917
12918 static int
12919 remote_can_do_single_step (struct target_ops *ops)
12920 {
12921   /* We can only tell whether target supports single step or not by
12922      supported s and S vCont actions if the stub supports vContSupported
12923      feature.  If the stub doesn't support vContSupported feature,
12924      we have conservatively to think target doesn't supports single
12925      step.  */
12926   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12927     {
12928       struct remote_state *rs = get_remote_state ();
12929
12930       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12931         remote_vcont_probe (rs);
12932
12933       return rs->supports_vCont.s && rs->supports_vCont.S;
12934     }
12935   else
12936     return 0;
12937 }
12938
12939 static void
12940 init_remote_ops (void)
12941 {
12942   remote_ops.to_shortname = "remote";
12943   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12944   remote_ops.to_doc =
12945     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12946 Specify the serial device it is connected to\n\
12947 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12948   remote_ops.to_open = remote_open;
12949   remote_ops.to_close = remote_close;
12950   remote_ops.to_detach = remote_detach;
12951   remote_ops.to_disconnect = remote_disconnect;
12952   remote_ops.to_resume = remote_resume;
12953   remote_ops.to_wait = remote_wait;
12954   remote_ops.to_fetch_registers = remote_fetch_registers;
12955   remote_ops.to_store_registers = remote_store_registers;
12956   remote_ops.to_prepare_to_store = remote_prepare_to_store;
12957   remote_ops.to_files_info = remote_files_info;
12958   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12959   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12960   remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12961   remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12962   remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12963   remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12964   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12965   remote_ops.to_stopped_data_address = remote_stopped_data_address;
12966   remote_ops.to_watchpoint_addr_within_range =
12967     remote_watchpoint_addr_within_range;
12968   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12969   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12970   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12971   remote_ops.to_region_ok_for_hw_watchpoint
12972      = remote_region_ok_for_hw_watchpoint;
12973   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12974   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12975   remote_ops.to_kill = remote_kill;
12976   remote_ops.to_load = remote_load;
12977   remote_ops.to_mourn_inferior = remote_mourn;
12978   remote_ops.to_pass_signals = remote_pass_signals;
12979   remote_ops.to_program_signals = remote_program_signals;
12980   remote_ops.to_thread_alive = remote_thread_alive;
12981   remote_ops.to_thread_name = remote_thread_name;
12982   remote_ops.to_update_thread_list = remote_update_thread_list;
12983   remote_ops.to_pid_to_str = remote_pid_to_str;
12984   remote_ops.to_extra_thread_info = remote_threads_extra_info;
12985   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12986   remote_ops.to_stop = remote_stop;
12987   remote_ops.to_interrupt = remote_interrupt;
12988   remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12989   remote_ops.to_xfer_partial = remote_xfer_partial;
12990   remote_ops.to_rcmd = remote_rcmd;
12991   remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12992   remote_ops.to_log_command = serial_log_command;
12993   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12994   remote_ops.to_stratum = process_stratum;
12995   remote_ops.to_has_all_memory = default_child_has_all_memory;
12996   remote_ops.to_has_memory = default_child_has_memory;
12997   remote_ops.to_has_stack = default_child_has_stack;
12998   remote_ops.to_has_registers = default_child_has_registers;
12999   remote_ops.to_has_execution = default_child_has_execution;
13000   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
13001   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13002   remote_ops.to_magic = OPS_MAGIC;
13003   remote_ops.to_memory_map = remote_memory_map;
13004   remote_ops.to_flash_erase = remote_flash_erase;
13005   remote_ops.to_flash_done = remote_flash_done;
13006   remote_ops.to_read_description = remote_read_description;
13007   remote_ops.to_search_memory = remote_search_memory;
13008   remote_ops.to_can_async_p = remote_can_async_p;
13009   remote_ops.to_is_async_p = remote_is_async_p;
13010   remote_ops.to_async = remote_async;
13011   remote_ops.to_thread_events = remote_thread_events;
13012   remote_ops.to_can_do_single_step = remote_can_do_single_step;
13013   remote_ops.to_terminal_inferior = remote_terminal_inferior;
13014   remote_ops.to_terminal_ours = remote_terminal_ours;
13015   remote_ops.to_supports_non_stop = remote_supports_non_stop;
13016   remote_ops.to_supports_multi_process = remote_supports_multi_process;
13017   remote_ops.to_supports_disable_randomization
13018     = remote_supports_disable_randomization;
13019   remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13020   remote_ops.to_fileio_open = remote_hostio_open;
13021   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13022   remote_ops.to_fileio_pread = remote_hostio_pread;
13023   remote_ops.to_fileio_fstat = remote_hostio_fstat;
13024   remote_ops.to_fileio_close = remote_hostio_close;
13025   remote_ops.to_fileio_unlink = remote_hostio_unlink;
13026   remote_ops.to_fileio_readlink = remote_hostio_readlink;
13027   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13028   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13029   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13030   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13031   remote_ops.to_trace_init = remote_trace_init;
13032   remote_ops.to_download_tracepoint = remote_download_tracepoint;
13033   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13034   remote_ops.to_download_trace_state_variable
13035     = remote_download_trace_state_variable;
13036   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13037   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13038   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13039   remote_ops.to_trace_start = remote_trace_start;
13040   remote_ops.to_get_trace_status = remote_get_trace_status;
13041   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13042   remote_ops.to_trace_stop = remote_trace_stop;
13043   remote_ops.to_trace_find = remote_trace_find;
13044   remote_ops.to_get_trace_state_variable_value
13045     = remote_get_trace_state_variable_value;
13046   remote_ops.to_save_trace_data = remote_save_trace_data;
13047   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13048   remote_ops.to_upload_trace_state_variables
13049     = remote_upload_trace_state_variables;
13050   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13051   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13052   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13053   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13054   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13055   remote_ops.to_set_trace_notes = remote_set_trace_notes;
13056   remote_ops.to_core_of_thread = remote_core_of_thread;
13057   remote_ops.to_verify_memory = remote_verify_memory;
13058   remote_ops.to_get_tib_address = remote_get_tib_address;
13059   remote_ops.to_set_permissions = remote_set_permissions;
13060   remote_ops.to_static_tracepoint_marker_at
13061     = remote_static_tracepoint_marker_at;
13062   remote_ops.to_static_tracepoint_markers_by_strid
13063     = remote_static_tracepoint_markers_by_strid;
13064   remote_ops.to_traceframe_info = remote_traceframe_info;
13065   remote_ops.to_use_agent = remote_use_agent;
13066   remote_ops.to_can_use_agent = remote_can_use_agent;
13067   remote_ops.to_supports_btrace = remote_supports_btrace;
13068   remote_ops.to_enable_btrace = remote_enable_btrace;
13069   remote_ops.to_disable_btrace = remote_disable_btrace;
13070   remote_ops.to_teardown_btrace = remote_teardown_btrace;
13071   remote_ops.to_read_btrace = remote_read_btrace;
13072   remote_ops.to_btrace_conf = remote_btrace_conf;
13073   remote_ops.to_augmented_libraries_svr4_read =
13074     remote_augmented_libraries_svr4_read;
13075   remote_ops.to_follow_fork = remote_follow_fork;
13076   remote_ops.to_follow_exec = remote_follow_exec;
13077   remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13078   remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13079   remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13080   remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13081   remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13082   remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13083 }
13084
13085 /* Set up the extended remote vector by making a copy of the standard
13086    remote vector and adding to it.  */
13087
13088 static void
13089 init_extended_remote_ops (void)
13090 {
13091   extended_remote_ops = remote_ops;
13092
13093   extended_remote_ops.to_shortname = "extended-remote";
13094   extended_remote_ops.to_longname =
13095     "Extended remote serial target in gdb-specific protocol";
13096   extended_remote_ops.to_doc =
13097     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13098 Specify the serial device it is connected to (e.g. /dev/ttya).";
13099   extended_remote_ops.to_open = extended_remote_open;
13100   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13101   extended_remote_ops.to_detach = extended_remote_detach;
13102   extended_remote_ops.to_attach = extended_remote_attach;
13103   extended_remote_ops.to_post_attach = extended_remote_post_attach;
13104   extended_remote_ops.to_supports_disable_randomization
13105     = extended_remote_supports_disable_randomization;
13106 }
13107
13108 static int
13109 remote_can_async_p (struct target_ops *ops)
13110 {
13111   struct remote_state *rs = get_remote_state ();
13112
13113   if (!target_async_permitted)
13114     /* We only enable async when the user specifically asks for it.  */
13115     return 0;
13116
13117   /* We're async whenever the serial device is.  */
13118   return serial_can_async_p (rs->remote_desc);
13119 }
13120
13121 static int
13122 remote_is_async_p (struct target_ops *ops)
13123 {
13124   struct remote_state *rs = get_remote_state ();
13125
13126   if (!target_async_permitted)
13127     /* We only enable async when the user specifically asks for it.  */
13128     return 0;
13129
13130   /* We're async whenever the serial device is.  */
13131   return serial_is_async_p (rs->remote_desc);
13132 }
13133
13134 /* Pass the SERIAL event on and up to the client.  One day this code
13135    will be able to delay notifying the client of an event until the
13136    point where an entire packet has been received.  */
13137
13138 static serial_event_ftype remote_async_serial_handler;
13139
13140 static void
13141 remote_async_serial_handler (struct serial *scb, void *context)
13142 {
13143   struct remote_state *rs = (struct remote_state *) context;
13144
13145   /* Don't propogate error information up to the client.  Instead let
13146      the client find out about the error by querying the target.  */
13147   inferior_event_handler (INF_REG_EVENT, NULL);
13148 }
13149
13150 static void
13151 remote_async_inferior_event_handler (gdb_client_data data)
13152 {
13153   inferior_event_handler (INF_REG_EVENT, NULL);
13154 }
13155
13156 static void
13157 remote_async (struct target_ops *ops, int enable)
13158 {
13159   struct remote_state *rs = get_remote_state ();
13160
13161   if (enable)
13162     {
13163       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13164
13165       /* If there are pending events in the stop reply queue tell the
13166          event loop to process them.  */
13167       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13168         mark_async_event_handler (remote_async_inferior_event_token);
13169       /* For simplicity, below we clear the pending events token
13170          without remembering whether it is marked, so here we always
13171          mark it.  If there's actually no pending notification to
13172          process, this ends up being a no-op (other than a spurious
13173          event-loop wakeup).  */
13174       if (target_is_non_stop_p ())
13175         mark_async_event_handler (rs->notif_state->get_pending_events_token);
13176     }
13177   else
13178     {
13179       serial_async (rs->remote_desc, NULL, NULL);
13180       /* If the core is disabling async, it doesn't want to be
13181          disturbed with target events.  Clear all async event sources
13182          too.  */
13183       clear_async_event_handler (remote_async_inferior_event_token);
13184       if (target_is_non_stop_p ())
13185         clear_async_event_handler (rs->notif_state->get_pending_events_token);
13186     }
13187 }
13188
13189 /* Implementation of the to_thread_events method.  */
13190
13191 static void
13192 remote_thread_events (struct target_ops *ops, int enable)
13193 {
13194   struct remote_state *rs = get_remote_state ();
13195   size_t size = get_remote_packet_size ();
13196   char *p = rs->buf;
13197
13198   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13199     return;
13200
13201   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13202   putpkt (rs->buf);
13203   getpkt (&rs->buf, &rs->buf_size, 0);
13204
13205   switch (packet_ok (rs->buf,
13206                      &remote_protocol_packets[PACKET_QThreadEvents]))
13207     {
13208     case PACKET_OK:
13209       if (strcmp (rs->buf, "OK") != 0)
13210         error (_("Remote refused setting thread events: %s"), rs->buf);
13211       break;
13212     case PACKET_ERROR:
13213       warning (_("Remote failure reply: %s"), rs->buf);
13214       break;
13215     case PACKET_UNKNOWN:
13216       break;
13217     }
13218 }
13219
13220 static void
13221 set_remote_cmd (char *args, int from_tty)
13222 {
13223   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13224 }
13225
13226 static void
13227 show_remote_cmd (char *args, int from_tty)
13228 {
13229   /* We can't just use cmd_show_list here, because we want to skip
13230      the redundant "show remote Z-packet" and the legacy aliases.  */
13231   struct cleanup *showlist_chain;
13232   struct cmd_list_element *list = remote_show_cmdlist;
13233   struct ui_out *uiout = current_uiout;
13234
13235   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13236   for (; list != NULL; list = list->next)
13237     if (strcmp (list->name, "Z-packet") == 0)
13238       continue;
13239     else if (list->type == not_set_cmd)
13240       /* Alias commands are exactly like the original, except they
13241          don't have the normal type.  */
13242       continue;
13243     else
13244       {
13245         struct cleanup *option_chain
13246           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13247
13248         ui_out_field_string (uiout, "name", list->name);
13249         ui_out_text (uiout, ":  ");
13250         if (list->type == show_cmd)
13251           do_show_command ((char *) NULL, from_tty, list);
13252         else
13253           cmd_func (list, NULL, from_tty);
13254         /* Close the tuple.  */
13255         do_cleanups (option_chain);
13256       }
13257
13258   /* Close the tuple.  */
13259   do_cleanups (showlist_chain);
13260 }
13261
13262
13263 /* Function to be called whenever a new objfile (shlib) is detected.  */
13264 static void
13265 remote_new_objfile (struct objfile *objfile)
13266 {
13267   struct remote_state *rs = get_remote_state ();
13268
13269   if (rs->remote_desc != 0)             /* Have a remote connection.  */
13270     remote_check_symbols ();
13271 }
13272
13273 /* Pull all the tracepoints defined on the target and create local
13274    data structures representing them.  We don't want to create real
13275    tracepoints yet, we don't want to mess up the user's existing
13276    collection.  */
13277   
13278 static int
13279 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13280 {
13281   struct remote_state *rs = get_remote_state ();
13282   char *p;
13283
13284   /* Ask for a first packet of tracepoint definition.  */
13285   putpkt ("qTfP");
13286   getpkt (&rs->buf, &rs->buf_size, 0);
13287   p = rs->buf;
13288   while (*p && *p != 'l')
13289     {
13290       parse_tracepoint_definition (p, utpp);
13291       /* Ask for another packet of tracepoint definition.  */
13292       putpkt ("qTsP");
13293       getpkt (&rs->buf, &rs->buf_size, 0);
13294       p = rs->buf;
13295     }
13296   return 0;
13297 }
13298
13299 static int
13300 remote_upload_trace_state_variables (struct target_ops *self,
13301                                      struct uploaded_tsv **utsvp)
13302 {
13303   struct remote_state *rs = get_remote_state ();
13304   char *p;
13305
13306   /* Ask for a first packet of variable definition.  */
13307   putpkt ("qTfV");
13308   getpkt (&rs->buf, &rs->buf_size, 0);
13309   p = rs->buf;
13310   while (*p && *p != 'l')
13311     {
13312       parse_tsv_definition (p, utsvp);
13313       /* Ask for another packet of variable definition.  */
13314       putpkt ("qTsV");
13315       getpkt (&rs->buf, &rs->buf_size, 0);
13316       p = rs->buf;
13317     }
13318   return 0;
13319 }
13320
13321 /* The "set/show range-stepping" show hook.  */
13322
13323 static void
13324 show_range_stepping (struct ui_file *file, int from_tty,
13325                      struct cmd_list_element *c,
13326                      const char *value)
13327 {
13328   fprintf_filtered (file,
13329                     _("Debugger's willingness to use range stepping "
13330                       "is %s.\n"), value);
13331 }
13332
13333 /* The "set/show range-stepping" set hook.  */
13334
13335 static void
13336 set_range_stepping (char *ignore_args, int from_tty,
13337                     struct cmd_list_element *c)
13338 {
13339   struct remote_state *rs = get_remote_state ();
13340
13341   /* Whene enabling, check whether range stepping is actually
13342      supported by the target, and warn if not.  */
13343   if (use_range_stepping)
13344     {
13345       if (rs->remote_desc != NULL)
13346         {
13347           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13348             remote_vcont_probe (rs);
13349
13350           if (packet_support (PACKET_vCont) == PACKET_ENABLE
13351               && rs->supports_vCont.r)
13352             return;
13353         }
13354
13355       warning (_("Range stepping is not supported by the current target"));
13356     }
13357 }
13358
13359 void
13360 _initialize_remote (void)
13361 {
13362   struct remote_state *rs;
13363   struct cmd_list_element *cmd;
13364   const char *cmd_name;
13365
13366   /* architecture specific data */
13367   remote_gdbarch_data_handle =
13368     gdbarch_data_register_post_init (init_remote_state);
13369   remote_g_packet_data_handle =
13370     gdbarch_data_register_pre_init (remote_g_packet_data_init);
13371
13372   remote_pspace_data
13373     = register_program_space_data_with_cleanup (NULL,
13374                                                 remote_pspace_data_cleanup);
13375
13376   /* Initialize the per-target state.  At the moment there is only one
13377      of these, not one per target.  Only one target is active at a
13378      time.  */
13379   remote_state = new_remote_state ();
13380
13381   init_remote_ops ();
13382   add_target (&remote_ops);
13383
13384   init_extended_remote_ops ();
13385   add_target (&extended_remote_ops);
13386
13387   /* Hook into new objfile notification.  */
13388   observer_attach_new_objfile (remote_new_objfile);
13389   /* We're no longer interested in notification events of an inferior
13390      when it exits.  */
13391   observer_attach_inferior_exit (discard_pending_stop_replies);
13392
13393   /* Set up signal handlers.  */
13394   async_sigint_remote_token =
13395     create_async_signal_handler (async_remote_interrupt, NULL);
13396   async_sigint_remote_twice_token =
13397     create_async_signal_handler (async_remote_interrupt_twice, NULL);
13398
13399 #if 0
13400   init_remote_threadtests ();
13401 #endif
13402
13403   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13404   /* set/show remote ...  */
13405
13406   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13407 Remote protocol specific variables\n\
13408 Configure various remote-protocol specific variables such as\n\
13409 the packets being used"),
13410                   &remote_set_cmdlist, "set remote ",
13411                   0 /* allow-unknown */, &setlist);
13412   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13413 Remote protocol specific variables\n\
13414 Configure various remote-protocol specific variables such as\n\
13415 the packets being used"),
13416                   &remote_show_cmdlist, "show remote ",
13417                   0 /* allow-unknown */, &showlist);
13418
13419   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13420 Compare section data on target to the exec file.\n\
13421 Argument is a single section name (default: all loaded sections).\n\
13422 To compare only read-only loaded sections, specify the -r option."),
13423            &cmdlist);
13424
13425   add_cmd ("packet", class_maintenance, packet_command, _("\
13426 Send an arbitrary packet to a remote target.\n\
13427    maintenance packet TEXT\n\
13428 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13429 this command sends the string TEXT to the inferior, and displays the\n\
13430 response packet.  GDB supplies the initial `$' character, and the\n\
13431 terminating `#' character and checksum."),
13432            &maintenancelist);
13433
13434   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13435 Set whether to send break if interrupted."), _("\
13436 Show whether to send break if interrupted."), _("\
13437 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13438                            set_remotebreak, show_remotebreak,
13439                            &setlist, &showlist);
13440   cmd_name = "remotebreak";
13441   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13442   deprecate_cmd (cmd, "set remote interrupt-sequence");
13443   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13444   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13445   deprecate_cmd (cmd, "show remote interrupt-sequence");
13446
13447   add_setshow_enum_cmd ("interrupt-sequence", class_support,
13448                         interrupt_sequence_modes, &interrupt_sequence_mode,
13449                         _("\
13450 Set interrupt sequence to remote target."), _("\
13451 Show interrupt sequence to remote target."), _("\
13452 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13453                         NULL, show_interrupt_sequence,
13454                         &remote_set_cmdlist,
13455                         &remote_show_cmdlist);
13456
13457   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13458                            &interrupt_on_connect, _("\
13459 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
13460 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
13461 If set, interrupt sequence is sent to remote target."),
13462                            NULL, NULL,
13463                            &remote_set_cmdlist, &remote_show_cmdlist);
13464
13465   /* Install commands for configuring memory read/write packets.  */
13466
13467   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13468 Set the maximum number of bytes per memory write packet (deprecated)."),
13469            &setlist);
13470   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13471 Show the maximum number of bytes per memory write packet (deprecated)."),
13472            &showlist);
13473   add_cmd ("memory-write-packet-size", no_class,
13474            set_memory_write_packet_size, _("\
13475 Set the maximum number of bytes per memory-write packet.\n\
13476 Specify the number of bytes in a packet or 0 (zero) for the\n\
13477 default packet size.  The actual limit is further reduced\n\
13478 dependent on the target.  Specify ``fixed'' to disable the\n\
13479 further restriction and ``limit'' to enable that restriction."),
13480            &remote_set_cmdlist);
13481   add_cmd ("memory-read-packet-size", no_class,
13482            set_memory_read_packet_size, _("\
13483 Set the maximum number of bytes per memory-read packet.\n\
13484 Specify the number of bytes in a packet or 0 (zero) for the\n\
13485 default packet size.  The actual limit is further reduced\n\
13486 dependent on the target.  Specify ``fixed'' to disable the\n\
13487 further restriction and ``limit'' to enable that restriction."),
13488            &remote_set_cmdlist);
13489   add_cmd ("memory-write-packet-size", no_class,
13490            show_memory_write_packet_size,
13491            _("Show the maximum number of bytes per memory-write packet."),
13492            &remote_show_cmdlist);
13493   add_cmd ("memory-read-packet-size", no_class,
13494            show_memory_read_packet_size,
13495            _("Show the maximum number of bytes per memory-read packet."),
13496            &remote_show_cmdlist);
13497
13498   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13499                             &remote_hw_watchpoint_limit, _("\
13500 Set the maximum number of target hardware watchpoints."), _("\
13501 Show the maximum number of target hardware watchpoints."), _("\
13502 Specify a negative limit for unlimited."),
13503                             NULL, NULL, /* FIXME: i18n: The maximum
13504                                            number of target hardware
13505                                            watchpoints is %s.  */
13506                             &remote_set_cmdlist, &remote_show_cmdlist);
13507   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13508                             &remote_hw_watchpoint_length_limit, _("\
13509 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13510 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13511 Specify a negative limit for unlimited."),
13512                             NULL, NULL, /* FIXME: i18n: The maximum
13513                                            length (in bytes) of a target
13514                                            hardware watchpoint is %s.  */
13515                             &remote_set_cmdlist, &remote_show_cmdlist);
13516   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13517                             &remote_hw_breakpoint_limit, _("\
13518 Set the maximum number of target hardware breakpoints."), _("\
13519 Show the maximum number of target hardware breakpoints."), _("\
13520 Specify a negative limit for unlimited."),
13521                             NULL, NULL, /* FIXME: i18n: The maximum
13522                                            number of target hardware
13523                                            breakpoints is %s.  */
13524                             &remote_set_cmdlist, &remote_show_cmdlist);
13525
13526   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13527                              &remote_address_size, _("\
13528 Set the maximum size of the address (in bits) in a memory packet."), _("\
13529 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13530                              NULL,
13531                              NULL, /* FIXME: i18n: */
13532                              &setlist, &showlist);
13533
13534   init_all_packet_configs ();
13535
13536   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13537                          "X", "binary-download", 1);
13538
13539   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13540                          "vCont", "verbose-resume", 0);
13541
13542   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13543                          "QPassSignals", "pass-signals", 0);
13544
13545   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13546                          "QProgramSignals", "program-signals", 0);
13547
13548   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13549                          "qSymbol", "symbol-lookup", 0);
13550
13551   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13552                          "P", "set-register", 1);
13553
13554   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13555                          "p", "fetch-register", 1);
13556
13557   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13558                          "Z0", "software-breakpoint", 0);
13559
13560   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13561                          "Z1", "hardware-breakpoint", 0);
13562
13563   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13564                          "Z2", "write-watchpoint", 0);
13565
13566   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13567                          "Z3", "read-watchpoint", 0);
13568
13569   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13570                          "Z4", "access-watchpoint", 0);
13571
13572   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13573                          "qXfer:auxv:read", "read-aux-vector", 0);
13574
13575   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13576                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
13577
13578   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13579                          "qXfer:features:read", "target-features", 0);
13580
13581   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13582                          "qXfer:libraries:read", "library-info", 0);
13583
13584   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13585                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13586
13587   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13588                          "qXfer:memory-map:read", "memory-map", 0);
13589
13590   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13591                          "qXfer:spu:read", "read-spu-object", 0);
13592
13593   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13594                          "qXfer:spu:write", "write-spu-object", 0);
13595
13596   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13597                         "qXfer:osdata:read", "osdata", 0);
13598
13599   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13600                          "qXfer:threads:read", "threads", 0);
13601
13602   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13603                          "qXfer:siginfo:read", "read-siginfo-object", 0);
13604
13605   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13606                          "qXfer:siginfo:write", "write-siginfo-object", 0);
13607
13608   add_packet_config_cmd
13609     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13610      "qXfer:traceframe-info:read", "traceframe-info", 0);
13611
13612   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13613                          "qXfer:uib:read", "unwind-info-block", 0);
13614
13615   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13616                          "qGetTLSAddr", "get-thread-local-storage-address",
13617                          0);
13618
13619   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13620                          "qGetTIBAddr", "get-thread-information-block-address",
13621                          0);
13622
13623   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13624                          "bc", "reverse-continue", 0);
13625
13626   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13627                          "bs", "reverse-step", 0);
13628
13629   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13630                          "qSupported", "supported-packets", 0);
13631
13632   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13633                          "qSearch:memory", "search-memory", 0);
13634
13635   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13636                          "qTStatus", "trace-status", 0);
13637
13638   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13639                          "vFile:setfs", "hostio-setfs", 0);
13640
13641   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13642                          "vFile:open", "hostio-open", 0);
13643
13644   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13645                          "vFile:pread", "hostio-pread", 0);
13646
13647   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13648                          "vFile:pwrite", "hostio-pwrite", 0);
13649
13650   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13651                          "vFile:close", "hostio-close", 0);
13652
13653   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13654                          "vFile:unlink", "hostio-unlink", 0);
13655
13656   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13657                          "vFile:readlink", "hostio-readlink", 0);
13658
13659   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13660                          "vFile:fstat", "hostio-fstat", 0);
13661
13662   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13663                          "vAttach", "attach", 0);
13664
13665   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13666                          "vRun", "run", 0);
13667
13668   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13669                          "QStartNoAckMode", "noack", 0);
13670
13671   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13672                          "vKill", "kill", 0);
13673
13674   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13675                          "qAttached", "query-attached", 0);
13676
13677   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13678                          "ConditionalTracepoints",
13679                          "conditional-tracepoints", 0);
13680
13681   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13682                          "ConditionalBreakpoints",
13683                          "conditional-breakpoints", 0);
13684
13685   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13686                          "BreakpointCommands",
13687                          "breakpoint-commands", 0);
13688
13689   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13690                          "FastTracepoints", "fast-tracepoints", 0);
13691
13692   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13693                          "TracepointSource", "TracepointSource", 0);
13694
13695   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13696                          "QAllow", "allow", 0);
13697
13698   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13699                          "StaticTracepoints", "static-tracepoints", 0);
13700
13701   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13702                          "InstallInTrace", "install-in-trace", 0);
13703
13704   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13705                          "qXfer:statictrace:read", "read-sdata-object", 0);
13706
13707   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13708                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13709
13710   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13711                          "QDisableRandomization", "disable-randomization", 0);
13712
13713   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13714                          "QAgent", "agent", 0);
13715
13716   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13717                          "QTBuffer:size", "trace-buffer-size", 0);
13718
13719   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13720        "Qbtrace:off", "disable-btrace", 0);
13721
13722   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13723        "Qbtrace:bts", "enable-btrace-bts", 0);
13724
13725   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13726        "Qbtrace:pt", "enable-btrace-pt", 0);
13727
13728   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13729        "qXfer:btrace", "read-btrace", 0);
13730
13731   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13732        "qXfer:btrace-conf", "read-btrace-conf", 0);
13733
13734   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13735        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13736
13737   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13738        "multiprocess-feature", "multiprocess-feature", 0);
13739
13740   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13741                          "swbreak-feature", "swbreak-feature", 0);
13742
13743   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13744                          "hwbreak-feature", "hwbreak-feature", 0);
13745
13746   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13747                          "fork-event-feature", "fork-event-feature", 0);
13748
13749   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13750                          "vfork-event-feature", "vfork-event-feature", 0);
13751
13752   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13753        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13754
13755   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13756                          "vContSupported", "verbose-resume-supported", 0);
13757
13758   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13759                          "exec-event-feature", "exec-event-feature", 0);
13760
13761   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13762                          "vCtrlC", "ctrl-c", 0);
13763
13764   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13765                          "QThreadEvents", "thread-events", 0);
13766
13767   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13768                          "N stop reply", "no-resumed-stop-reply", 0);
13769
13770   /* Assert that we've registered "set remote foo-packet" commands
13771      for all packet configs.  */
13772   {
13773     int i;
13774
13775     for (i = 0; i < PACKET_MAX; i++)
13776       {
13777         /* Ideally all configs would have a command associated.  Some
13778            still don't though.  */
13779         int excepted;
13780
13781         switch (i)
13782           {
13783           case PACKET_QNonStop:
13784           case PACKET_EnableDisableTracepoints_feature:
13785           case PACKET_tracenz_feature:
13786           case PACKET_DisconnectedTracing_feature:
13787           case PACKET_augmented_libraries_svr4_read_feature:
13788           case PACKET_qCRC:
13789             /* Additions to this list need to be well justified:
13790                pre-existing packets are OK; new packets are not.  */
13791             excepted = 1;
13792             break;
13793           default:
13794             excepted = 0;
13795             break;
13796           }
13797
13798         /* This catches both forgetting to add a config command, and
13799            forgetting to remove a packet from the exception list.  */
13800         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13801       }
13802   }
13803
13804   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
13805      Z sub-packet has its own set and show commands, but users may
13806      have sets to this variable in their .gdbinit files (or in their
13807      documentation).  */
13808   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13809                                 &remote_Z_packet_detect, _("\
13810 Set use of remote protocol `Z' packets"), _("\
13811 Show use of remote protocol `Z' packets "), _("\
13812 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13813 packets."),
13814                                 set_remote_protocol_Z_packet_cmd,
13815                                 show_remote_protocol_Z_packet_cmd,
13816                                 /* FIXME: i18n: Use of remote protocol
13817                                    `Z' packets is %s.  */
13818                                 &remote_set_cmdlist, &remote_show_cmdlist);
13819
13820   add_prefix_cmd ("remote", class_files, remote_command, _("\
13821 Manipulate files on the remote system\n\
13822 Transfer files to and from the remote target system."),
13823                   &remote_cmdlist, "remote ",
13824                   0 /* allow-unknown */, &cmdlist);
13825
13826   add_cmd ("put", class_files, remote_put_command,
13827            _("Copy a local file to the remote system."),
13828            &remote_cmdlist);
13829
13830   add_cmd ("get", class_files, remote_get_command,
13831            _("Copy a remote file to the local system."),
13832            &remote_cmdlist);
13833
13834   add_cmd ("delete", class_files, remote_delete_command,
13835            _("Delete a remote file."),
13836            &remote_cmdlist);
13837
13838   add_setshow_string_noescape_cmd ("exec-file", class_files,
13839                                    &remote_exec_file_var, _("\
13840 Set the remote pathname for \"run\""), _("\
13841 Show the remote pathname for \"run\""), NULL,
13842                                    set_remote_exec_file,
13843                                    show_remote_exec_file,
13844                                    &remote_set_cmdlist,
13845                                    &remote_show_cmdlist);
13846
13847   add_setshow_boolean_cmd ("range-stepping", class_run,
13848                            &use_range_stepping, _("\
13849 Enable or disable range stepping."), _("\
13850 Show whether target-assisted range stepping is enabled."), _("\
13851 If on, and the target supports it, when stepping a source line, GDB\n\
13852 tells the target to step the corresponding range of addresses itself instead\n\
13853 of issuing multiple single-steps.  This speeds up source level\n\
13854 stepping.  If off, GDB always issues single-steps, even if range\n\
13855 stepping is supported by the target.  The default is on."),
13856                            set_range_stepping,
13857                            show_range_stepping,
13858                            &setlist,
13859                            &showlist);
13860
13861   /* Eventually initialize fileio.  See fileio.c */
13862   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13863
13864   /* Take advantage of the fact that the TID field is not used, to tag
13865      special ptids with it set to != 0.  */
13866   magic_null_ptid = ptid_build (42000, -1, 1);
13867   not_sent_ptid = ptid_build (42000, -2, 1);
13868   any_thread_ptid = ptid_build (42000, 0, 1);
13869
13870   target_buf_size = 2048;
13871   target_buf = (char *) xmalloc (target_buf_size);
13872 }
13873