Decouple target_interrupt from all-stop/non-stop modes
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2016 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* See the GDB User Guide for details of the GDB remote protocol.  */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 /*#include "terminal.h" */
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observer.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "filestuff.h"
46 #include "rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdb_sys_time.h"
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "agent.h"
72 #include "btrace.h"
73
74 /* Temp hacks for tracepoint encoding migration.  */
75 static char *target_buf;
76 static long target_buf_size;
77
78 /* Per-program-space data key.  */
79 static const struct program_space_data *remote_pspace_data;
80
81 /* The variable registered as the control variable used by the
82    remote exec-file commands.  While the remote exec-file setting is
83    per-program-space, the set/show machinery uses this as the 
84    location of the remote exec-file value.  */
85 static char *remote_exec_file_var;
86
87 /* The size to align memory write packets, when practical.  The protocol
88    does not guarantee any alignment, and gdb will generate short
89    writes and unaligned writes, but even as a best-effort attempt this
90    can improve bulk transfers.  For instance, if a write is misaligned
91    relative to the target's data bus, the stub may need to make an extra
92    round trip fetching data from the target.  This doesn't make a
93    huge difference, but it's easy to do, so we try to be helpful.
94
95    The alignment chosen is arbitrary; usually data bus width is
96    important here, not the possibly larger cache line size.  */
97 enum { REMOTE_ALIGN_WRITES = 16 };
98
99 /* Prototypes for local functions.  */
100 static void async_cleanup_sigint_signal_handler (void *dummy);
101 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
102 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
103                                  int forever, int *is_notif);
104
105 static void async_handle_remote_sigint (int);
106 static void async_handle_remote_sigint_twice (int);
107
108 static void remote_files_info (struct target_ops *ignore);
109
110 static void remote_prepare_to_store (struct target_ops *self,
111                                      struct regcache *regcache);
112
113 static void remote_open_1 (const char *, int, struct target_ops *,
114                            int extended_p);
115
116 static void remote_close (struct target_ops *self);
117
118 struct remote_state;
119
120 static int remote_vkill (int pid, struct remote_state *rs);
121
122 static void remote_kill_k (void);
123
124 static void remote_mourn (struct target_ops *ops);
125
126 static void extended_remote_restart (void);
127
128 static void remote_send (char **buf, long *sizeof_buf_p);
129
130 static int readchar (int timeout);
131
132 static void remote_serial_write (const char *str, int len);
133
134 static void remote_kill (struct target_ops *ops);
135
136 static int remote_can_async_p (struct target_ops *);
137
138 static int remote_is_async_p (struct target_ops *);
139
140 static void remote_async (struct target_ops *ops, int enable);
141
142 static void remote_thread_events (struct target_ops *ops, int enable);
143
144 static void sync_remote_interrupt_twice (int signo);
145
146 static void interrupt_query (void);
147
148 static void set_general_thread (struct ptid ptid);
149 static void set_continue_thread (struct ptid ptid);
150
151 static void get_offsets (void);
152
153 static void skip_frame (void);
154
155 static long read_frame (char **buf_p, long *sizeof_buf);
156
157 static int hexnumlen (ULONGEST num);
158
159 static void init_remote_ops (void);
160
161 static void init_extended_remote_ops (void);
162
163 static void remote_stop (struct target_ops *self, ptid_t);
164
165 static int stubhex (int ch);
166
167 static int hexnumstr (char *, ULONGEST);
168
169 static int hexnumnstr (char *, ULONGEST, int);
170
171 static CORE_ADDR remote_address_masked (CORE_ADDR);
172
173 static void print_packet (const char *);
174
175 static void compare_sections_command (char *, int);
176
177 static void packet_command (char *, int);
178
179 static int stub_unpack_int (char *buff, int fieldlength);
180
181 static ptid_t remote_current_thread (ptid_t oldptid);
182
183 static int putpkt_binary (const char *buf, int cnt);
184
185 static void check_binary_download (CORE_ADDR addr);
186
187 struct packet_config;
188
189 static void show_packet_config_cmd (struct packet_config *config);
190
191 static void show_remote_protocol_packet_cmd (struct ui_file *file,
192                                              int from_tty,
193                                              struct cmd_list_element *c,
194                                              const char *value);
195
196 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
197 static ptid_t read_ptid (char *buf, char **obuf);
198
199 static void remote_set_permissions (struct target_ops *self);
200
201 static int remote_get_trace_status (struct target_ops *self,
202                                     struct trace_status *ts);
203
204 static int remote_upload_tracepoints (struct target_ops *self,
205                                       struct uploaded_tp **utpp);
206
207 static int remote_upload_trace_state_variables (struct target_ops *self,
208                                                 struct uploaded_tsv **utsvp);
209   
210 static void remote_query_supported (void);
211
212 static void remote_check_symbols (void);
213
214 void _initialize_remote (void);
215
216 struct stop_reply;
217 static void stop_reply_xfree (struct stop_reply *);
218 static void remote_parse_stop_reply (char *, struct stop_reply *);
219 static void push_stop_reply (struct stop_reply *);
220 static void discard_pending_stop_replies_in_queue (struct remote_state *);
221 static int peek_stop_reply (ptid_t ptid);
222
223 struct threads_listing_context;
224 static void remove_new_fork_children (struct threads_listing_context *);
225
226 static void remote_async_inferior_event_handler (gdb_client_data);
227
228 static void remote_terminal_ours (struct target_ops *self);
229
230 static int remote_read_description_p (struct target_ops *target);
231
232 static void remote_console_output (char *msg);
233
234 static int remote_supports_cond_breakpoints (struct target_ops *self);
235
236 static int remote_can_run_breakpoint_commands (struct target_ops *self);
237
238 static void remote_btrace_reset (void);
239
240 static int stop_reply_queue_length (void);
241
242 static void readahead_cache_invalidate (void);
243
244 /* For "remote".  */
245
246 static struct cmd_list_element *remote_cmdlist;
247
248 /* For "set remote" and "show remote".  */
249
250 static struct cmd_list_element *remote_set_cmdlist;
251 static struct cmd_list_element *remote_show_cmdlist;
252
253 /* Stub vCont actions support.
254
255    Each field is a boolean flag indicating whether the stub reports
256    support for the corresponding action.  */
257
258 struct vCont_action_support
259 {
260   /* vCont;t */
261   int t;
262
263   /* vCont;r */
264   int r;
265
266   /* vCont;s */
267   int s;
268
269   /* vCont;S */
270   int S;
271 };
272
273 /* Controls whether GDB is willing to use range stepping.  */
274
275 static int use_range_stepping = 1;
276
277 #define OPAQUETHREADBYTES 8
278
279 /* a 64 bit opaque identifier */
280 typedef unsigned char threadref[OPAQUETHREADBYTES];
281
282 /* About this many threadisds fit in a packet.  */
283
284 #define MAXTHREADLISTRESULTS 32
285
286 /* Data for the vFile:pread readahead cache.  */
287
288 struct readahead_cache
289 {
290   /* The file descriptor for the file that is being cached.  -1 if the
291      cache is invalid.  */
292   int fd;
293
294   /* The offset into the file that the cache buffer corresponds
295      to.  */
296   ULONGEST offset;
297
298   /* The buffer holding the cache contents.  */
299   gdb_byte *buf;
300   /* The buffer's size.  We try to read as much as fits into a packet
301      at a time.  */
302   size_t bufsize;
303
304   /* Cache hit and miss counters.  */
305   ULONGEST hit_count;
306   ULONGEST miss_count;
307 };
308
309 /* Description of the remote protocol state for the currently
310    connected target.  This is per-target state, and independent of the
311    selected architecture.  */
312
313 struct remote_state
314 {
315   /* A buffer to use for incoming packets, and its current size.  The
316      buffer is grown dynamically for larger incoming packets.
317      Outgoing packets may also be constructed in this buffer.
318      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
320      packets.  */
321   char *buf;
322   long buf_size;
323
324   /* True if we're going through initial connection setup (finding out
325      about the remote side's threads, relocating symbols, etc.).  */
326   int starting_up;
327
328   /* If we negotiated packet size explicitly (and thus can bypass
329      heuristics for the largest packet size that will not overflow
330      a buffer in the stub), this will be set to that packet size.
331      Otherwise zero, meaning to use the guessed size.  */
332   long explicit_packet_size;
333
334   /* remote_wait is normally called when the target is running and
335      waits for a stop reply packet.  But sometimes we need to call it
336      when the target is already stopped.  We can send a "?" packet
337      and have remote_wait read the response.  Or, if we already have
338      the response, we can stash it in BUF and tell remote_wait to
339      skip calling getpkt.  This flag is set when BUF contains a
340      stop reply packet and the target is not waiting.  */
341   int cached_wait_status;
342
343   /* True, if in no ack mode.  That is, neither GDB nor the stub will
344      expect acks from each other.  The connection is assumed to be
345      reliable.  */
346   int noack_mode;
347
348   /* True if we're connected in extended remote mode.  */
349   int extended;
350
351   /* True if we resumed the target and we're waiting for the target to
352      stop.  In the mean time, we can't start another command/query.
353      The remote server wouldn't be ready to process it, so we'd
354      timeout waiting for a reply that would never come and eventually
355      we'd close the connection.  This can happen in asynchronous mode
356      because we allow GDB commands while the target is running.  */
357   int waiting_for_stop_reply;
358
359   /* The status of the stub support for the various vCont actions.  */
360   struct vCont_action_support supports_vCont;
361
362   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363      responded to that.  */
364   int ctrlc_pending_p;
365
366   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
367      remote_open knows that we don't have a file open when the program
368      starts.  */
369   struct serial *remote_desc;
370
371   /* These are the threads which we last sent to the remote system.  The
372      TID member will be -1 for all or -2 for not sent yet.  */
373   ptid_t general_thread;
374   ptid_t continue_thread;
375
376   /* This is the traceframe which we last selected on the remote system.
377      It will be -1 if no traceframe is selected.  */
378   int remote_traceframe_number;
379
380   char *last_pass_packet;
381
382   /* The last QProgramSignals packet sent to the target.  We bypass
383      sending a new program signals list down to the target if the new
384      packet is exactly the same as the last we sent.  IOW, we only let
385      the target know about program signals list changes.  */
386   char *last_program_signals_packet;
387
388   enum gdb_signal last_sent_signal;
389
390   int last_sent_step;
391
392   char *finished_object;
393   char *finished_annex;
394   ULONGEST finished_offset;
395
396   /* Should we try the 'ThreadInfo' query packet?
397
398      This variable (NOT available to the user: auto-detect only!)
399      determines whether GDB will use the new, simpler "ThreadInfo"
400      query or the older, more complex syntax for thread queries.
401      This is an auto-detect variable (set to true at each connect,
402      and set to false when the target fails to recognize it).  */
403   int use_threadinfo_query;
404   int use_threadextra_query;
405
406   threadref echo_nextthread;
407   threadref nextthread;
408   threadref resultthreadlist[MAXTHREADLISTRESULTS];
409
410   /* The state of remote notification.  */
411   struct remote_notif_state *notif_state;
412
413   /* The branch trace configuration.  */
414   struct btrace_config btrace_config;
415
416   /* The argument to the last "vFile:setfs:" packet we sent, used
417      to avoid sending repeated unnecessary "vFile:setfs:" packets.
418      Initialized to -1 to indicate that no "vFile:setfs:" packet
419      has yet been sent.  */
420   int fs_pid;
421
422   /* A readahead cache for vFile:pread.  Often, reading a binary
423      involves a sequence of small reads.  E.g., when parsing an ELF
424      file.  A readahead cache helps mostly the case of remote
425      debugging on a connection with higher latency, due to the
426      request/reply nature of the RSP.  We only cache data for a single
427      file descriptor at a time.  */
428   struct readahead_cache readahead_cache;
429 };
430
431 /* Private data that we'll store in (struct thread_info)->private.  */
432 struct private_thread_info
433 {
434   char *extra;
435   char *name;
436   int core;
437
438   /* Whether the target stopped for a breakpoint/watchpoint.  */
439   enum target_stop_reason stop_reason;
440
441   /* This is set to the data address of the access causing the target
442      to stop for a watchpoint.  */
443   CORE_ADDR watch_data_address;
444 };
445
446 static void
447 free_private_thread_info (struct private_thread_info *info)
448 {
449   xfree (info->extra);
450   xfree (info->name);
451   xfree (info);
452 }
453
454 /* This data could be associated with a target, but we do not always
455    have access to the current target when we need it, so for now it is
456    static.  This will be fine for as long as only one target is in use
457    at a time.  */
458 static struct remote_state *remote_state;
459
460 static struct remote_state *
461 get_remote_state_raw (void)
462 {
463   return remote_state;
464 }
465
466 /* Allocate a new struct remote_state with xmalloc, initialize it, and
467    return it.  */
468
469 static struct remote_state *
470 new_remote_state (void)
471 {
472   struct remote_state *result = XCNEW (struct remote_state);
473
474   /* The default buffer size is unimportant; it will be expanded
475      whenever a larger buffer is needed. */
476   result->buf_size = 400;
477   result->buf = (char *) xmalloc (result->buf_size);
478   result->remote_traceframe_number = -1;
479   result->last_sent_signal = GDB_SIGNAL_0;
480   result->fs_pid = -1;
481
482   return result;
483 }
484
485 /* Description of the remote protocol for a given architecture.  */
486
487 struct packet_reg
488 {
489   long offset; /* Offset into G packet.  */
490   long regnum; /* GDB's internal register number.  */
491   LONGEST pnum; /* Remote protocol register number.  */
492   int in_g_packet; /* Always part of G packet.  */
493   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
494      at present.  */
495   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
496      at present.  */
497 };
498
499 struct remote_arch_state
500 {
501   /* Description of the remote protocol registers.  */
502   long sizeof_g_packet;
503
504   /* Description of the remote protocol registers indexed by REGNUM
505      (making an array gdbarch_num_regs in size).  */
506   struct packet_reg *regs;
507
508   /* This is the size (in chars) of the first response to the ``g''
509      packet.  It is used as a heuristic when determining the maximum
510      size of memory-read and memory-write packets.  A target will
511      typically only reserve a buffer large enough to hold the ``g''
512      packet.  The size does not include packet overhead (headers and
513      trailers).  */
514   long actual_register_packet_size;
515
516   /* This is the maximum size (in chars) of a non read/write packet.
517      It is also used as a cap on the size of read/write packets.  */
518   long remote_packet_size;
519 };
520
521 /* Utility: generate error from an incoming stub packet.  */
522 static void
523 trace_error (char *buf)
524 {
525   if (*buf++ != 'E')
526     return;                     /* not an error msg */
527   switch (*buf)
528     {
529     case '1':                   /* malformed packet error */
530       if (*++buf == '0')        /*   general case: */
531         error (_("remote.c: error in outgoing packet."));
532       else
533         error (_("remote.c: error in outgoing packet at field #%ld."),
534                strtol (buf, NULL, 16));
535     default:
536       error (_("Target returns error code '%s'."), buf);
537     }
538 }
539
540 /* Utility: wait for reply from stub, while accepting "O" packets.  */
541 static char *
542 remote_get_noisy_reply (char **buf_p,
543                         long *sizeof_buf)
544 {
545   do                            /* Loop on reply from remote stub.  */
546     {
547       char *buf;
548
549       QUIT;                     /* Allow user to bail out with ^C.  */
550       getpkt (buf_p, sizeof_buf, 0);
551       buf = *buf_p;
552       if (buf[0] == 'E')
553         trace_error (buf);
554       else if (startswith (buf, "qRelocInsn:"))
555         {
556           ULONGEST ul;
557           CORE_ADDR from, to, org_to;
558           char *p, *pp;
559           int adjusted_size = 0;
560           int relocated = 0;
561
562           p = buf + strlen ("qRelocInsn:");
563           pp = unpack_varlen_hex (p, &ul);
564           if (*pp != ';')
565             error (_("invalid qRelocInsn packet: %s"), buf);
566           from = ul;
567
568           p = pp + 1;
569           unpack_varlen_hex (p, &ul);
570           to = ul;
571
572           org_to = to;
573
574           TRY
575             {
576               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
577               relocated = 1;
578             }
579           CATCH (ex, RETURN_MASK_ALL)
580             {
581               if (ex.error == MEMORY_ERROR)
582                 {
583                   /* Propagate memory errors silently back to the
584                      target.  The stub may have limited the range of
585                      addresses we can write to, for example.  */
586                 }
587               else
588                 {
589                   /* Something unexpectedly bad happened.  Be verbose
590                      so we can tell what, and propagate the error back
591                      to the stub, so it doesn't get stuck waiting for
592                      a response.  */
593                   exception_fprintf (gdb_stderr, ex,
594                                      _("warning: relocating instruction: "));
595                 }
596               putpkt ("E01");
597             }
598           END_CATCH
599
600           if (relocated)
601             {
602               adjusted_size = to - org_to;
603
604               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
605               putpkt (buf);
606             }
607         }
608       else if (buf[0] == 'O' && buf[1] != 'K')
609         remote_console_output (buf + 1);        /* 'O' message from stub */
610       else
611         return buf;             /* Here's the actual reply.  */
612     }
613   while (1);
614 }
615
616 /* Handle for retreving the remote protocol data from gdbarch.  */
617 static struct gdbarch_data *remote_gdbarch_data_handle;
618
619 static struct remote_arch_state *
620 get_remote_arch_state (void)
621 {
622   gdb_assert (target_gdbarch () != NULL);
623   return ((struct remote_arch_state *)
624           gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
625 }
626
627 /* Fetch the global remote target state.  */
628
629 static struct remote_state *
630 get_remote_state (void)
631 {
632   /* Make sure that the remote architecture state has been
633      initialized, because doing so might reallocate rs->buf.  Any
634      function which calls getpkt also needs to be mindful of changes
635      to rs->buf, but this call limits the number of places which run
636      into trouble.  */
637   get_remote_arch_state ();
638
639   return get_remote_state_raw ();
640 }
641
642 /* Cleanup routine for the remote module's pspace data.  */
643
644 static void
645 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
646 {
647   char *remote_exec_file = (char *) arg;
648
649   xfree (remote_exec_file);
650 }
651
652 /* Fetch the remote exec-file from the current program space.  */
653
654 static const char *
655 get_remote_exec_file (void)
656 {
657   char *remote_exec_file;
658
659   remote_exec_file
660     = (char *) program_space_data (current_program_space,
661                                    remote_pspace_data);
662   if (remote_exec_file == NULL)
663     return "";
664
665   return remote_exec_file;
666 }
667
668 /* Set the remote exec file for PSPACE.  */
669
670 static void
671 set_pspace_remote_exec_file (struct program_space *pspace,
672                         char *remote_exec_file)
673 {
674   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
675
676   xfree (old_file);
677   set_program_space_data (pspace, remote_pspace_data,
678                           xstrdup (remote_exec_file));
679 }
680
681 /* The "set/show remote exec-file" set command hook.  */
682
683 static void
684 set_remote_exec_file (char *ignored, int from_tty,
685                       struct cmd_list_element *c)
686 {
687   gdb_assert (remote_exec_file_var != NULL);
688   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
689 }
690
691 /* The "set/show remote exec-file" show command hook.  */
692
693 static void
694 show_remote_exec_file (struct ui_file *file, int from_tty,
695                        struct cmd_list_element *cmd, const char *value)
696 {
697   fprintf_filtered (file, "%s\n", remote_exec_file_var);
698 }
699
700 static int
701 compare_pnums (const void *lhs_, const void *rhs_)
702 {
703   const struct packet_reg * const *lhs
704     = (const struct packet_reg * const *) lhs_;
705   const struct packet_reg * const *rhs
706     = (const struct packet_reg * const *) rhs_;
707
708   if ((*lhs)->pnum < (*rhs)->pnum)
709     return -1;
710   else if ((*lhs)->pnum == (*rhs)->pnum)
711     return 0;
712   else
713     return 1;
714 }
715
716 static int
717 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
718 {
719   int regnum, num_remote_regs, offset;
720   struct packet_reg **remote_regs;
721
722   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
723     {
724       struct packet_reg *r = &regs[regnum];
725
726       if (register_size (gdbarch, regnum) == 0)
727         /* Do not try to fetch zero-sized (placeholder) registers.  */
728         r->pnum = -1;
729       else
730         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
731
732       r->regnum = regnum;
733     }
734
735   /* Define the g/G packet format as the contents of each register
736      with a remote protocol number, in order of ascending protocol
737      number.  */
738
739   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
740   for (num_remote_regs = 0, regnum = 0;
741        regnum < gdbarch_num_regs (gdbarch);
742        regnum++)
743     if (regs[regnum].pnum != -1)
744       remote_regs[num_remote_regs++] = &regs[regnum];
745
746   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
747          compare_pnums);
748
749   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
750     {
751       remote_regs[regnum]->in_g_packet = 1;
752       remote_regs[regnum]->offset = offset;
753       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
754     }
755
756   return offset;
757 }
758
759 /* Given the architecture described by GDBARCH, return the remote
760    protocol register's number and the register's offset in the g/G
761    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
762    If the target does not have a mapping for REGNUM, return false,
763    otherwise, return true.  */
764
765 int
766 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
767                                    int *pnum, int *poffset)
768 {
769   struct packet_reg *regs;
770   struct cleanup *old_chain;
771
772   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
773
774   regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
775   old_chain = make_cleanup (xfree, regs);
776
777   map_regcache_remote_table (gdbarch, regs);
778
779   *pnum = regs[regnum].pnum;
780   *poffset = regs[regnum].offset;
781
782   do_cleanups (old_chain);
783
784   return *pnum != -1;
785 }
786
787 static void *
788 init_remote_state (struct gdbarch *gdbarch)
789 {
790   struct remote_state *rs = get_remote_state_raw ();
791   struct remote_arch_state *rsa;
792
793   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
794
795   /* Use the architecture to build a regnum<->pnum table, which will be
796      1:1 unless a feature set specifies otherwise.  */
797   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
798                                       gdbarch_num_regs (gdbarch),
799                                       struct packet_reg);
800
801   /* Record the maximum possible size of the g packet - it may turn out
802      to be smaller.  */
803   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
804
805   /* Default maximum number of characters in a packet body.  Many
806      remote stubs have a hardwired buffer size of 400 bytes
807      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
808      as the maximum packet-size to ensure that the packet and an extra
809      NUL character can always fit in the buffer.  This stops GDB
810      trashing stubs that try to squeeze an extra NUL into what is
811      already a full buffer (As of 1999-12-04 that was most stubs).  */
812   rsa->remote_packet_size = 400 - 1;
813
814   /* This one is filled in when a ``g'' packet is received.  */
815   rsa->actual_register_packet_size = 0;
816
817   /* Should rsa->sizeof_g_packet needs more space than the
818      default, adjust the size accordingly.  Remember that each byte is
819      encoded as two characters.  32 is the overhead for the packet
820      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
821      (``$NN:G...#NN'') is a better guess, the below has been padded a
822      little.  */
823   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
824     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
825
826   /* Make sure that the packet buffer is plenty big enough for
827      this architecture.  */
828   if (rs->buf_size < rsa->remote_packet_size)
829     {
830       rs->buf_size = 2 * rsa->remote_packet_size;
831       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
832     }
833
834   return rsa;
835 }
836
837 /* Return the current allowed size of a remote packet.  This is
838    inferred from the current architecture, and should be used to
839    limit the length of outgoing packets.  */
840 static long
841 get_remote_packet_size (void)
842 {
843   struct remote_state *rs = get_remote_state ();
844   struct remote_arch_state *rsa = get_remote_arch_state ();
845
846   if (rs->explicit_packet_size)
847     return rs->explicit_packet_size;
848
849   return rsa->remote_packet_size;
850 }
851
852 static struct packet_reg *
853 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
854 {
855   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
856     return NULL;
857   else
858     {
859       struct packet_reg *r = &rsa->regs[regnum];
860
861       gdb_assert (r->regnum == regnum);
862       return r;
863     }
864 }
865
866 static struct packet_reg *
867 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
868 {
869   int i;
870
871   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
872     {
873       struct packet_reg *r = &rsa->regs[i];
874
875       if (r->pnum == pnum)
876         return r;
877     }
878   return NULL;
879 }
880
881 static struct target_ops remote_ops;
882
883 static struct target_ops extended_remote_ops;
884
885 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
886    ``forever'' still use the normal timeout mechanism.  This is
887    currently used by the ASYNC code to guarentee that target reads
888    during the initial connect always time-out.  Once getpkt has been
889    modified to return a timeout indication and, in turn
890    remote_wait()/wait_for_inferior() have gained a timeout parameter
891    this can go away.  */
892 static int wait_forever_enabled_p = 1;
893
894 /* Allow the user to specify what sequence to send to the remote
895    when he requests a program interruption: Although ^C is usually
896    what remote systems expect (this is the default, here), it is
897    sometimes preferable to send a break.  On other systems such
898    as the Linux kernel, a break followed by g, which is Magic SysRq g
899    is required in order to interrupt the execution.  */
900 const char interrupt_sequence_control_c[] = "Ctrl-C";
901 const char interrupt_sequence_break[] = "BREAK";
902 const char interrupt_sequence_break_g[] = "BREAK-g";
903 static const char *const interrupt_sequence_modes[] =
904   {
905     interrupt_sequence_control_c,
906     interrupt_sequence_break,
907     interrupt_sequence_break_g,
908     NULL
909   };
910 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
911
912 static void
913 show_interrupt_sequence (struct ui_file *file, int from_tty,
914                          struct cmd_list_element *c,
915                          const char *value)
916 {
917   if (interrupt_sequence_mode == interrupt_sequence_control_c)
918     fprintf_filtered (file,
919                       _("Send the ASCII ETX character (Ctrl-c) "
920                         "to the remote target to interrupt the "
921                         "execution of the program.\n"));
922   else if (interrupt_sequence_mode == interrupt_sequence_break)
923     fprintf_filtered (file,
924                       _("send a break signal to the remote target "
925                         "to interrupt the execution of the program.\n"));
926   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
927     fprintf_filtered (file,
928                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
929                         "the remote target to interrupt the execution "
930                         "of Linux kernel.\n"));
931   else
932     internal_error (__FILE__, __LINE__,
933                     _("Invalid value for interrupt_sequence_mode: %s."),
934                     interrupt_sequence_mode);
935 }
936
937 /* This boolean variable specifies whether interrupt_sequence is sent
938    to the remote target when gdb connects to it.
939    This is mostly needed when you debug the Linux kernel: The Linux kernel
940    expects BREAK g which is Magic SysRq g for connecting gdb.  */
941 static int interrupt_on_connect = 0;
942
943 /* This variable is used to implement the "set/show remotebreak" commands.
944    Since these commands are now deprecated in favor of "set/show remote
945    interrupt-sequence", it no longer has any effect on the code.  */
946 static int remote_break;
947
948 static void
949 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
950 {
951   if (remote_break)
952     interrupt_sequence_mode = interrupt_sequence_break;
953   else
954     interrupt_sequence_mode = interrupt_sequence_control_c;
955 }
956
957 static void
958 show_remotebreak (struct ui_file *file, int from_tty,
959                   struct cmd_list_element *c,
960                   const char *value)
961 {
962 }
963
964 /* This variable sets the number of bits in an address that are to be
965    sent in a memory ("M" or "m") packet.  Normally, after stripping
966    leading zeros, the entire address would be sent.  This variable
967    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
968    initial implementation of remote.c restricted the address sent in
969    memory packets to ``host::sizeof long'' bytes - (typically 32
970    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
971    address was never sent.  Since fixing this bug may cause a break in
972    some remote targets this variable is principly provided to
973    facilitate backward compatibility.  */
974
975 static unsigned int remote_address_size;
976
977 /* Temporary to track who currently owns the terminal.  See
978    remote_terminal_* for more details.  */
979
980 static int remote_async_terminal_ours_p;
981
982 \f
983 /* User configurable variables for the number of characters in a
984    memory read/write packet.  MIN (rsa->remote_packet_size,
985    rsa->sizeof_g_packet) is the default.  Some targets need smaller
986    values (fifo overruns, et.al.) and some users need larger values
987    (speed up transfers).  The variables ``preferred_*'' (the user
988    request), ``current_*'' (what was actually set) and ``forced_*''
989    (Positive - a soft limit, negative - a hard limit).  */
990
991 struct memory_packet_config
992 {
993   char *name;
994   long size;
995   int fixed_p;
996 };
997
998 /* The default max memory-write-packet-size.  The 16k is historical.
999    (It came from older GDB's using alloca for buffers and the
1000    knowledge (folklore?) that some hosts don't cope very well with
1001    large alloca calls.)  */
1002 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1003
1004 /* The minimum remote packet size for memory transfers.  Ensures we
1005    can write at least one byte.  */
1006 #define MIN_MEMORY_PACKET_SIZE 20
1007
1008 /* Compute the current size of a read/write packet.  Since this makes
1009    use of ``actual_register_packet_size'' the computation is dynamic.  */
1010
1011 static long
1012 get_memory_packet_size (struct memory_packet_config *config)
1013 {
1014   struct remote_state *rs = get_remote_state ();
1015   struct remote_arch_state *rsa = get_remote_arch_state ();
1016
1017   long what_they_get;
1018   if (config->fixed_p)
1019     {
1020       if (config->size <= 0)
1021         what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1022       else
1023         what_they_get = config->size;
1024     }
1025   else
1026     {
1027       what_they_get = get_remote_packet_size ();
1028       /* Limit the packet to the size specified by the user.  */
1029       if (config->size > 0
1030           && what_they_get > config->size)
1031         what_they_get = config->size;
1032
1033       /* Limit it to the size of the targets ``g'' response unless we have
1034          permission from the stub to use a larger packet size.  */
1035       if (rs->explicit_packet_size == 0
1036           && rsa->actual_register_packet_size > 0
1037           && what_they_get > rsa->actual_register_packet_size)
1038         what_they_get = rsa->actual_register_packet_size;
1039     }
1040   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1041     what_they_get = MIN_MEMORY_PACKET_SIZE;
1042
1043   /* Make sure there is room in the global buffer for this packet
1044      (including its trailing NUL byte).  */
1045   if (rs->buf_size < what_they_get + 1)
1046     {
1047       rs->buf_size = 2 * what_they_get;
1048       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1049     }
1050
1051   return what_they_get;
1052 }
1053
1054 /* Update the size of a read/write packet.  If they user wants
1055    something really big then do a sanity check.  */
1056
1057 static void
1058 set_memory_packet_size (char *args, struct memory_packet_config *config)
1059 {
1060   int fixed_p = config->fixed_p;
1061   long size = config->size;
1062
1063   if (args == NULL)
1064     error (_("Argument required (integer, `fixed' or `limited')."));
1065   else if (strcmp (args, "hard") == 0
1066       || strcmp (args, "fixed") == 0)
1067     fixed_p = 1;
1068   else if (strcmp (args, "soft") == 0
1069            || strcmp (args, "limit") == 0)
1070     fixed_p = 0;
1071   else
1072     {
1073       char *end;
1074
1075       size = strtoul (args, &end, 0);
1076       if (args == end)
1077         error (_("Invalid %s (bad syntax)."), config->name);
1078
1079       /* Instead of explicitly capping the size of a packet to or
1080          disallowing it, the user is allowed to set the size to
1081          something arbitrarily large.  */
1082     }
1083
1084   /* So that the query shows the correct value.  */
1085   if (size <= 0)
1086     size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1087
1088   /* Extra checks?  */
1089   if (fixed_p && !config->fixed_p)
1090     {
1091       if (! query (_("The target may not be able to correctly handle a %s\n"
1092                    "of %ld bytes. Change the packet size? "),
1093                    config->name, size))
1094         error (_("Packet size not changed."));
1095     }
1096   /* Update the config.  */
1097   config->fixed_p = fixed_p;
1098   config->size = size;
1099 }
1100
1101 static void
1102 show_memory_packet_size (struct memory_packet_config *config)
1103 {
1104   printf_filtered (_("The %s is %ld. "), config->name, config->size);
1105   if (config->fixed_p)
1106     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1107                      get_memory_packet_size (config));
1108   else
1109     printf_filtered (_("Packets are limited to %ld bytes.\n"),
1110                      get_memory_packet_size (config));
1111 }
1112
1113 static struct memory_packet_config memory_write_packet_config =
1114 {
1115   "memory-write-packet-size",
1116 };
1117
1118 static void
1119 set_memory_write_packet_size (char *args, int from_tty)
1120 {
1121   set_memory_packet_size (args, &memory_write_packet_config);
1122 }
1123
1124 static void
1125 show_memory_write_packet_size (char *args, int from_tty)
1126 {
1127   show_memory_packet_size (&memory_write_packet_config);
1128 }
1129
1130 static long
1131 get_memory_write_packet_size (void)
1132 {
1133   return get_memory_packet_size (&memory_write_packet_config);
1134 }
1135
1136 static struct memory_packet_config memory_read_packet_config =
1137 {
1138   "memory-read-packet-size",
1139 };
1140
1141 static void
1142 set_memory_read_packet_size (char *args, int from_tty)
1143 {
1144   set_memory_packet_size (args, &memory_read_packet_config);
1145 }
1146
1147 static void
1148 show_memory_read_packet_size (char *args, int from_tty)
1149 {
1150   show_memory_packet_size (&memory_read_packet_config);
1151 }
1152
1153 static long
1154 get_memory_read_packet_size (void)
1155 {
1156   long size = get_memory_packet_size (&memory_read_packet_config);
1157
1158   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1159      extra buffer size argument before the memory read size can be
1160      increased beyond this.  */
1161   if (size > get_remote_packet_size ())
1162     size = get_remote_packet_size ();
1163   return size;
1164 }
1165
1166 \f
1167 /* Generic configuration support for packets the stub optionally
1168    supports.  Allows the user to specify the use of the packet as well
1169    as allowing GDB to auto-detect support in the remote stub.  */
1170
1171 enum packet_support
1172   {
1173     PACKET_SUPPORT_UNKNOWN = 0,
1174     PACKET_ENABLE,
1175     PACKET_DISABLE
1176   };
1177
1178 struct packet_config
1179   {
1180     const char *name;
1181     const char *title;
1182
1183     /* If auto, GDB auto-detects support for this packet or feature,
1184        either through qSupported, or by trying the packet and looking
1185        at the response.  If true, GDB assumes the target supports this
1186        packet.  If false, the packet is disabled.  Configs that don't
1187        have an associated command always have this set to auto.  */
1188     enum auto_boolean detect;
1189
1190     /* Does the target support this packet?  */
1191     enum packet_support support;
1192   };
1193
1194 /* Analyze a packet's return value and update the packet config
1195    accordingly.  */
1196
1197 enum packet_result
1198 {
1199   PACKET_ERROR,
1200   PACKET_OK,
1201   PACKET_UNKNOWN
1202 };
1203
1204 static enum packet_support packet_config_support (struct packet_config *config);
1205 static enum packet_support packet_support (int packet);
1206
1207 static void
1208 show_packet_config_cmd (struct packet_config *config)
1209 {
1210   char *support = "internal-error";
1211
1212   switch (packet_config_support (config))
1213     {
1214     case PACKET_ENABLE:
1215       support = "enabled";
1216       break;
1217     case PACKET_DISABLE:
1218       support = "disabled";
1219       break;
1220     case PACKET_SUPPORT_UNKNOWN:
1221       support = "unknown";
1222       break;
1223     }
1224   switch (config->detect)
1225     {
1226     case AUTO_BOOLEAN_AUTO:
1227       printf_filtered (_("Support for the `%s' packet "
1228                          "is auto-detected, currently %s.\n"),
1229                        config->name, support);
1230       break;
1231     case AUTO_BOOLEAN_TRUE:
1232     case AUTO_BOOLEAN_FALSE:
1233       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1234                        config->name, support);
1235       break;
1236     }
1237 }
1238
1239 static void
1240 add_packet_config_cmd (struct packet_config *config, const char *name,
1241                        const char *title, int legacy)
1242 {
1243   char *set_doc;
1244   char *show_doc;
1245   char *cmd_name;
1246
1247   config->name = name;
1248   config->title = title;
1249   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1250                         name, title);
1251   show_doc = xstrprintf ("Show current use of remote "
1252                          "protocol `%s' (%s) packet",
1253                          name, title);
1254   /* set/show TITLE-packet {auto,on,off} */
1255   cmd_name = xstrprintf ("%s-packet", title);
1256   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1257                                 &config->detect, set_doc,
1258                                 show_doc, NULL, /* help_doc */
1259                                 NULL,
1260                                 show_remote_protocol_packet_cmd,
1261                                 &remote_set_cmdlist, &remote_show_cmdlist);
1262   /* The command code copies the documentation strings.  */
1263   xfree (set_doc);
1264   xfree (show_doc);
1265   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1266   if (legacy)
1267     {
1268       char *legacy_name;
1269
1270       legacy_name = xstrprintf ("%s-packet", name);
1271       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1272                      &remote_set_cmdlist);
1273       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1274                      &remote_show_cmdlist);
1275     }
1276 }
1277
1278 static enum packet_result
1279 packet_check_result (const char *buf)
1280 {
1281   if (buf[0] != '\0')
1282     {
1283       /* The stub recognized the packet request.  Check that the
1284          operation succeeded.  */
1285       if (buf[0] == 'E'
1286           && isxdigit (buf[1]) && isxdigit (buf[2])
1287           && buf[3] == '\0')
1288         /* "Enn"  - definitly an error.  */
1289         return PACKET_ERROR;
1290
1291       /* Always treat "E." as an error.  This will be used for
1292          more verbose error messages, such as E.memtypes.  */
1293       if (buf[0] == 'E' && buf[1] == '.')
1294         return PACKET_ERROR;
1295
1296       /* The packet may or may not be OK.  Just assume it is.  */
1297       return PACKET_OK;
1298     }
1299   else
1300     /* The stub does not support the packet.  */
1301     return PACKET_UNKNOWN;
1302 }
1303
1304 static enum packet_result
1305 packet_ok (const char *buf, struct packet_config *config)
1306 {
1307   enum packet_result result;
1308
1309   if (config->detect != AUTO_BOOLEAN_TRUE
1310       && config->support == PACKET_DISABLE)
1311     internal_error (__FILE__, __LINE__,
1312                     _("packet_ok: attempt to use a disabled packet"));
1313
1314   result = packet_check_result (buf);
1315   switch (result)
1316     {
1317     case PACKET_OK:
1318     case PACKET_ERROR:
1319       /* The stub recognized the packet request.  */
1320       if (config->support == PACKET_SUPPORT_UNKNOWN)
1321         {
1322           if (remote_debug)
1323             fprintf_unfiltered (gdb_stdlog,
1324                                 "Packet %s (%s) is supported\n",
1325                                 config->name, config->title);
1326           config->support = PACKET_ENABLE;
1327         }
1328       break;
1329     case PACKET_UNKNOWN:
1330       /* The stub does not support the packet.  */
1331       if (config->detect == AUTO_BOOLEAN_AUTO
1332           && config->support == PACKET_ENABLE)
1333         {
1334           /* If the stub previously indicated that the packet was
1335              supported then there is a protocol error.  */
1336           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1337                  config->name, config->title);
1338         }
1339       else if (config->detect == AUTO_BOOLEAN_TRUE)
1340         {
1341           /* The user set it wrong.  */
1342           error (_("Enabled packet %s (%s) not recognized by stub"),
1343                  config->name, config->title);
1344         }
1345
1346       if (remote_debug)
1347         fprintf_unfiltered (gdb_stdlog,
1348                             "Packet %s (%s) is NOT supported\n",
1349                             config->name, config->title);
1350       config->support = PACKET_DISABLE;
1351       break;
1352     }
1353
1354   return result;
1355 }
1356
1357 enum {
1358   PACKET_vCont = 0,
1359   PACKET_X,
1360   PACKET_qSymbol,
1361   PACKET_P,
1362   PACKET_p,
1363   PACKET_Z0,
1364   PACKET_Z1,
1365   PACKET_Z2,
1366   PACKET_Z3,
1367   PACKET_Z4,
1368   PACKET_vFile_setfs,
1369   PACKET_vFile_open,
1370   PACKET_vFile_pread,
1371   PACKET_vFile_pwrite,
1372   PACKET_vFile_close,
1373   PACKET_vFile_unlink,
1374   PACKET_vFile_readlink,
1375   PACKET_vFile_fstat,
1376   PACKET_qXfer_auxv,
1377   PACKET_qXfer_features,
1378   PACKET_qXfer_exec_file,
1379   PACKET_qXfer_libraries,
1380   PACKET_qXfer_libraries_svr4,
1381   PACKET_qXfer_memory_map,
1382   PACKET_qXfer_spu_read,
1383   PACKET_qXfer_spu_write,
1384   PACKET_qXfer_osdata,
1385   PACKET_qXfer_threads,
1386   PACKET_qXfer_statictrace_read,
1387   PACKET_qXfer_traceframe_info,
1388   PACKET_qXfer_uib,
1389   PACKET_qGetTIBAddr,
1390   PACKET_qGetTLSAddr,
1391   PACKET_qSupported,
1392   PACKET_qTStatus,
1393   PACKET_QPassSignals,
1394   PACKET_QCatchSyscalls,
1395   PACKET_QProgramSignals,
1396   PACKET_qCRC,
1397   PACKET_qSearch_memory,
1398   PACKET_vAttach,
1399   PACKET_vRun,
1400   PACKET_QStartNoAckMode,
1401   PACKET_vKill,
1402   PACKET_qXfer_siginfo_read,
1403   PACKET_qXfer_siginfo_write,
1404   PACKET_qAttached,
1405
1406   /* Support for conditional tracepoints.  */
1407   PACKET_ConditionalTracepoints,
1408
1409   /* Support for target-side breakpoint conditions.  */
1410   PACKET_ConditionalBreakpoints,
1411
1412   /* Support for target-side breakpoint commands.  */
1413   PACKET_BreakpointCommands,
1414
1415   /* Support for fast tracepoints.  */
1416   PACKET_FastTracepoints,
1417
1418   /* Support for static tracepoints.  */
1419   PACKET_StaticTracepoints,
1420
1421   /* Support for installing tracepoints while a trace experiment is
1422      running.  */
1423   PACKET_InstallInTrace,
1424
1425   PACKET_bc,
1426   PACKET_bs,
1427   PACKET_TracepointSource,
1428   PACKET_QAllow,
1429   PACKET_qXfer_fdpic,
1430   PACKET_QDisableRandomization,
1431   PACKET_QAgent,
1432   PACKET_QTBuffer_size,
1433   PACKET_Qbtrace_off,
1434   PACKET_Qbtrace_bts,
1435   PACKET_Qbtrace_pt,
1436   PACKET_qXfer_btrace,
1437
1438   /* Support for the QNonStop packet.  */
1439   PACKET_QNonStop,
1440
1441   /* Support for the QThreadEvents packet.  */
1442   PACKET_QThreadEvents,
1443
1444   /* Support for multi-process extensions.  */
1445   PACKET_multiprocess_feature,
1446
1447   /* Support for enabling and disabling tracepoints while a trace
1448      experiment is running.  */
1449   PACKET_EnableDisableTracepoints_feature,
1450
1451   /* Support for collecting strings using the tracenz bytecode.  */
1452   PACKET_tracenz_feature,
1453
1454   /* Support for continuing to run a trace experiment while GDB is
1455      disconnected.  */
1456   PACKET_DisconnectedTracing_feature,
1457
1458   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1459   PACKET_augmented_libraries_svr4_read_feature,
1460
1461   /* Support for the qXfer:btrace-conf:read packet.  */
1462   PACKET_qXfer_btrace_conf,
1463
1464   /* Support for the Qbtrace-conf:bts:size packet.  */
1465   PACKET_Qbtrace_conf_bts_size,
1466
1467   /* Support for swbreak+ feature.  */
1468   PACKET_swbreak_feature,
1469
1470   /* Support for hwbreak+ feature.  */
1471   PACKET_hwbreak_feature,
1472
1473   /* Support for fork events.  */
1474   PACKET_fork_event_feature,
1475
1476   /* Support for vfork events.  */
1477   PACKET_vfork_event_feature,
1478
1479   /* Support for the Qbtrace-conf:pt:size packet.  */
1480   PACKET_Qbtrace_conf_pt_size,
1481
1482   /* Support for exec events.  */
1483   PACKET_exec_event_feature,
1484
1485   /* Support for query supported vCont actions.  */
1486   PACKET_vContSupported,
1487
1488   /* Support remote CTRL-C.  */
1489   PACKET_vCtrlC,
1490
1491   /* Support TARGET_WAITKIND_NO_RESUMED.  */
1492   PACKET_no_resumed,
1493
1494   PACKET_MAX
1495 };
1496
1497 static struct packet_config remote_protocol_packets[PACKET_MAX];
1498
1499 /* Returns the packet's corresponding "set remote foo-packet" command
1500    state.  See struct packet_config for more details.  */
1501
1502 static enum auto_boolean
1503 packet_set_cmd_state (int packet)
1504 {
1505   return remote_protocol_packets[packet].detect;
1506 }
1507
1508 /* Returns whether a given packet or feature is supported.  This takes
1509    into account the state of the corresponding "set remote foo-packet"
1510    command, which may be used to bypass auto-detection.  */
1511
1512 static enum packet_support
1513 packet_config_support (struct packet_config *config)
1514 {
1515   switch (config->detect)
1516     {
1517     case AUTO_BOOLEAN_TRUE:
1518       return PACKET_ENABLE;
1519     case AUTO_BOOLEAN_FALSE:
1520       return PACKET_DISABLE;
1521     case AUTO_BOOLEAN_AUTO:
1522       return config->support;
1523     default:
1524       gdb_assert_not_reached (_("bad switch"));
1525     }
1526 }
1527
1528 /* Same as packet_config_support, but takes the packet's enum value as
1529    argument.  */
1530
1531 static enum packet_support
1532 packet_support (int packet)
1533 {
1534   struct packet_config *config = &remote_protocol_packets[packet];
1535
1536   return packet_config_support (config);
1537 }
1538
1539 static void
1540 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1541                                  struct cmd_list_element *c,
1542                                  const char *value)
1543 {
1544   struct packet_config *packet;
1545
1546   for (packet = remote_protocol_packets;
1547        packet < &remote_protocol_packets[PACKET_MAX];
1548        packet++)
1549     {
1550       if (&packet->detect == c->var)
1551         {
1552           show_packet_config_cmd (packet);
1553           return;
1554         }
1555     }
1556   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1557                   c->name);
1558 }
1559
1560 /* Should we try one of the 'Z' requests?  */
1561
1562 enum Z_packet_type
1563 {
1564   Z_PACKET_SOFTWARE_BP,
1565   Z_PACKET_HARDWARE_BP,
1566   Z_PACKET_WRITE_WP,
1567   Z_PACKET_READ_WP,
1568   Z_PACKET_ACCESS_WP,
1569   NR_Z_PACKET_TYPES
1570 };
1571
1572 /* For compatibility with older distributions.  Provide a ``set remote
1573    Z-packet ...'' command that updates all the Z packet types.  */
1574
1575 static enum auto_boolean remote_Z_packet_detect;
1576
1577 static void
1578 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1579                                   struct cmd_list_element *c)
1580 {
1581   int i;
1582
1583   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1584     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1585 }
1586
1587 static void
1588 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1589                                    struct cmd_list_element *c,
1590                                    const char *value)
1591 {
1592   int i;
1593
1594   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1595     {
1596       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1597     }
1598 }
1599
1600 /* Returns true if the multi-process extensions are in effect.  */
1601
1602 static int
1603 remote_multi_process_p (struct remote_state *rs)
1604 {
1605   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1606 }
1607
1608 /* Returns true if fork events are supported.  */
1609
1610 static int
1611 remote_fork_event_p (struct remote_state *rs)
1612 {
1613   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1614 }
1615
1616 /* Returns true if vfork events are supported.  */
1617
1618 static int
1619 remote_vfork_event_p (struct remote_state *rs)
1620 {
1621   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1622 }
1623
1624 /* Returns true if exec events are supported.  */
1625
1626 static int
1627 remote_exec_event_p (struct remote_state *rs)
1628 {
1629   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1630 }
1631
1632 /* Insert fork catchpoint target routine.  If fork events are enabled
1633    then return success, nothing more to do.  */
1634
1635 static int
1636 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1637 {
1638   struct remote_state *rs = get_remote_state ();
1639
1640   return !remote_fork_event_p (rs);
1641 }
1642
1643 /* Remove fork catchpoint target routine.  Nothing to do, just
1644    return success.  */
1645
1646 static int
1647 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1648 {
1649   return 0;
1650 }
1651
1652 /* Insert vfork catchpoint target routine.  If vfork events are enabled
1653    then return success, nothing more to do.  */
1654
1655 static int
1656 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1657 {
1658   struct remote_state *rs = get_remote_state ();
1659
1660   return !remote_vfork_event_p (rs);
1661 }
1662
1663 /* Remove vfork catchpoint target routine.  Nothing to do, just
1664    return success.  */
1665
1666 static int
1667 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1668 {
1669   return 0;
1670 }
1671
1672 /* Insert exec catchpoint target routine.  If exec events are
1673    enabled, just return success.  */
1674
1675 static int
1676 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1677 {
1678   struct remote_state *rs = get_remote_state ();
1679
1680   return !remote_exec_event_p (rs);
1681 }
1682
1683 /* Remove exec catchpoint target routine.  Nothing to do, just
1684    return success.  */
1685
1686 static int
1687 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1688 {
1689   return 0;
1690 }
1691
1692 /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
1693 static struct async_signal_handler *async_sigint_remote_twice_token;
1694 static struct async_signal_handler *async_sigint_remote_token;
1695
1696 \f
1697 /* Asynchronous signal handle registered as event loop source for
1698    when we have pending events ready to be passed to the core.  */
1699
1700 static struct async_event_handler *remote_async_inferior_event_token;
1701
1702 \f
1703
1704 static ptid_t magic_null_ptid;
1705 static ptid_t not_sent_ptid;
1706 static ptid_t any_thread_ptid;
1707
1708 /* Find out if the stub attached to PID (and hence GDB should offer to
1709    detach instead of killing it when bailing out).  */
1710
1711 static int
1712 remote_query_attached (int pid)
1713 {
1714   struct remote_state *rs = get_remote_state ();
1715   size_t size = get_remote_packet_size ();
1716
1717   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1718     return 0;
1719
1720   if (remote_multi_process_p (rs))
1721     xsnprintf (rs->buf, size, "qAttached:%x", pid);
1722   else
1723     xsnprintf (rs->buf, size, "qAttached");
1724
1725   putpkt (rs->buf);
1726   getpkt (&rs->buf, &rs->buf_size, 0);
1727
1728   switch (packet_ok (rs->buf,
1729                      &remote_protocol_packets[PACKET_qAttached]))
1730     {
1731     case PACKET_OK:
1732       if (strcmp (rs->buf, "1") == 0)
1733         return 1;
1734       break;
1735     case PACKET_ERROR:
1736       warning (_("Remote failure reply: %s"), rs->buf);
1737       break;
1738     case PACKET_UNKNOWN:
1739       break;
1740     }
1741
1742   return 0;
1743 }
1744
1745 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
1746    has been invented by GDB, instead of reported by the target.  Since
1747    we can be connected to a remote system before before knowing about
1748    any inferior, mark the target with execution when we find the first
1749    inferior.  If ATTACHED is 1, then we had just attached to this
1750    inferior.  If it is 0, then we just created this inferior.  If it
1751    is -1, then try querying the remote stub to find out if it had
1752    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
1753    attempt to open this inferior's executable as the main executable
1754    if no main executable is open already.  */
1755
1756 static struct inferior *
1757 remote_add_inferior (int fake_pid_p, int pid, int attached,
1758                      int try_open_exec)
1759 {
1760   struct inferior *inf;
1761
1762   /* Check whether this process we're learning about is to be
1763      considered attached, or if is to be considered to have been
1764      spawned by the stub.  */
1765   if (attached == -1)
1766     attached = remote_query_attached (pid);
1767
1768   if (gdbarch_has_global_solist (target_gdbarch ()))
1769     {
1770       /* If the target shares code across all inferiors, then every
1771          attach adds a new inferior.  */
1772       inf = add_inferior (pid);
1773
1774       /* ... and every inferior is bound to the same program space.
1775          However, each inferior may still have its own address
1776          space.  */
1777       inf->aspace = maybe_new_address_space ();
1778       inf->pspace = current_program_space;
1779     }
1780   else
1781     {
1782       /* In the traditional debugging scenario, there's a 1-1 match
1783          between program/address spaces.  We simply bind the inferior
1784          to the program space's address space.  */
1785       inf = current_inferior ();
1786       inferior_appeared (inf, pid);
1787     }
1788
1789   inf->attach_flag = attached;
1790   inf->fake_pid_p = fake_pid_p;
1791
1792   /* If no main executable is currently open then attempt to
1793      open the file that was executed to create this inferior.  */
1794   if (try_open_exec && get_exec_file (0) == NULL)
1795     exec_file_locate_attach (pid, 1);
1796
1797   return inf;
1798 }
1799
1800 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1801    according to RUNNING.  */
1802
1803 static void
1804 remote_add_thread (ptid_t ptid, int running, int executing)
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, executing);
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.  EXECUTING indicates whether the
1828    thread is (internally) executing or stopped.  */
1829
1830 static void
1831 remote_notice_new_inferior (ptid_t currthread, int executing)
1832 {
1833   /* In non-stop mode, we assume new found threads are (externally)
1834      running until proven otherwise with a stop reply.  In all-stop,
1835      we can only get here if all threads are stopped.  */
1836   int running = target_is_non_stop_p () ? 1 : 0;
1837
1838   /* If this is a new thread, add it to GDB's thread list.
1839      If we leave it up to WFI to do this, bad things will happen.  */
1840
1841   if (in_thread_list (currthread) && is_exited (currthread))
1842     {
1843       /* We're seeing an event on a thread id we knew had exited.
1844          This has to be a new thread reusing the old id.  Add it.  */
1845       remote_add_thread (currthread, running, executing);
1846       return;
1847     }
1848
1849   if (!in_thread_list (currthread))
1850     {
1851       struct inferior *inf = NULL;
1852       int pid = ptid_get_pid (currthread);
1853
1854       if (ptid_is_pid (inferior_ptid)
1855           && pid == ptid_get_pid (inferior_ptid))
1856         {
1857           /* inferior_ptid has no thread member yet.  This can happen
1858              with the vAttach -> remote_wait,"TAAthread:" path if the
1859              stub doesn't support qC.  This is the first stop reported
1860              after an attach, so this is the main thread.  Update the
1861              ptid in the thread list.  */
1862           if (in_thread_list (pid_to_ptid (pid)))
1863             thread_change_ptid (inferior_ptid, currthread);
1864           else
1865             {
1866               remote_add_thread (currthread, running, executing);
1867               inferior_ptid = currthread;
1868             }
1869           return;
1870         }
1871
1872       if (ptid_equal (magic_null_ptid, inferior_ptid))
1873         {
1874           /* inferior_ptid is not set yet.  This can happen with the
1875              vRun -> remote_wait,"TAAthread:" path if the stub
1876              doesn't support qC.  This is the first stop reported
1877              after an attach, so this is the main thread.  Update the
1878              ptid in the thread list.  */
1879           thread_change_ptid (inferior_ptid, currthread);
1880           return;
1881         }
1882
1883       /* When connecting to a target remote, or to a target
1884          extended-remote which already was debugging an inferior, we
1885          may not know about it yet.  Add it before adding its child
1886          thread, so notifications are emitted in a sensible order.  */
1887       if (!in_inferior_list (ptid_get_pid (currthread)))
1888         {
1889           struct remote_state *rs = get_remote_state ();
1890           int fake_pid_p = !remote_multi_process_p (rs);
1891
1892           inf = remote_add_inferior (fake_pid_p,
1893                                      ptid_get_pid (currthread), -1, 1);
1894         }
1895
1896       /* This is really a new thread.  Add it.  */
1897       remote_add_thread (currthread, running, executing);
1898
1899       /* If we found a new inferior, let the common code do whatever
1900          it needs to with it (e.g., read shared libraries, insert
1901          breakpoints), unless we're just setting up an all-stop
1902          connection.  */
1903       if (inf != NULL)
1904         {
1905           struct remote_state *rs = get_remote_state ();
1906
1907           if (!rs->starting_up)
1908             notice_new_inferior (currthread, executing, 0);
1909         }
1910     }
1911 }
1912
1913 /* Return the private thread data, creating it if necessary.  */
1914
1915 static struct private_thread_info *
1916 demand_private_info (ptid_t ptid)
1917 {
1918   struct thread_info *info = find_thread_ptid (ptid);
1919
1920   gdb_assert (info);
1921
1922   if (!info->priv)
1923     {
1924       info->priv = XNEW (struct private_thread_info);
1925       info->private_dtor = free_private_thread_info;
1926       info->priv->core = -1;
1927       info->priv->extra = NULL;
1928       info->priv->name = NULL;
1929     }
1930
1931   return info->priv;
1932 }
1933
1934 /* Call this function as a result of
1935    1) A halt indication (T packet) containing a thread id
1936    2) A direct query of currthread
1937    3) Successful execution of set thread */
1938
1939 static void
1940 record_currthread (struct remote_state *rs, ptid_t currthread)
1941 {
1942   rs->general_thread = currthread;
1943 }
1944
1945 /* If 'QPassSignals' is supported, tell the remote stub what signals
1946    it can simply pass through to the inferior without reporting.  */
1947
1948 static void
1949 remote_pass_signals (struct target_ops *self,
1950                      int numsigs, unsigned char *pass_signals)
1951 {
1952   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1953     {
1954       char *pass_packet, *p;
1955       int count = 0, i;
1956       struct remote_state *rs = get_remote_state ();
1957
1958       gdb_assert (numsigs < 256);
1959       for (i = 0; i < numsigs; i++)
1960         {
1961           if (pass_signals[i])
1962             count++;
1963         }
1964       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1965       strcpy (pass_packet, "QPassSignals:");
1966       p = pass_packet + strlen (pass_packet);
1967       for (i = 0; i < numsigs; i++)
1968         {
1969           if (pass_signals[i])
1970             {
1971               if (i >= 16)
1972                 *p++ = tohex (i >> 4);
1973               *p++ = tohex (i & 15);
1974               if (count)
1975                 *p++ = ';';
1976               else
1977                 break;
1978               count--;
1979             }
1980         }
1981       *p = 0;
1982       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1983         {
1984           putpkt (pass_packet);
1985           getpkt (&rs->buf, &rs->buf_size, 0);
1986           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1987           if (rs->last_pass_packet)
1988             xfree (rs->last_pass_packet);
1989           rs->last_pass_packet = pass_packet;
1990         }
1991       else
1992         xfree (pass_packet);
1993     }
1994 }
1995
1996 /* If 'QCatchSyscalls' is supported, tell the remote stub
1997    to report syscalls to GDB.  */
1998
1999 static int
2000 remote_set_syscall_catchpoint (struct target_ops *self,
2001                                int pid, int needed, int any_count,
2002                                int table_size, int *table)
2003 {
2004   char *catch_packet;
2005   enum packet_result result;
2006   int n_sysno = 0;
2007
2008   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2009     {
2010       /* Not supported.  */
2011       return 1;
2012     }
2013
2014   if (needed && !any_count)
2015     {
2016       int i;
2017
2018       /* Count how many syscalls are to be caught (table[sysno] != 0).  */
2019       for (i = 0; i < table_size; i++)
2020         {
2021           if (table[i] != 0)
2022             n_sysno++;
2023         }
2024     }
2025
2026   if (remote_debug)
2027     {
2028       fprintf_unfiltered (gdb_stdlog,
2029                           "remote_set_syscall_catchpoint "
2030                           "pid %d needed %d any_count %d n_sysno %d\n",
2031                           pid, needed, any_count, n_sysno);
2032     }
2033
2034   if (needed)
2035     {
2036       /* Prepare a packet with the sysno list, assuming max 8+1
2037          characters for a sysno.  If the resulting packet size is too
2038          big, fallback on the non-selective packet.  */
2039       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2040
2041       catch_packet = (char *) xmalloc (maxpktsz);
2042       strcpy (catch_packet, "QCatchSyscalls:1");
2043       if (!any_count)
2044         {
2045           int i;
2046           char *p;
2047
2048           p = catch_packet;
2049           p += strlen (p);
2050
2051           /* Add in catch_packet each syscall to be caught (table[i] != 0).  */
2052           for (i = 0; i < table_size; i++)
2053             {
2054               if (table[i] != 0)
2055                 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2056             }
2057         }
2058       if (strlen (catch_packet) > get_remote_packet_size ())
2059         {
2060           /* catch_packet too big.  Fallback to less efficient
2061              non selective mode, with GDB doing the filtering.  */
2062           catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2063         }
2064     }
2065   else
2066     catch_packet = xstrdup ("QCatchSyscalls:0");
2067
2068   {
2069     struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2070     struct remote_state *rs = get_remote_state ();
2071
2072     putpkt (catch_packet);
2073     getpkt (&rs->buf, &rs->buf_size, 0);
2074     result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2075     do_cleanups (old_chain);
2076     if (result == PACKET_OK)
2077       return 0;
2078     else
2079       return -1;
2080   }
2081 }
2082
2083 /* If 'QProgramSignals' is supported, tell the remote stub what
2084    signals it should pass through to the inferior when detaching.  */
2085
2086 static void
2087 remote_program_signals (struct target_ops *self,
2088                         int numsigs, unsigned char *signals)
2089 {
2090   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2091     {
2092       char *packet, *p;
2093       int count = 0, i;
2094       struct remote_state *rs = get_remote_state ();
2095
2096       gdb_assert (numsigs < 256);
2097       for (i = 0; i < numsigs; i++)
2098         {
2099           if (signals[i])
2100             count++;
2101         }
2102       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2103       strcpy (packet, "QProgramSignals:");
2104       p = packet + strlen (packet);
2105       for (i = 0; i < numsigs; i++)
2106         {
2107           if (signal_pass_state (i))
2108             {
2109               if (i >= 16)
2110                 *p++ = tohex (i >> 4);
2111               *p++ = tohex (i & 15);
2112               if (count)
2113                 *p++ = ';';
2114               else
2115                 break;
2116               count--;
2117             }
2118         }
2119       *p = 0;
2120       if (!rs->last_program_signals_packet
2121           || strcmp (rs->last_program_signals_packet, packet) != 0)
2122         {
2123           putpkt (packet);
2124           getpkt (&rs->buf, &rs->buf_size, 0);
2125           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2126           xfree (rs->last_program_signals_packet);
2127           rs->last_program_signals_packet = packet;
2128         }
2129       else
2130         xfree (packet);
2131     }
2132 }
2133
2134 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2135    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2136    thread.  If GEN is set, set the general thread, if not, then set
2137    the step/continue thread.  */
2138 static void
2139 set_thread (struct ptid ptid, int gen)
2140 {
2141   struct remote_state *rs = get_remote_state ();
2142   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2143   char *buf = rs->buf;
2144   char *endbuf = rs->buf + get_remote_packet_size ();
2145
2146   if (ptid_equal (state, ptid))
2147     return;
2148
2149   *buf++ = 'H';
2150   *buf++ = gen ? 'g' : 'c';
2151   if (ptid_equal (ptid, magic_null_ptid))
2152     xsnprintf (buf, endbuf - buf, "0");
2153   else if (ptid_equal (ptid, any_thread_ptid))
2154     xsnprintf (buf, endbuf - buf, "0");
2155   else if (ptid_equal (ptid, minus_one_ptid))
2156     xsnprintf (buf, endbuf - buf, "-1");
2157   else
2158     write_ptid (buf, endbuf, ptid);
2159   putpkt (rs->buf);
2160   getpkt (&rs->buf, &rs->buf_size, 0);
2161   if (gen)
2162     rs->general_thread = ptid;
2163   else
2164     rs->continue_thread = ptid;
2165 }
2166
2167 static void
2168 set_general_thread (struct ptid ptid)
2169 {
2170   set_thread (ptid, 1);
2171 }
2172
2173 static void
2174 set_continue_thread (struct ptid ptid)
2175 {
2176   set_thread (ptid, 0);
2177 }
2178
2179 /* Change the remote current process.  Which thread within the process
2180    ends up selected isn't important, as long as it is the same process
2181    as what INFERIOR_PTID points to.
2182
2183    This comes from that fact that there is no explicit notion of
2184    "selected process" in the protocol.  The selected process for
2185    general operations is the process the selected general thread
2186    belongs to.  */
2187
2188 static void
2189 set_general_process (void)
2190 {
2191   struct remote_state *rs = get_remote_state ();
2192
2193   /* If the remote can't handle multiple processes, don't bother.  */
2194   if (!remote_multi_process_p (rs))
2195     return;
2196
2197   /* We only need to change the remote current thread if it's pointing
2198      at some other process.  */
2199   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2200     set_general_thread (inferior_ptid);
2201 }
2202
2203 \f
2204 /* Return nonzero if this is the main thread that we made up ourselves
2205    to model non-threaded targets as single-threaded.  */
2206
2207 static int
2208 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2209 {
2210   if (ptid_equal (ptid, magic_null_ptid))
2211     /* The main thread is always alive.  */
2212     return 1;
2213
2214   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2215     /* The main thread is always alive.  This can happen after a
2216        vAttach, if the remote side doesn't support
2217        multi-threading.  */
2218     return 1;
2219
2220   return 0;
2221 }
2222
2223 /* Return nonzero if the thread PTID is still alive on the remote
2224    system.  */
2225
2226 static int
2227 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2228 {
2229   struct remote_state *rs = get_remote_state ();
2230   char *p, *endp;
2231
2232   /* Check if this is a thread that we made up ourselves to model
2233      non-threaded targets as single-threaded.  */
2234   if (remote_thread_always_alive (ops, ptid))
2235     return 1;
2236
2237   p = rs->buf;
2238   endp = rs->buf + get_remote_packet_size ();
2239
2240   *p++ = 'T';
2241   write_ptid (p, endp, ptid);
2242
2243   putpkt (rs->buf);
2244   getpkt (&rs->buf, &rs->buf_size, 0);
2245   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2246 }
2247
2248 /* Return a pointer to a thread name if we know it and NULL otherwise.
2249    The thread_info object owns the memory for the name.  */
2250
2251 static const char *
2252 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2253 {
2254   if (info->priv != NULL)
2255     return info->priv->name;
2256
2257   return NULL;
2258 }
2259
2260 /* About these extended threadlist and threadinfo packets.  They are
2261    variable length packets but, the fields within them are often fixed
2262    length.  They are redundent enough to send over UDP as is the
2263    remote protocol in general.  There is a matching unit test module
2264    in libstub.  */
2265
2266 /* WARNING: This threadref data structure comes from the remote O.S.,
2267    libstub protocol encoding, and remote.c.  It is not particularly
2268    changable.  */
2269
2270 /* Right now, the internal structure is int. We want it to be bigger.
2271    Plan to fix this.  */
2272
2273 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2274
2275 /* gdb_ext_thread_info is an internal GDB data structure which is
2276    equivalent to the reply of the remote threadinfo packet.  */
2277
2278 struct gdb_ext_thread_info
2279   {
2280     threadref threadid;         /* External form of thread reference.  */
2281     int active;                 /* Has state interesting to GDB?
2282                                    regs, stack.  */
2283     char display[256];          /* Brief state display, name,
2284                                    blocked/suspended.  */
2285     char shortname[32];         /* To be used to name threads.  */
2286     char more_display[256];     /* Long info, statistics, queue depth,
2287                                    whatever.  */
2288   };
2289
2290 /* The volume of remote transfers can be limited by submitting
2291    a mask containing bits specifying the desired information.
2292    Use a union of these values as the 'selection' parameter to
2293    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2294
2295 #define TAG_THREADID 1
2296 #define TAG_EXISTS 2
2297 #define TAG_DISPLAY 4
2298 #define TAG_THREADNAME 8
2299 #define TAG_MOREDISPLAY 16
2300
2301 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2302
2303 static char *unpack_nibble (char *buf, int *val);
2304
2305 static char *unpack_byte (char *buf, int *value);
2306
2307 static char *pack_int (char *buf, int value);
2308
2309 static char *unpack_int (char *buf, int *value);
2310
2311 static char *unpack_string (char *src, char *dest, int length);
2312
2313 static char *pack_threadid (char *pkt, threadref *id);
2314
2315 static char *unpack_threadid (char *inbuf, threadref *id);
2316
2317 void int_to_threadref (threadref *id, int value);
2318
2319 static int threadref_to_int (threadref *ref);
2320
2321 static void copy_threadref (threadref *dest, threadref *src);
2322
2323 static int threadmatch (threadref *dest, threadref *src);
2324
2325 static char *pack_threadinfo_request (char *pkt, int mode,
2326                                       threadref *id);
2327
2328 static int remote_unpack_thread_info_response (char *pkt,
2329                                                threadref *expectedref,
2330                                                struct gdb_ext_thread_info
2331                                                *info);
2332
2333
2334 static int remote_get_threadinfo (threadref *threadid,
2335                                   int fieldset, /*TAG mask */
2336                                   struct gdb_ext_thread_info *info);
2337
2338 static char *pack_threadlist_request (char *pkt, int startflag,
2339                                       int threadcount,
2340                                       threadref *nextthread);
2341
2342 static int parse_threadlist_response (char *pkt,
2343                                       int result_limit,
2344                                       threadref *original_echo,
2345                                       threadref *resultlist,
2346                                       int *doneflag);
2347
2348 static int remote_get_threadlist (int startflag,
2349                                   threadref *nextthread,
2350                                   int result_limit,
2351                                   int *done,
2352                                   int *result_count,
2353                                   threadref *threadlist);
2354
2355 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2356
2357 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2358                                        void *context, int looplimit);
2359
2360 static int remote_newthread_step (threadref *ref, void *context);
2361
2362
2363 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2364    buffer we're allowed to write to.  Returns
2365    BUF+CHARACTERS_WRITTEN.  */
2366
2367 static char *
2368 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2369 {
2370   int pid, tid;
2371   struct remote_state *rs = get_remote_state ();
2372
2373   if (remote_multi_process_p (rs))
2374     {
2375       pid = ptid_get_pid (ptid);
2376       if (pid < 0)
2377         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2378       else
2379         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2380     }
2381   tid = ptid_get_lwp (ptid);
2382   if (tid < 0)
2383     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2384   else
2385     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2386
2387   return buf;
2388 }
2389
2390 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
2391    passed the last parsed char.  Returns null_ptid on error.  */
2392
2393 static ptid_t
2394 read_ptid (char *buf, char **obuf)
2395 {
2396   char *p = buf;
2397   char *pp;
2398   ULONGEST pid = 0, tid = 0;
2399
2400   if (*p == 'p')
2401     {
2402       /* Multi-process ptid.  */
2403       pp = unpack_varlen_hex (p + 1, &pid);
2404       if (*pp != '.')
2405         error (_("invalid remote ptid: %s"), p);
2406
2407       p = pp;
2408       pp = unpack_varlen_hex (p + 1, &tid);
2409       if (obuf)
2410         *obuf = pp;
2411       return ptid_build (pid, tid, 0);
2412     }
2413
2414   /* No multi-process.  Just a tid.  */
2415   pp = unpack_varlen_hex (p, &tid);
2416
2417   /* Return null_ptid when no thread id is found.  */
2418   if (p == pp)
2419     {
2420       if (obuf)
2421         *obuf = pp;
2422       return null_ptid;
2423     }
2424
2425   /* Since the stub is not sending a process id, then default to
2426      what's in inferior_ptid, unless it's null at this point.  If so,
2427      then since there's no way to know the pid of the reported
2428      threads, use the magic number.  */
2429   if (ptid_equal (inferior_ptid, null_ptid))
2430     pid = ptid_get_pid (magic_null_ptid);
2431   else
2432     pid = ptid_get_pid (inferior_ptid);
2433
2434   if (obuf)
2435     *obuf = pp;
2436   return ptid_build (pid, tid, 0);
2437 }
2438
2439 static int
2440 stubhex (int ch)
2441 {
2442   if (ch >= 'a' && ch <= 'f')
2443     return ch - 'a' + 10;
2444   if (ch >= '0' && ch <= '9')
2445     return ch - '0';
2446   if (ch >= 'A' && ch <= 'F')
2447     return ch - 'A' + 10;
2448   return -1;
2449 }
2450
2451 static int
2452 stub_unpack_int (char *buff, int fieldlength)
2453 {
2454   int nibble;
2455   int retval = 0;
2456
2457   while (fieldlength)
2458     {
2459       nibble = stubhex (*buff++);
2460       retval |= nibble;
2461       fieldlength--;
2462       if (fieldlength)
2463         retval = retval << 4;
2464     }
2465   return retval;
2466 }
2467
2468 static char *
2469 unpack_nibble (char *buf, int *val)
2470 {
2471   *val = fromhex (*buf++);
2472   return buf;
2473 }
2474
2475 static char *
2476 unpack_byte (char *buf, int *value)
2477 {
2478   *value = stub_unpack_int (buf, 2);
2479   return buf + 2;
2480 }
2481
2482 static char *
2483 pack_int (char *buf, int value)
2484 {
2485   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2486   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2487   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2488   buf = pack_hex_byte (buf, (value & 0xff));
2489   return buf;
2490 }
2491
2492 static char *
2493 unpack_int (char *buf, int *value)
2494 {
2495   *value = stub_unpack_int (buf, 8);
2496   return buf + 8;
2497 }
2498
2499 #if 0                   /* Currently unused, uncomment when needed.  */
2500 static char *pack_string (char *pkt, char *string);
2501
2502 static char *
2503 pack_string (char *pkt, char *string)
2504 {
2505   char ch;
2506   int len;
2507
2508   len = strlen (string);
2509   if (len > 200)
2510     len = 200;          /* Bigger than most GDB packets, junk???  */
2511   pkt = pack_hex_byte (pkt, len);
2512   while (len-- > 0)
2513     {
2514       ch = *string++;
2515       if ((ch == '\0') || (ch == '#'))
2516         ch = '*';               /* Protect encapsulation.  */
2517       *pkt++ = ch;
2518     }
2519   return pkt;
2520 }
2521 #endif /* 0 (unused) */
2522
2523 static char *
2524 unpack_string (char *src, char *dest, int length)
2525 {
2526   while (length--)
2527     *dest++ = *src++;
2528   *dest = '\0';
2529   return src;
2530 }
2531
2532 static char *
2533 pack_threadid (char *pkt, threadref *id)
2534 {
2535   char *limit;
2536   unsigned char *altid;
2537
2538   altid = (unsigned char *) id;
2539   limit = pkt + BUF_THREAD_ID_SIZE;
2540   while (pkt < limit)
2541     pkt = pack_hex_byte (pkt, *altid++);
2542   return pkt;
2543 }
2544
2545
2546 static char *
2547 unpack_threadid (char *inbuf, threadref *id)
2548 {
2549   char *altref;
2550   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2551   int x, y;
2552
2553   altref = (char *) id;
2554
2555   while (inbuf < limit)
2556     {
2557       x = stubhex (*inbuf++);
2558       y = stubhex (*inbuf++);
2559       *altref++ = (x << 4) | y;
2560     }
2561   return inbuf;
2562 }
2563
2564 /* Externally, threadrefs are 64 bits but internally, they are still
2565    ints.  This is due to a mismatch of specifications.  We would like
2566    to use 64bit thread references internally.  This is an adapter
2567    function.  */
2568
2569 void
2570 int_to_threadref (threadref *id, int value)
2571 {
2572   unsigned char *scan;
2573
2574   scan = (unsigned char *) id;
2575   {
2576     int i = 4;
2577     while (i--)
2578       *scan++ = 0;
2579   }
2580   *scan++ = (value >> 24) & 0xff;
2581   *scan++ = (value >> 16) & 0xff;
2582   *scan++ = (value >> 8) & 0xff;
2583   *scan++ = (value & 0xff);
2584 }
2585
2586 static int
2587 threadref_to_int (threadref *ref)
2588 {
2589   int i, value = 0;
2590   unsigned char *scan;
2591
2592   scan = *ref;
2593   scan += 4;
2594   i = 4;
2595   while (i-- > 0)
2596     value = (value << 8) | ((*scan++) & 0xff);
2597   return value;
2598 }
2599
2600 static void
2601 copy_threadref (threadref *dest, threadref *src)
2602 {
2603   int i;
2604   unsigned char *csrc, *cdest;
2605
2606   csrc = (unsigned char *) src;
2607   cdest = (unsigned char *) dest;
2608   i = 8;
2609   while (i--)
2610     *cdest++ = *csrc++;
2611 }
2612
2613 static int
2614 threadmatch (threadref *dest, threadref *src)
2615 {
2616   /* Things are broken right now, so just assume we got a match.  */
2617 #if 0
2618   unsigned char *srcp, *destp;
2619   int i, result;
2620   srcp = (char *) src;
2621   destp = (char *) dest;
2622
2623   result = 1;
2624   while (i-- > 0)
2625     result &= (*srcp++ == *destp++) ? 1 : 0;
2626   return result;
2627 #endif
2628   return 1;
2629 }
2630
2631 /*
2632    threadid:1,        # always request threadid
2633    context_exists:2,
2634    display:4,
2635    unique_name:8,
2636    more_display:16
2637  */
2638
2639 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2640
2641 static char *
2642 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2643 {
2644   *pkt++ = 'q';                         /* Info Query */
2645   *pkt++ = 'P';                         /* process or thread info */
2646   pkt = pack_int (pkt, mode);           /* mode */
2647   pkt = pack_threadid (pkt, id);        /* threadid */
2648   *pkt = '\0';                          /* terminate */
2649   return pkt;
2650 }
2651
2652 /* These values tag the fields in a thread info response packet.  */
2653 /* Tagging the fields allows us to request specific fields and to
2654    add more fields as time goes by.  */
2655
2656 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2657 #define TAG_EXISTS 2            /* Is this process defined enough to
2658                                    fetch registers and its stack?  */
2659 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2660 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2661 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2662                                    the process.  */
2663
2664 static int
2665 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2666                                     struct gdb_ext_thread_info *info)
2667 {
2668   struct remote_state *rs = get_remote_state ();
2669   int mask, length;
2670   int tag;
2671   threadref ref;
2672   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2673   int retval = 1;
2674
2675   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2676   info->active = 0;
2677   info->display[0] = '\0';
2678   info->shortname[0] = '\0';
2679   info->more_display[0] = '\0';
2680
2681   /* Assume the characters indicating the packet type have been
2682      stripped.  */
2683   pkt = unpack_int (pkt, &mask);        /* arg mask */
2684   pkt = unpack_threadid (pkt, &ref);
2685
2686   if (mask == 0)
2687     warning (_("Incomplete response to threadinfo request."));
2688   if (!threadmatch (&ref, expectedref))
2689     {                   /* This is an answer to a different request.  */
2690       warning (_("ERROR RMT Thread info mismatch."));
2691       return 0;
2692     }
2693   copy_threadref (&info->threadid, &ref);
2694
2695   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
2696
2697   /* Packets are terminated with nulls.  */
2698   while ((pkt < limit) && mask && *pkt)
2699     {
2700       pkt = unpack_int (pkt, &tag);     /* tag */
2701       pkt = unpack_byte (pkt, &length); /* length */
2702       if (!(tag & mask))                /* Tags out of synch with mask.  */
2703         {
2704           warning (_("ERROR RMT: threadinfo tag mismatch."));
2705           retval = 0;
2706           break;
2707         }
2708       if (tag == TAG_THREADID)
2709         {
2710           if (length != 16)
2711             {
2712               warning (_("ERROR RMT: length of threadid is not 16."));
2713               retval = 0;
2714               break;
2715             }
2716           pkt = unpack_threadid (pkt, &ref);
2717           mask = mask & ~TAG_THREADID;
2718           continue;
2719         }
2720       if (tag == TAG_EXISTS)
2721         {
2722           info->active = stub_unpack_int (pkt, length);
2723           pkt += length;
2724           mask = mask & ~(TAG_EXISTS);
2725           if (length > 8)
2726             {
2727               warning (_("ERROR RMT: 'exists' length too long."));
2728               retval = 0;
2729               break;
2730             }
2731           continue;
2732         }
2733       if (tag == TAG_THREADNAME)
2734         {
2735           pkt = unpack_string (pkt, &info->shortname[0], length);
2736           mask = mask & ~TAG_THREADNAME;
2737           continue;
2738         }
2739       if (tag == TAG_DISPLAY)
2740         {
2741           pkt = unpack_string (pkt, &info->display[0], length);
2742           mask = mask & ~TAG_DISPLAY;
2743           continue;
2744         }
2745       if (tag == TAG_MOREDISPLAY)
2746         {
2747           pkt = unpack_string (pkt, &info->more_display[0], length);
2748           mask = mask & ~TAG_MOREDISPLAY;
2749           continue;
2750         }
2751       warning (_("ERROR RMT: unknown thread info tag."));
2752       break;                    /* Not a tag we know about.  */
2753     }
2754   return retval;
2755 }
2756
2757 static int
2758 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2759                        struct gdb_ext_thread_info *info)
2760 {
2761   struct remote_state *rs = get_remote_state ();
2762   int result;
2763
2764   pack_threadinfo_request (rs->buf, fieldset, threadid);
2765   putpkt (rs->buf);
2766   getpkt (&rs->buf, &rs->buf_size, 0);
2767
2768   if (rs->buf[0] == '\0')
2769     return 0;
2770
2771   result = remote_unpack_thread_info_response (rs->buf + 2,
2772                                                threadid, info);
2773   return result;
2774 }
2775
2776 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2777
2778 static char *
2779 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2780                          threadref *nextthread)
2781 {
2782   *pkt++ = 'q';                 /* info query packet */
2783   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2784   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2785   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2786   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2787   *pkt = '\0';
2788   return pkt;
2789 }
2790
2791 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2792
2793 static int
2794 parse_threadlist_response (char *pkt, int result_limit,
2795                            threadref *original_echo, threadref *resultlist,
2796                            int *doneflag)
2797 {
2798   struct remote_state *rs = get_remote_state ();
2799   char *limit;
2800   int count, resultcount, done;
2801
2802   resultcount = 0;
2803   /* Assume the 'q' and 'M chars have been stripped.  */
2804   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2805   /* done parse past here */
2806   pkt = unpack_byte (pkt, &count);      /* count field */
2807   pkt = unpack_nibble (pkt, &done);
2808   /* The first threadid is the argument threadid.  */
2809   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2810   while ((count-- > 0) && (pkt < limit))
2811     {
2812       pkt = unpack_threadid (pkt, resultlist++);
2813       if (resultcount++ >= result_limit)
2814         break;
2815     }
2816   if (doneflag)
2817     *doneflag = done;
2818   return resultcount;
2819 }
2820
2821 /* Fetch the next batch of threads from the remote.  Returns -1 if the
2822    qL packet is not supported, 0 on error and 1 on success.  */
2823
2824 static int
2825 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2826                        int *done, int *result_count, threadref *threadlist)
2827 {
2828   struct remote_state *rs = get_remote_state ();
2829   int result = 1;
2830
2831   /* Trancate result limit to be smaller than the packet size.  */
2832   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2833       >= get_remote_packet_size ())
2834     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2835
2836   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2837   putpkt (rs->buf);
2838   getpkt (&rs->buf, &rs->buf_size, 0);
2839   if (*rs->buf == '\0')
2840     {
2841       /* Packet not supported.  */
2842       return -1;
2843     }
2844
2845   *result_count =
2846     parse_threadlist_response (rs->buf + 2, result_limit,
2847                                &rs->echo_nextthread, threadlist, done);
2848
2849   if (!threadmatch (&rs->echo_nextthread, nextthread))
2850     {
2851       /* FIXME: This is a good reason to drop the packet.  */
2852       /* Possably, there is a duplicate response.  */
2853       /* Possabilities :
2854          retransmit immediatly - race conditions
2855          retransmit after timeout - yes
2856          exit
2857          wait for packet, then exit
2858        */
2859       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2860       return 0;                 /* I choose simply exiting.  */
2861     }
2862   if (*result_count <= 0)
2863     {
2864       if (*done != 1)
2865         {
2866           warning (_("RMT ERROR : failed to get remote thread list."));
2867           result = 0;
2868         }
2869       return result;            /* break; */
2870     }
2871   if (*result_count > result_limit)
2872     {
2873       *result_count = 0;
2874       warning (_("RMT ERROR: threadlist response longer than requested."));
2875       return 0;
2876     }
2877   return result;
2878 }
2879
2880 /* Fetch the list of remote threads, with the qL packet, and call
2881    STEPFUNCTION for each thread found.  Stops iterating and returns 1
2882    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
2883    STEPFUNCTION returns false.  If the packet is not supported,
2884    returns -1.  */
2885
2886 static int
2887 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2888                             int looplimit)
2889 {
2890   struct remote_state *rs = get_remote_state ();
2891   int done, i, result_count;
2892   int startflag = 1;
2893   int result = 1;
2894   int loopcount = 0;
2895
2896   done = 0;
2897   while (!done)
2898     {
2899       if (loopcount++ > looplimit)
2900         {
2901           result = 0;
2902           warning (_("Remote fetch threadlist -infinite loop-."));
2903           break;
2904         }
2905       result = remote_get_threadlist (startflag, &rs->nextthread,
2906                                       MAXTHREADLISTRESULTS,
2907                                       &done, &result_count,
2908                                       rs->resultthreadlist);
2909       if (result <= 0)
2910         break;
2911       /* Clear for later iterations.  */
2912       startflag = 0;
2913       /* Setup to resume next batch of thread references, set nextthread.  */
2914       if (result_count >= 1)
2915         copy_threadref (&rs->nextthread,
2916                         &rs->resultthreadlist[result_count - 1]);
2917       i = 0;
2918       while (result_count--)
2919         {
2920           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2921             {
2922               result = 0;
2923               break;
2924             }
2925         }
2926     }
2927   return result;
2928 }
2929
2930 /* A thread found on the remote target.  */
2931
2932 typedef struct thread_item
2933 {
2934   /* The thread's PTID.  */
2935   ptid_t ptid;
2936
2937   /* The thread's extra info.  May be NULL.  */
2938   char *extra;
2939
2940   /* The thread's name.  May be NULL.  */
2941   char *name;
2942
2943   /* The core the thread was running on.  -1 if not known.  */
2944   int core;
2945 } thread_item_t;
2946 DEF_VEC_O(thread_item_t);
2947
2948 /* Context passed around to the various methods listing remote
2949    threads.  As new threads are found, they're added to the ITEMS
2950    vector.  */
2951
2952 struct threads_listing_context
2953 {
2954   /* The threads found on the remote target.  */
2955   VEC (thread_item_t) *items;
2956 };
2957
2958 /* Discard the contents of the constructed thread listing context.  */
2959
2960 static void
2961 clear_threads_listing_context (void *p)
2962 {
2963   struct threads_listing_context *context
2964     = (struct threads_listing_context *) p;
2965   int i;
2966   struct thread_item *item;
2967
2968   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2969     {
2970       xfree (item->extra);
2971       xfree (item->name);
2972     }
2973
2974   VEC_free (thread_item_t, context->items);
2975 }
2976
2977 /* Remove the thread specified as the related_pid field of WS
2978    from the CONTEXT list.  */
2979
2980 static void
2981 threads_listing_context_remove (struct target_waitstatus *ws,
2982                                 struct threads_listing_context *context)
2983 {
2984   struct thread_item *item;
2985   int i;
2986   ptid_t child_ptid = ws->value.related_pid;
2987
2988   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2989     {
2990       if (ptid_equal (item->ptid, child_ptid))
2991         {
2992           VEC_ordered_remove (thread_item_t, context->items, i);
2993           break;
2994         }
2995     }
2996 }
2997
2998 static int
2999 remote_newthread_step (threadref *ref, void *data)
3000 {
3001   struct threads_listing_context *context
3002     = (struct threads_listing_context *) data;
3003   struct thread_item item;
3004   int pid = ptid_get_pid (inferior_ptid);
3005
3006   item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3007   item.core = -1;
3008   item.name = NULL;
3009   item.extra = NULL;
3010
3011   VEC_safe_push (thread_item_t, context->items, &item);
3012
3013   return 1;                     /* continue iterator */
3014 }
3015
3016 #define CRAZY_MAX_THREADS 1000
3017
3018 static ptid_t
3019 remote_current_thread (ptid_t oldpid)
3020 {
3021   struct remote_state *rs = get_remote_state ();
3022
3023   putpkt ("qC");
3024   getpkt (&rs->buf, &rs->buf_size, 0);
3025   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3026     {
3027       char *obuf;
3028       ptid_t result;
3029
3030       result = read_ptid (&rs->buf[2], &obuf);
3031       if (*obuf != '\0' && remote_debug)
3032         fprintf_unfiltered (gdb_stdlog,
3033                             "warning: garbage in qC reply\n");
3034
3035       return result;
3036     }
3037   else
3038     return oldpid;
3039 }
3040
3041 /* List remote threads using the deprecated qL packet.  */
3042
3043 static int
3044 remote_get_threads_with_ql (struct target_ops *ops,
3045                             struct threads_listing_context *context)
3046 {
3047   if (remote_threadlist_iterator (remote_newthread_step, context,
3048                                   CRAZY_MAX_THREADS) >= 0)
3049     return 1;
3050
3051   return 0;
3052 }
3053
3054 #if defined(HAVE_LIBEXPAT)
3055
3056 static void
3057 start_thread (struct gdb_xml_parser *parser,
3058               const struct gdb_xml_element *element,
3059               void *user_data, VEC(gdb_xml_value_s) *attributes)
3060 {
3061   struct threads_listing_context *data
3062     = (struct threads_listing_context *) user_data;
3063
3064   struct thread_item item;
3065   char *id;
3066   struct gdb_xml_value *attr;
3067
3068   id = (char *) xml_find_attribute (attributes, "id")->value;
3069   item.ptid = read_ptid (id, NULL);
3070
3071   attr = xml_find_attribute (attributes, "core");
3072   if (attr != NULL)
3073     item.core = *(ULONGEST *) attr->value;
3074   else
3075     item.core = -1;
3076
3077   attr = xml_find_attribute (attributes, "name");
3078   item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3079
3080   item.extra = 0;
3081
3082   VEC_safe_push (thread_item_t, data->items, &item);
3083 }
3084
3085 static void
3086 end_thread (struct gdb_xml_parser *parser,
3087             const struct gdb_xml_element *element,
3088             void *user_data, const char *body_text)
3089 {
3090   struct threads_listing_context *data
3091     = (struct threads_listing_context *) user_data;
3092
3093   if (body_text && *body_text)
3094     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3095 }
3096
3097 const struct gdb_xml_attribute thread_attributes[] = {
3098   { "id", GDB_XML_AF_NONE, NULL, NULL },
3099   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3100   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3101   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3102 };
3103
3104 const struct gdb_xml_element thread_children[] = {
3105   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3106 };
3107
3108 const struct gdb_xml_element threads_children[] = {
3109   { "thread", thread_attributes, thread_children,
3110     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3111     start_thread, end_thread },
3112   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3113 };
3114
3115 const struct gdb_xml_element threads_elements[] = {
3116   { "threads", NULL, threads_children,
3117     GDB_XML_EF_NONE, NULL, NULL },
3118   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3119 };
3120
3121 #endif
3122
3123 /* List remote threads using qXfer:threads:read.  */
3124
3125 static int
3126 remote_get_threads_with_qxfer (struct target_ops *ops,
3127                                struct threads_listing_context *context)
3128 {
3129 #if defined(HAVE_LIBEXPAT)
3130   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3131     {
3132       char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3133       struct cleanup *back_to = make_cleanup (xfree, xml);
3134
3135       if (xml != NULL && *xml != '\0')
3136         {
3137           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3138                                threads_elements, xml, context);
3139         }
3140
3141       do_cleanups (back_to);
3142       return 1;
3143     }
3144 #endif
3145
3146   return 0;
3147 }
3148
3149 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3150
3151 static int
3152 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3153                                      struct threads_listing_context *context)
3154 {
3155   struct remote_state *rs = get_remote_state ();
3156
3157   if (rs->use_threadinfo_query)
3158     {
3159       char *bufp;
3160
3161       putpkt ("qfThreadInfo");
3162       getpkt (&rs->buf, &rs->buf_size, 0);
3163       bufp = rs->buf;
3164       if (bufp[0] != '\0')              /* q packet recognized */
3165         {
3166           while (*bufp++ == 'm')        /* reply contains one or more TID */
3167             {
3168               do
3169                 {
3170                   struct thread_item item;
3171
3172                   item.ptid = read_ptid (bufp, &bufp);
3173                   item.core = -1;
3174                   item.name = NULL;
3175                   item.extra = NULL;
3176
3177                   VEC_safe_push (thread_item_t, context->items, &item);
3178                 }
3179               while (*bufp++ == ',');   /* comma-separated list */
3180               putpkt ("qsThreadInfo");
3181               getpkt (&rs->buf, &rs->buf_size, 0);
3182               bufp = rs->buf;
3183             }
3184           return 1;
3185         }
3186       else
3187         {
3188           /* Packet not recognized.  */
3189           rs->use_threadinfo_query = 0;
3190         }
3191     }
3192
3193   return 0;
3194 }
3195
3196 /* Implement the to_update_thread_list function for the remote
3197    targets.  */
3198
3199 static void
3200 remote_update_thread_list (struct target_ops *ops)
3201 {
3202   struct threads_listing_context context;
3203   struct cleanup *old_chain;
3204   int got_list = 0;
3205
3206   context.items = NULL;
3207   old_chain = make_cleanup (clear_threads_listing_context, &context);
3208
3209   /* We have a few different mechanisms to fetch the thread list.  Try
3210      them all, starting with the most preferred one first, falling
3211      back to older methods.  */
3212   if (remote_get_threads_with_qxfer (ops, &context)
3213       || remote_get_threads_with_qthreadinfo (ops, &context)
3214       || remote_get_threads_with_ql (ops, &context))
3215     {
3216       int i;
3217       struct thread_item *item;
3218       struct thread_info *tp, *tmp;
3219
3220       got_list = 1;
3221
3222       if (VEC_empty (thread_item_t, context.items)
3223           && remote_thread_always_alive (ops, inferior_ptid))
3224         {
3225           /* Some targets don't really support threads, but still
3226              reply an (empty) thread list in response to the thread
3227              listing packets, instead of replying "packet not
3228              supported".  Exit early so we don't delete the main
3229              thread.  */
3230           do_cleanups (old_chain);
3231           return;
3232         }
3233
3234       /* CONTEXT now holds the current thread list on the remote
3235          target end.  Delete GDB-side threads no longer found on the
3236          target.  */
3237       ALL_THREADS_SAFE (tp, tmp)
3238         {
3239           for (i = 0;
3240                VEC_iterate (thread_item_t, context.items, i, item);
3241                ++i)
3242             {
3243               if (ptid_equal (item->ptid, tp->ptid))
3244                 break;
3245             }
3246
3247           if (i == VEC_length (thread_item_t, context.items))
3248             {
3249               /* Not found.  */
3250               delete_thread (tp->ptid);
3251             }
3252         }
3253
3254       /* Remove any unreported fork child threads from CONTEXT so
3255          that we don't interfere with follow fork, which is where
3256          creation of such threads is handled.  */
3257       remove_new_fork_children (&context);
3258
3259       /* And now add threads we don't know about yet to our list.  */
3260       for (i = 0;
3261            VEC_iterate (thread_item_t, context.items, i, item);
3262            ++i)
3263         {
3264           if (!ptid_equal (item->ptid, null_ptid))
3265             {
3266               struct private_thread_info *info;
3267               /* In non-stop mode, we assume new found threads are
3268                  executing until proven otherwise with a stop reply.
3269                  In all-stop, we can only get here if all threads are
3270                  stopped.  */
3271               int executing = target_is_non_stop_p () ? 1 : 0;
3272
3273               remote_notice_new_inferior (item->ptid, executing);
3274
3275               info = demand_private_info (item->ptid);
3276               info->core = item->core;
3277               info->extra = item->extra;
3278               item->extra = NULL;
3279               info->name = item->name;
3280               item->name = NULL;
3281             }
3282         }
3283     }
3284
3285   if (!got_list)
3286     {
3287       /* If no thread listing method is supported, then query whether
3288          each known thread is alive, one by one, with the T packet.
3289          If the target doesn't support threads at all, then this is a
3290          no-op.  See remote_thread_alive.  */
3291       prune_threads ();
3292     }
3293
3294   do_cleanups (old_chain);
3295 }
3296
3297 /*
3298  * Collect a descriptive string about the given thread.
3299  * The target may say anything it wants to about the thread
3300  * (typically info about its blocked / runnable state, name, etc.).
3301  * This string will appear in the info threads display.
3302  *
3303  * Optional: targets are not required to implement this function.
3304  */
3305
3306 static char *
3307 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3308 {
3309   struct remote_state *rs = get_remote_state ();
3310   int result;
3311   int set;
3312   threadref id;
3313   struct gdb_ext_thread_info threadinfo;
3314   static char display_buf[100]; /* arbitrary...  */
3315   int n = 0;                    /* position in display_buf */
3316
3317   if (rs->remote_desc == 0)             /* paranoia */
3318     internal_error (__FILE__, __LINE__,
3319                     _("remote_threads_extra_info"));
3320
3321   if (ptid_equal (tp->ptid, magic_null_ptid)
3322       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3323     /* This is the main thread which was added by GDB.  The remote
3324        server doesn't know about it.  */
3325     return NULL;
3326
3327   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3328     {
3329       struct thread_info *info = find_thread_ptid (tp->ptid);
3330
3331       if (info && info->priv)
3332         return info->priv->extra;
3333       else
3334         return NULL;
3335     }
3336
3337   if (rs->use_threadextra_query)
3338     {
3339       char *b = rs->buf;
3340       char *endb = rs->buf + get_remote_packet_size ();
3341
3342       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3343       b += strlen (b);
3344       write_ptid (b, endb, tp->ptid);
3345
3346       putpkt (rs->buf);
3347       getpkt (&rs->buf, &rs->buf_size, 0);
3348       if (rs->buf[0] != 0)
3349         {
3350           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3351           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3352           display_buf [result] = '\0';
3353           return display_buf;
3354         }
3355     }
3356
3357   /* If the above query fails, fall back to the old method.  */
3358   rs->use_threadextra_query = 0;
3359   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3360     | TAG_MOREDISPLAY | TAG_DISPLAY;
3361   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3362   if (remote_get_threadinfo (&id, set, &threadinfo))
3363     if (threadinfo.active)
3364       {
3365         if (*threadinfo.shortname)
3366           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3367                           " Name: %s,", threadinfo.shortname);
3368         if (*threadinfo.display)
3369           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3370                           " State: %s,", threadinfo.display);
3371         if (*threadinfo.more_display)
3372           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3373                           " Priority: %s", threadinfo.more_display);
3374
3375         if (n > 0)
3376           {
3377             /* For purely cosmetic reasons, clear up trailing commas.  */
3378             if (',' == display_buf[n-1])
3379               display_buf[n-1] = ' ';
3380             return display_buf;
3381           }
3382       }
3383   return NULL;
3384 }
3385 \f
3386
3387 static int
3388 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3389                                     struct static_tracepoint_marker *marker)
3390 {
3391   struct remote_state *rs = get_remote_state ();
3392   char *p = rs->buf;
3393
3394   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3395   p += strlen (p);
3396   p += hexnumstr (p, addr);
3397   putpkt (rs->buf);
3398   getpkt (&rs->buf, &rs->buf_size, 0);
3399   p = rs->buf;
3400
3401   if (*p == 'E')
3402     error (_("Remote failure reply: %s"), p);
3403
3404   if (*p++ == 'm')
3405     {
3406       parse_static_tracepoint_marker_definition (p, &p, marker);
3407       return 1;
3408     }
3409
3410   return 0;
3411 }
3412
3413 static VEC(static_tracepoint_marker_p) *
3414 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3415                                            const char *strid)
3416 {
3417   struct remote_state *rs = get_remote_state ();
3418   VEC(static_tracepoint_marker_p) *markers = NULL;
3419   struct static_tracepoint_marker *marker = NULL;
3420   struct cleanup *old_chain;
3421   char *p;
3422
3423   /* Ask for a first packet of static tracepoint marker
3424      definition.  */
3425   putpkt ("qTfSTM");
3426   getpkt (&rs->buf, &rs->buf_size, 0);
3427   p = rs->buf;
3428   if (*p == 'E')
3429     error (_("Remote failure reply: %s"), p);
3430
3431   old_chain = make_cleanup (free_current_marker, &marker);
3432
3433   while (*p++ == 'm')
3434     {
3435       if (marker == NULL)
3436         marker = XCNEW (struct static_tracepoint_marker);
3437
3438       do
3439         {
3440           parse_static_tracepoint_marker_definition (p, &p, marker);
3441
3442           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3443             {
3444               VEC_safe_push (static_tracepoint_marker_p,
3445                              markers, marker);
3446               marker = NULL;
3447             }
3448           else
3449             {
3450               release_static_tracepoint_marker (marker);
3451               memset (marker, 0, sizeof (*marker));
3452             }
3453         }
3454       while (*p++ == ',');      /* comma-separated list */
3455       /* Ask for another packet of static tracepoint definition.  */
3456       putpkt ("qTsSTM");
3457       getpkt (&rs->buf, &rs->buf_size, 0);
3458       p = rs->buf;
3459     }
3460
3461   do_cleanups (old_chain);
3462   return markers;
3463 }
3464
3465 \f
3466 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3467
3468 static ptid_t
3469 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3470 {
3471   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3472 }
3473 \f
3474
3475 /* Restart the remote side; this is an extended protocol operation.  */
3476
3477 static void
3478 extended_remote_restart (void)
3479 {
3480   struct remote_state *rs = get_remote_state ();
3481
3482   /* Send the restart command; for reasons I don't understand the
3483      remote side really expects a number after the "R".  */
3484   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3485   putpkt (rs->buf);
3486
3487   remote_fileio_reset ();
3488 }
3489 \f
3490 /* Clean up connection to a remote debugger.  */
3491
3492 static void
3493 remote_close (struct target_ops *self)
3494 {
3495   struct remote_state *rs = get_remote_state ();
3496
3497   if (rs->remote_desc == NULL)
3498     return; /* already closed */
3499
3500   /* Make sure we leave stdin registered in the event loop, and we
3501      don't leave the async SIGINT signal handler installed.  */
3502   remote_terminal_ours (self);
3503
3504   serial_close (rs->remote_desc);
3505   rs->remote_desc = NULL;
3506
3507   /* We don't have a connection to the remote stub anymore.  Get rid
3508      of all the inferiors and their threads we were controlling.
3509      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3510      will be unable to find the thread corresponding to (pid, 0, 0).  */
3511   inferior_ptid = null_ptid;
3512   discard_all_inferiors ();
3513
3514   /* We are closing the remote target, so we should discard
3515      everything of this target.  */
3516   discard_pending_stop_replies_in_queue (rs);
3517
3518   if (remote_async_inferior_event_token)
3519     delete_async_event_handler (&remote_async_inferior_event_token);
3520
3521   remote_notif_state_xfree (rs->notif_state);
3522
3523   trace_reset_local_state ();
3524 }
3525
3526 /* Query the remote side for the text, data and bss offsets.  */
3527
3528 static void
3529 get_offsets (void)
3530 {
3531   struct remote_state *rs = get_remote_state ();
3532   char *buf;
3533   char *ptr;
3534   int lose, num_segments = 0, do_sections, do_segments;
3535   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3536   struct section_offsets *offs;
3537   struct symfile_segment_data *data;
3538
3539   if (symfile_objfile == NULL)
3540     return;
3541
3542   putpkt ("qOffsets");
3543   getpkt (&rs->buf, &rs->buf_size, 0);
3544   buf = rs->buf;
3545
3546   if (buf[0] == '\000')
3547     return;                     /* Return silently.  Stub doesn't support
3548                                    this command.  */
3549   if (buf[0] == 'E')
3550     {
3551       warning (_("Remote failure reply: %s"), buf);
3552       return;
3553     }
3554
3555   /* Pick up each field in turn.  This used to be done with scanf, but
3556      scanf will make trouble if CORE_ADDR size doesn't match
3557      conversion directives correctly.  The following code will work
3558      with any size of CORE_ADDR.  */
3559   text_addr = data_addr = bss_addr = 0;
3560   ptr = buf;
3561   lose = 0;
3562
3563   if (startswith (ptr, "Text="))
3564     {
3565       ptr += 5;
3566       /* Don't use strtol, could lose on big values.  */
3567       while (*ptr && *ptr != ';')
3568         text_addr = (text_addr << 4) + fromhex (*ptr++);
3569
3570       if (startswith (ptr, ";Data="))
3571         {
3572           ptr += 6;
3573           while (*ptr && *ptr != ';')
3574             data_addr = (data_addr << 4) + fromhex (*ptr++);
3575         }
3576       else
3577         lose = 1;
3578
3579       if (!lose && startswith (ptr, ";Bss="))
3580         {
3581           ptr += 5;
3582           while (*ptr && *ptr != ';')
3583             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3584
3585           if (bss_addr != data_addr)
3586             warning (_("Target reported unsupported offsets: %s"), buf);
3587         }
3588       else
3589         lose = 1;
3590     }
3591   else if (startswith (ptr, "TextSeg="))
3592     {
3593       ptr += 8;
3594       /* Don't use strtol, could lose on big values.  */
3595       while (*ptr && *ptr != ';')
3596         text_addr = (text_addr << 4) + fromhex (*ptr++);
3597       num_segments = 1;
3598
3599       if (startswith (ptr, ";DataSeg="))
3600         {
3601           ptr += 9;
3602           while (*ptr && *ptr != ';')
3603             data_addr = (data_addr << 4) + fromhex (*ptr++);
3604           num_segments++;
3605         }
3606     }
3607   else
3608     lose = 1;
3609
3610   if (lose)
3611     error (_("Malformed response to offset query, %s"), buf);
3612   else if (*ptr != '\0')
3613     warning (_("Target reported unsupported offsets: %s"), buf);
3614
3615   offs = ((struct section_offsets *)
3616           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3617   memcpy (offs, symfile_objfile->section_offsets,
3618           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3619
3620   data = get_symfile_segment_data (symfile_objfile->obfd);
3621   do_segments = (data != NULL);
3622   do_sections = num_segments == 0;
3623
3624   if (num_segments > 0)
3625     {
3626       segments[0] = text_addr;
3627       segments[1] = data_addr;
3628     }
3629   /* If we have two segments, we can still try to relocate everything
3630      by assuming that the .text and .data offsets apply to the whole
3631      text and data segments.  Convert the offsets given in the packet
3632      to base addresses for symfile_map_offsets_to_segments.  */
3633   else if (data && data->num_segments == 2)
3634     {
3635       segments[0] = data->segment_bases[0] + text_addr;
3636       segments[1] = data->segment_bases[1] + data_addr;
3637       num_segments = 2;
3638     }
3639   /* If the object file has only one segment, assume that it is text
3640      rather than data; main programs with no writable data are rare,
3641      but programs with no code are useless.  Of course the code might
3642      have ended up in the data segment... to detect that we would need
3643      the permissions here.  */
3644   else if (data && data->num_segments == 1)
3645     {
3646       segments[0] = data->segment_bases[0] + text_addr;
3647       num_segments = 1;
3648     }
3649   /* There's no way to relocate by segment.  */
3650   else
3651     do_segments = 0;
3652
3653   if (do_segments)
3654     {
3655       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3656                                                  offs, num_segments, segments);
3657
3658       if (ret == 0 && !do_sections)
3659         error (_("Can not handle qOffsets TextSeg "
3660                  "response with this symbol file"));
3661
3662       if (ret > 0)
3663         do_sections = 0;
3664     }
3665
3666   if (data)
3667     free_symfile_segment_data (data);
3668
3669   if (do_sections)
3670     {
3671       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3672
3673       /* This is a temporary kludge to force data and bss to use the
3674          same offsets because that's what nlmconv does now.  The real
3675          solution requires changes to the stub and remote.c that I
3676          don't have time to do right now.  */
3677
3678       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3679       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3680     }
3681
3682   objfile_relocate (symfile_objfile, offs);
3683 }
3684
3685 /* Send interrupt_sequence to remote target.  */
3686 static void
3687 send_interrupt_sequence (void)
3688 {
3689   struct remote_state *rs = get_remote_state ();
3690
3691   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3692     remote_serial_write ("\x03", 1);
3693   else if (interrupt_sequence_mode == interrupt_sequence_break)
3694     serial_send_break (rs->remote_desc);
3695   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3696     {
3697       serial_send_break (rs->remote_desc);
3698       remote_serial_write ("g", 1);
3699     }
3700   else
3701     internal_error (__FILE__, __LINE__,
3702                     _("Invalid value for interrupt_sequence_mode: %s."),
3703                     interrupt_sequence_mode);
3704 }
3705
3706
3707 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3708    and extract the PTID.  Returns NULL_PTID if not found.  */
3709
3710 static ptid_t
3711 stop_reply_extract_thread (char *stop_reply)
3712 {
3713   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3714     {
3715       char *p;
3716
3717       /* Txx r:val ; r:val (...)  */
3718       p = &stop_reply[3];
3719
3720       /* Look for "register" named "thread".  */
3721       while (*p != '\0')
3722         {
3723           char *p1;
3724
3725           p1 = strchr (p, ':');
3726           if (p1 == NULL)
3727             return null_ptid;
3728
3729           if (strncmp (p, "thread", p1 - p) == 0)
3730             return read_ptid (++p1, &p);
3731
3732           p1 = strchr (p, ';');
3733           if (p1 == NULL)
3734             return null_ptid;
3735           p1++;
3736
3737           p = p1;
3738         }
3739     }
3740
3741   return null_ptid;
3742 }
3743
3744 /* Determine the remote side's current thread.  If we have a stop
3745    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3746    "thread" register we can extract the current thread from.  If not,
3747    ask the remote which is the current thread with qC.  The former
3748    method avoids a roundtrip.  */
3749
3750 static ptid_t
3751 get_current_thread (char *wait_status)
3752 {
3753   ptid_t ptid = null_ptid;
3754
3755   /* Note we don't use remote_parse_stop_reply as that makes use of
3756      the target architecture, which we haven't yet fully determined at
3757      this point.  */
3758   if (wait_status != NULL)
3759     ptid = stop_reply_extract_thread (wait_status);
3760   if (ptid_equal (ptid, null_ptid))
3761     ptid = remote_current_thread (inferior_ptid);
3762
3763   return ptid;
3764 }
3765
3766 /* Query the remote target for which is the current thread/process,
3767    add it to our tables, and update INFERIOR_PTID.  The caller is
3768    responsible for setting the state such that the remote end is ready
3769    to return the current thread.
3770
3771    This function is called after handling the '?' or 'vRun' packets,
3772    whose response is a stop reply from which we can also try
3773    extracting the thread.  If the target doesn't support the explicit
3774    qC query, we infer the current thread from that stop reply, passed
3775    in in WAIT_STATUS, which may be NULL.  */
3776
3777 static void
3778 add_current_inferior_and_thread (char *wait_status)
3779 {
3780   struct remote_state *rs = get_remote_state ();
3781   int fake_pid_p = 0;
3782   ptid_t ptid;
3783
3784   inferior_ptid = null_ptid;
3785
3786   /* Now, if we have thread information, update inferior_ptid.  */
3787   ptid = get_current_thread (wait_status);
3788
3789   if (!ptid_equal (ptid, null_ptid))
3790     {
3791       if (!remote_multi_process_p (rs))
3792         fake_pid_p = 1;
3793
3794       inferior_ptid = ptid;
3795     }
3796   else
3797     {
3798       /* Without this, some commands which require an active target
3799          (such as kill) won't work.  This variable serves (at least)
3800          double duty as both the pid of the target process (if it has
3801          such), and as a flag indicating that a target is active.  */
3802       inferior_ptid = magic_null_ptid;
3803       fake_pid_p = 1;
3804     }
3805
3806   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3807
3808   /* Add the main thread.  */
3809   add_thread_silent (inferior_ptid);
3810 }
3811
3812 /* Print info about a thread that was found already stopped on
3813    connection.  */
3814
3815 static void
3816 print_one_stopped_thread (struct thread_info *thread)
3817 {
3818   struct target_waitstatus *ws = &thread->suspend.waitstatus;
3819
3820   switch_to_thread (thread->ptid);
3821   stop_pc = get_frame_pc (get_current_frame ());
3822   set_current_sal_from_frame (get_current_frame ());
3823
3824   thread->suspend.waitstatus_pending_p = 0;
3825
3826   if (ws->kind == TARGET_WAITKIND_STOPPED)
3827     {
3828       enum gdb_signal sig = ws->value.sig;
3829
3830       if (signal_print_state (sig))
3831         observer_notify_signal_received (sig);
3832     }
3833   observer_notify_normal_stop (NULL, 1);
3834 }
3835
3836 /* Process all initial stop replies the remote side sent in response
3837    to the ? packet.  These indicate threads that were already stopped
3838    on initial connection.  We mark these threads as stopped and print
3839    their current frame before giving the user the prompt.  */
3840
3841 static void
3842 process_initial_stop_replies (int from_tty)
3843 {
3844   int pending_stop_replies = stop_reply_queue_length ();
3845   struct inferior *inf;
3846   struct thread_info *thread;
3847   struct thread_info *selected = NULL;
3848   struct thread_info *lowest_stopped = NULL;
3849   struct thread_info *first = NULL;
3850
3851   /* Consume the initial pending events.  */
3852   while (pending_stop_replies-- > 0)
3853     {
3854       ptid_t waiton_ptid = minus_one_ptid;
3855       ptid_t event_ptid;
3856       struct target_waitstatus ws;
3857       int ignore_event = 0;
3858       struct thread_info *thread;
3859
3860       memset (&ws, 0, sizeof (ws));
3861       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3862       if (remote_debug)
3863         print_target_wait_results (waiton_ptid, event_ptid, &ws);
3864
3865       switch (ws.kind)
3866         {
3867         case TARGET_WAITKIND_IGNORE:
3868         case TARGET_WAITKIND_NO_RESUMED:
3869         case TARGET_WAITKIND_SIGNALLED:
3870         case TARGET_WAITKIND_EXITED:
3871           /* We shouldn't see these, but if we do, just ignore.  */
3872           if (remote_debug)
3873             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3874           ignore_event = 1;
3875           break;
3876
3877         case TARGET_WAITKIND_EXECD:
3878           xfree (ws.value.execd_pathname);
3879           break;
3880         default:
3881           break;
3882         }
3883
3884       if (ignore_event)
3885         continue;
3886
3887       thread = find_thread_ptid (event_ptid);
3888
3889       if (ws.kind == TARGET_WAITKIND_STOPPED)
3890         {
3891           enum gdb_signal sig = ws.value.sig;
3892
3893           /* Stubs traditionally report SIGTRAP as initial signal,
3894              instead of signal 0.  Suppress it.  */
3895           if (sig == GDB_SIGNAL_TRAP)
3896             sig = GDB_SIGNAL_0;
3897           thread->suspend.stop_signal = sig;
3898           ws.value.sig = sig;
3899         }
3900
3901       thread->suspend.waitstatus = ws;
3902
3903       if (ws.kind != TARGET_WAITKIND_STOPPED
3904           || ws.value.sig != GDB_SIGNAL_0)
3905         thread->suspend.waitstatus_pending_p = 1;
3906
3907       set_executing (event_ptid, 0);
3908       set_running (event_ptid, 0);
3909     }
3910
3911   /* "Notice" the new inferiors before anything related to
3912      registers/memory.  */
3913   ALL_INFERIORS (inf)
3914     {
3915       if (inf->pid == 0)
3916         continue;
3917
3918       inf->needs_setup = 1;
3919
3920       if (non_stop)
3921         {
3922           thread = any_live_thread_of_process (inf->pid);
3923           notice_new_inferior (thread->ptid,
3924                                thread->state == THREAD_RUNNING,
3925                                from_tty);
3926         }
3927     }
3928
3929   /* If all-stop on top of non-stop, pause all threads.  Note this
3930      records the threads' stop pc, so must be done after "noticing"
3931      the inferiors.  */
3932   if (!non_stop)
3933     {
3934       stop_all_threads ();
3935
3936       /* If all threads of an inferior were already stopped, we
3937          haven't setup the inferior yet.  */
3938       ALL_INFERIORS (inf)
3939         {
3940           if (inf->pid == 0)
3941             continue;
3942
3943           if (inf->needs_setup)
3944             {
3945               thread = any_live_thread_of_process (inf->pid);
3946               switch_to_thread_no_regs (thread);
3947               setup_inferior (0);
3948             }
3949         }
3950     }
3951
3952   /* Now go over all threads that are stopped, and print their current
3953      frame.  If all-stop, then if there's a signalled thread, pick
3954      that as current.  */
3955   ALL_NON_EXITED_THREADS (thread)
3956     {
3957       if (first == NULL)
3958         first = thread;
3959
3960       if (!non_stop)
3961         set_running (thread->ptid, 0);
3962       else if (thread->state != THREAD_STOPPED)
3963         continue;
3964
3965       if (selected == NULL
3966           && thread->suspend.waitstatus_pending_p)
3967         selected = thread;
3968
3969       if (lowest_stopped == NULL
3970           || thread->inf->num < lowest_stopped->inf->num
3971           || thread->per_inf_num < lowest_stopped->per_inf_num)
3972         lowest_stopped = thread;
3973
3974       if (non_stop)
3975         print_one_stopped_thread (thread);
3976     }
3977
3978   /* In all-stop, we only print the status of one thread, and leave
3979      others with their status pending.  */
3980   if (!non_stop)
3981     {
3982       thread = selected;
3983       if (thread == NULL)
3984         thread = lowest_stopped;
3985       if (thread == NULL)
3986         thread = first;
3987
3988       print_one_stopped_thread (thread);
3989     }
3990
3991   /* For "info program".  */
3992   thread = inferior_thread ();
3993   if (thread->state == THREAD_STOPPED)
3994     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
3995 }
3996
3997 static void
3998 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3999 {
4000   struct remote_state *rs = get_remote_state ();
4001   struct packet_config *noack_config;
4002   char *wait_status = NULL;
4003
4004   immediate_quit++;             /* Allow user to interrupt it.  */
4005   QUIT;
4006
4007   if (interrupt_on_connect)
4008     send_interrupt_sequence ();
4009
4010   /* Ack any packet which the remote side has already sent.  */
4011   serial_write (rs->remote_desc, "+", 1);
4012
4013   /* Signal other parts that we're going through the initial setup,
4014      and so things may not be stable yet.  */
4015   rs->starting_up = 1;
4016
4017   /* The first packet we send to the target is the optional "supported
4018      packets" request.  If the target can answer this, it will tell us
4019      which later probes to skip.  */
4020   remote_query_supported ();
4021
4022   /* If the stub wants to get a QAllow, compose one and send it.  */
4023   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4024     remote_set_permissions (target);
4025
4026   /* Next, we possibly activate noack mode.
4027
4028      If the QStartNoAckMode packet configuration is set to AUTO,
4029      enable noack mode if the stub reported a wish for it with
4030      qSupported.
4031
4032      If set to TRUE, then enable noack mode even if the stub didn't
4033      report it in qSupported.  If the stub doesn't reply OK, the
4034      session ends with an error.
4035
4036      If FALSE, then don't activate noack mode, regardless of what the
4037      stub claimed should be the default with qSupported.  */
4038
4039   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4040   if (packet_config_support (noack_config) != PACKET_DISABLE)
4041     {
4042       putpkt ("QStartNoAckMode");
4043       getpkt (&rs->buf, &rs->buf_size, 0);
4044       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4045         rs->noack_mode = 1;
4046     }
4047
4048   if (extended_p)
4049     {
4050       /* Tell the remote that we are using the extended protocol.  */
4051       putpkt ("!");
4052       getpkt (&rs->buf, &rs->buf_size, 0);
4053     }
4054
4055   /* Let the target know which signals it is allowed to pass down to
4056      the program.  */
4057   update_signals_program_target ();
4058
4059   /* Next, if the target can specify a description, read it.  We do
4060      this before anything involving memory or registers.  */
4061   target_find_description ();
4062
4063   /* Next, now that we know something about the target, update the
4064      address spaces in the program spaces.  */
4065   update_address_spaces ();
4066
4067   /* On OSs where the list of libraries is global to all
4068      processes, we fetch them early.  */
4069   if (gdbarch_has_global_solist (target_gdbarch ()))
4070     solib_add (NULL, from_tty, target, auto_solib_add);
4071
4072   if (target_is_non_stop_p ())
4073     {
4074       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4075         error (_("Non-stop mode requested, but remote "
4076                  "does not support non-stop"));
4077
4078       putpkt ("QNonStop:1");
4079       getpkt (&rs->buf, &rs->buf_size, 0);
4080
4081       if (strcmp (rs->buf, "OK") != 0)
4082         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4083
4084       /* Find about threads and processes the stub is already
4085          controlling.  We default to adding them in the running state.
4086          The '?' query below will then tell us about which threads are
4087          stopped.  */
4088       remote_update_thread_list (target);
4089     }
4090   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4091     {
4092       /* Don't assume that the stub can operate in all-stop mode.
4093          Request it explicitly.  */
4094       putpkt ("QNonStop:0");
4095       getpkt (&rs->buf, &rs->buf_size, 0);
4096
4097       if (strcmp (rs->buf, "OK") != 0)
4098         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4099     }
4100
4101   /* Upload TSVs regardless of whether the target is running or not.  The
4102      remote stub, such as GDBserver, may have some predefined or builtin
4103      TSVs, even if the target is not running.  */
4104   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4105     {
4106       struct uploaded_tsv *uploaded_tsvs = NULL;
4107
4108       remote_upload_trace_state_variables (target, &uploaded_tsvs);
4109       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4110     }
4111
4112   /* Check whether the target is running now.  */
4113   putpkt ("?");
4114   getpkt (&rs->buf, &rs->buf_size, 0);
4115
4116   if (!target_is_non_stop_p ())
4117     {
4118       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4119         {
4120           if (!extended_p)
4121             error (_("The target is not running (try extended-remote?)"));
4122
4123           /* We're connected, but not running.  Drop out before we
4124              call start_remote.  */
4125           rs->starting_up = 0;
4126           return;
4127         }
4128       else
4129         {
4130           /* Save the reply for later.  */
4131           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4132           strcpy (wait_status, rs->buf);
4133         }
4134
4135       /* Fetch thread list.  */
4136       target_update_thread_list ();
4137
4138       /* Let the stub know that we want it to return the thread.  */
4139       set_continue_thread (minus_one_ptid);
4140
4141       if (thread_count () == 0)
4142         {
4143           /* Target has no concept of threads at all.  GDB treats
4144              non-threaded target as single-threaded; add a main
4145              thread.  */
4146           add_current_inferior_and_thread (wait_status);
4147         }
4148       else
4149         {
4150           /* We have thread information; select the thread the target
4151              says should be current.  If we're reconnecting to a
4152              multi-threaded program, this will ideally be the thread
4153              that last reported an event before GDB disconnected.  */
4154           inferior_ptid = get_current_thread (wait_status);
4155           if (ptid_equal (inferior_ptid, null_ptid))
4156             {
4157               /* Odd... The target was able to list threads, but not
4158                  tell us which thread was current (no "thread"
4159                  register in T stop reply?).  Just pick the first
4160                  thread in the thread list then.  */
4161               
4162               if (remote_debug)
4163                 fprintf_unfiltered (gdb_stdlog,
4164                                     "warning: couldn't determine remote "
4165                                     "current thread; picking first in list.\n");
4166
4167               inferior_ptid = thread_list->ptid;
4168             }
4169         }
4170
4171       /* init_wait_for_inferior should be called before get_offsets in order
4172          to manage `inserted' flag in bp loc in a correct state.
4173          breakpoint_init_inferior, called from init_wait_for_inferior, set
4174          `inserted' flag to 0, while before breakpoint_re_set, called from
4175          start_remote, set `inserted' flag to 1.  In the initialization of
4176          inferior, breakpoint_init_inferior should be called first, and then
4177          breakpoint_re_set can be called.  If this order is broken, state of
4178          `inserted' flag is wrong, and cause some problems on breakpoint
4179          manipulation.  */
4180       init_wait_for_inferior ();
4181
4182       get_offsets ();           /* Get text, data & bss offsets.  */
4183
4184       /* If we could not find a description using qXfer, and we know
4185          how to do it some other way, try again.  This is not
4186          supported for non-stop; it could be, but it is tricky if
4187          there are no stopped threads when we connect.  */
4188       if (remote_read_description_p (target)
4189           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4190         {
4191           target_clear_description ();
4192           target_find_description ();
4193         }
4194
4195       /* Use the previously fetched status.  */
4196       gdb_assert (wait_status != NULL);
4197       strcpy (rs->buf, wait_status);
4198       rs->cached_wait_status = 1;
4199
4200       immediate_quit--;
4201       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4202     }
4203   else
4204     {
4205       /* Clear WFI global state.  Do this before finding about new
4206          threads and inferiors, and setting the current inferior.
4207          Otherwise we would clear the proceed status of the current
4208          inferior when we want its stop_soon state to be preserved
4209          (see notice_new_inferior).  */
4210       init_wait_for_inferior ();
4211
4212       /* In non-stop, we will either get an "OK", meaning that there
4213          are no stopped threads at this time; or, a regular stop
4214          reply.  In the latter case, there may be more than one thread
4215          stopped --- we pull them all out using the vStopped
4216          mechanism.  */
4217       if (strcmp (rs->buf, "OK") != 0)
4218         {
4219           struct notif_client *notif = &notif_client_stop;
4220
4221           /* remote_notif_get_pending_replies acks this one, and gets
4222              the rest out.  */
4223           rs->notif_state->pending_event[notif_client_stop.id]
4224             = remote_notif_parse (notif, rs->buf);
4225           remote_notif_get_pending_events (notif);
4226         }
4227
4228       if (thread_count () == 0)
4229         {
4230           if (!extended_p)
4231             error (_("The target is not running (try extended-remote?)"));
4232
4233           /* We're connected, but not running.  Drop out before we
4234              call start_remote.  */
4235           rs->starting_up = 0;
4236           return;
4237         }
4238
4239       /* In non-stop mode, any cached wait status will be stored in
4240          the stop reply queue.  */
4241       gdb_assert (wait_status == NULL);
4242
4243       /* Report all signals during attach/startup.  */
4244       remote_pass_signals (target, 0, NULL);
4245
4246       /* If there are already stopped threads, mark them stopped and
4247          report their stops before giving the prompt to the user.  */
4248       process_initial_stop_replies (from_tty);
4249
4250       if (target_can_async_p ())
4251         target_async (1);
4252     }
4253
4254   /* If we connected to a live target, do some additional setup.  */
4255   if (target_has_execution)
4256     {
4257       if (symfile_objfile)      /* No use without a symbol-file.  */
4258         remote_check_symbols ();
4259     }
4260
4261   /* Possibly the target has been engaged in a trace run started
4262      previously; find out where things are at.  */
4263   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4264     {
4265       struct uploaded_tp *uploaded_tps = NULL;
4266
4267       if (current_trace_status ()->running)
4268         printf_filtered (_("Trace is already running on the target.\n"));
4269
4270       remote_upload_tracepoints (target, &uploaded_tps);
4271
4272       merge_uploaded_tracepoints (&uploaded_tps);
4273     }
4274
4275   /* The thread and inferior lists are now synchronized with the
4276      target, our symbols have been relocated, and we're merged the
4277      target's tracepoints with ours.  We're done with basic start
4278      up.  */
4279   rs->starting_up = 0;
4280
4281   /* Maybe breakpoints are global and need to be inserted now.  */
4282   if (breakpoints_should_be_inserted_now ())
4283     insert_breakpoints ();
4284 }
4285
4286 /* Open a connection to a remote debugger.
4287    NAME is the filename used for communication.  */
4288
4289 static void
4290 remote_open (const char *name, int from_tty)
4291 {
4292   remote_open_1 (name, from_tty, &remote_ops, 0);
4293 }
4294
4295 /* Open a connection to a remote debugger using the extended
4296    remote gdb protocol.  NAME is the filename used for communication.  */
4297
4298 static void
4299 extended_remote_open (const char *name, int from_tty)
4300 {
4301   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4302 }
4303
4304 /* Reset all packets back to "unknown support".  Called when opening a
4305    new connection to a remote target.  */
4306
4307 static void
4308 reset_all_packet_configs_support (void)
4309 {
4310   int i;
4311
4312   for (i = 0; i < PACKET_MAX; i++)
4313     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4314 }
4315
4316 /* Initialize all packet configs.  */
4317
4318 static void
4319 init_all_packet_configs (void)
4320 {
4321   int i;
4322
4323   for (i = 0; i < PACKET_MAX; i++)
4324     {
4325       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4326       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4327     }
4328 }
4329
4330 /* Symbol look-up.  */
4331
4332 static void
4333 remote_check_symbols (void)
4334 {
4335   struct remote_state *rs = get_remote_state ();
4336   char *msg, *reply, *tmp;
4337   int end;
4338   long reply_size;
4339   struct cleanup *old_chain;
4340
4341   /* The remote side has no concept of inferiors that aren't running
4342      yet, it only knows about running processes.  If we're connected
4343      but our current inferior is not running, we should not invite the
4344      remote target to request symbol lookups related to its
4345      (unrelated) current process.  */
4346   if (!target_has_execution)
4347     return;
4348
4349   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4350     return;
4351
4352   /* Make sure the remote is pointing at the right process.  Note
4353      there's no way to select "no process".  */
4354   set_general_process ();
4355
4356   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4357      because we need both at the same time.  */
4358   msg = (char *) xmalloc (get_remote_packet_size ());
4359   old_chain = make_cleanup (xfree, msg);
4360   reply = (char *) xmalloc (get_remote_packet_size ());
4361   make_cleanup (free_current_contents, &reply);
4362   reply_size = get_remote_packet_size ();
4363
4364   /* Invite target to request symbol lookups.  */
4365
4366   putpkt ("qSymbol::");
4367   getpkt (&reply, &reply_size, 0);
4368   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4369
4370   while (startswith (reply, "qSymbol:"))
4371     {
4372       struct bound_minimal_symbol sym;
4373
4374       tmp = &reply[8];
4375       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4376       msg[end] = '\0';
4377       sym = lookup_minimal_symbol (msg, NULL, NULL);
4378       if (sym.minsym == NULL)
4379         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4380       else
4381         {
4382           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4383           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4384
4385           /* If this is a function address, return the start of code
4386              instead of any data function descriptor.  */
4387           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4388                                                          sym_addr,
4389                                                          &current_target);
4390
4391           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4392                      phex_nz (sym_addr, addr_size), &reply[8]);
4393         }
4394   
4395       putpkt (msg);
4396       getpkt (&reply, &reply_size, 0);
4397     }
4398
4399   do_cleanups (old_chain);
4400 }
4401
4402 static struct serial *
4403 remote_serial_open (const char *name)
4404 {
4405   static int udp_warning = 0;
4406
4407   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4408      of in ser-tcp.c, because it is the remote protocol assuming that the
4409      serial connection is reliable and not the serial connection promising
4410      to be.  */
4411   if (!udp_warning && startswith (name, "udp:"))
4412     {
4413       warning (_("The remote protocol may be unreliable over UDP.\n"
4414                  "Some events may be lost, rendering further debugging "
4415                  "impossible."));
4416       udp_warning = 1;
4417     }
4418
4419   return serial_open (name);
4420 }
4421
4422 /* Inform the target of our permission settings.  The permission flags
4423    work without this, but if the target knows the settings, it can do
4424    a couple things.  First, it can add its own check, to catch cases
4425    that somehow manage to get by the permissions checks in target
4426    methods.  Second, if the target is wired to disallow particular
4427    settings (for instance, a system in the field that is not set up to
4428    be able to stop at a breakpoint), it can object to any unavailable
4429    permissions.  */
4430
4431 void
4432 remote_set_permissions (struct target_ops *self)
4433 {
4434   struct remote_state *rs = get_remote_state ();
4435
4436   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4437              "WriteReg:%x;WriteMem:%x;"
4438              "InsertBreak:%x;InsertTrace:%x;"
4439              "InsertFastTrace:%x;Stop:%x",
4440              may_write_registers, may_write_memory,
4441              may_insert_breakpoints, may_insert_tracepoints,
4442              may_insert_fast_tracepoints, may_stop);
4443   putpkt (rs->buf);
4444   getpkt (&rs->buf, &rs->buf_size, 0);
4445
4446   /* If the target didn't like the packet, warn the user.  Do not try
4447      to undo the user's settings, that would just be maddening.  */
4448   if (strcmp (rs->buf, "OK") != 0)
4449     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4450 }
4451
4452 /* This type describes each known response to the qSupported
4453    packet.  */
4454 struct protocol_feature
4455 {
4456   /* The name of this protocol feature.  */
4457   const char *name;
4458
4459   /* The default for this protocol feature.  */
4460   enum packet_support default_support;
4461
4462   /* The function to call when this feature is reported, or after
4463      qSupported processing if the feature is not supported.
4464      The first argument points to this structure.  The second
4465      argument indicates whether the packet requested support be
4466      enabled, disabled, or probed (or the default, if this function
4467      is being called at the end of processing and this feature was
4468      not reported).  The third argument may be NULL; if not NULL, it
4469      is a NUL-terminated string taken from the packet following
4470      this feature's name and an equals sign.  */
4471   void (*func) (const struct protocol_feature *, enum packet_support,
4472                 const char *);
4473
4474   /* The corresponding packet for this feature.  Only used if
4475      FUNC is remote_supported_packet.  */
4476   int packet;
4477 };
4478
4479 static void
4480 remote_supported_packet (const struct protocol_feature *feature,
4481                          enum packet_support support,
4482                          const char *argument)
4483 {
4484   if (argument)
4485     {
4486       warning (_("Remote qSupported response supplied an unexpected value for"
4487                  " \"%s\"."), feature->name);
4488       return;
4489     }
4490
4491   remote_protocol_packets[feature->packet].support = support;
4492 }
4493
4494 static void
4495 remote_packet_size (const struct protocol_feature *feature,
4496                     enum packet_support support, const char *value)
4497 {
4498   struct remote_state *rs = get_remote_state ();
4499
4500   int packet_size;
4501   char *value_end;
4502
4503   if (support != PACKET_ENABLE)
4504     return;
4505
4506   if (value == NULL || *value == '\0')
4507     {
4508       warning (_("Remote target reported \"%s\" without a size."),
4509                feature->name);
4510       return;
4511     }
4512
4513   errno = 0;
4514   packet_size = strtol (value, &value_end, 16);
4515   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4516     {
4517       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4518                feature->name, value);
4519       return;
4520     }
4521
4522   /* Record the new maximum packet size.  */
4523   rs->explicit_packet_size = packet_size;
4524 }
4525
4526 static const struct protocol_feature remote_protocol_features[] = {
4527   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4528   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4529     PACKET_qXfer_auxv },
4530   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4531     PACKET_qXfer_exec_file },
4532   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4533     PACKET_qXfer_features },
4534   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4535     PACKET_qXfer_libraries },
4536   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4537     PACKET_qXfer_libraries_svr4 },
4538   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4539     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4540   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4541     PACKET_qXfer_memory_map },
4542   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4543     PACKET_qXfer_spu_read },
4544   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4545     PACKET_qXfer_spu_write },
4546   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4547     PACKET_qXfer_osdata },
4548   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4549     PACKET_qXfer_threads },
4550   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4551     PACKET_qXfer_traceframe_info },
4552   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4553     PACKET_QPassSignals },
4554   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4555     PACKET_QCatchSyscalls },
4556   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4557     PACKET_QProgramSignals },
4558   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4559     PACKET_QStartNoAckMode },
4560   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4561     PACKET_multiprocess_feature },
4562   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4563   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4564     PACKET_qXfer_siginfo_read },
4565   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4566     PACKET_qXfer_siginfo_write },
4567   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4568     PACKET_ConditionalTracepoints },
4569   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4570     PACKET_ConditionalBreakpoints },
4571   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4572     PACKET_BreakpointCommands },
4573   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4574     PACKET_FastTracepoints },
4575   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4576     PACKET_StaticTracepoints },
4577   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4578    PACKET_InstallInTrace},
4579   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4580     PACKET_DisconnectedTracing_feature },
4581   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4582     PACKET_bc },
4583   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4584     PACKET_bs },
4585   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4586     PACKET_TracepointSource },
4587   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4588     PACKET_QAllow },
4589   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4590     PACKET_EnableDisableTracepoints_feature },
4591   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4592     PACKET_qXfer_fdpic },
4593   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4594     PACKET_qXfer_uib },
4595   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4596     PACKET_QDisableRandomization },
4597   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4598   { "QTBuffer:size", PACKET_DISABLE,
4599     remote_supported_packet, PACKET_QTBuffer_size},
4600   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4601   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4602   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4603   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4604   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4605     PACKET_qXfer_btrace },
4606   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4607     PACKET_qXfer_btrace_conf },
4608   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4609     PACKET_Qbtrace_conf_bts_size },
4610   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4611   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4612   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4613     PACKET_fork_event_feature },
4614   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4615     PACKET_vfork_event_feature },
4616   { "exec-events", PACKET_DISABLE, remote_supported_packet,
4617     PACKET_exec_event_feature },
4618   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4619     PACKET_Qbtrace_conf_pt_size },
4620   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4621   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4622   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4623 };
4624
4625 static char *remote_support_xml;
4626
4627 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4628
4629 void
4630 register_remote_support_xml (const char *xml)
4631 {
4632 #if defined(HAVE_LIBEXPAT)
4633   if (remote_support_xml == NULL)
4634     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4635   else
4636     {
4637       char *copy = xstrdup (remote_support_xml + 13);
4638       char *p = strtok (copy, ",");
4639
4640       do
4641         {
4642           if (strcmp (p, xml) == 0)
4643             {
4644               /* already there */
4645               xfree (copy);
4646               return;
4647             }
4648         }
4649       while ((p = strtok (NULL, ",")) != NULL);
4650       xfree (copy);
4651
4652       remote_support_xml = reconcat (remote_support_xml,
4653                                      remote_support_xml, ",", xml,
4654                                      (char *) NULL);
4655     }
4656 #endif
4657 }
4658
4659 static char *
4660 remote_query_supported_append (char *msg, const char *append)
4661 {
4662   if (msg)
4663     return reconcat (msg, msg, ";", append, (char *) NULL);
4664   else
4665     return xstrdup (append);
4666 }
4667
4668 static void
4669 remote_query_supported (void)
4670 {
4671   struct remote_state *rs = get_remote_state ();
4672   char *next;
4673   int i;
4674   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4675
4676   /* The packet support flags are handled differently for this packet
4677      than for most others.  We treat an error, a disabled packet, and
4678      an empty response identically: any features which must be reported
4679      to be used will be automatically disabled.  An empty buffer
4680      accomplishes this, since that is also the representation for a list
4681      containing no features.  */
4682
4683   rs->buf[0] = 0;
4684   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4685     {
4686       char *q = NULL;
4687       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4688
4689       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4690         q = remote_query_supported_append (q, "multiprocess+");
4691
4692       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4693         q = remote_query_supported_append (q, "swbreak+");
4694       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4695         q = remote_query_supported_append (q, "hwbreak+");
4696
4697       q = remote_query_supported_append (q, "qRelocInsn+");
4698
4699       if (packet_set_cmd_state (PACKET_fork_event_feature)
4700           != AUTO_BOOLEAN_FALSE)
4701         q = remote_query_supported_append (q, "fork-events+");
4702       if (packet_set_cmd_state (PACKET_vfork_event_feature)
4703           != AUTO_BOOLEAN_FALSE)
4704         q = remote_query_supported_append (q, "vfork-events+");
4705       if (packet_set_cmd_state (PACKET_exec_event_feature)
4706           != AUTO_BOOLEAN_FALSE)
4707         q = remote_query_supported_append (q, "exec-events+");
4708
4709       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4710         q = remote_query_supported_append (q, "vContSupported+");
4711
4712       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4713         q = remote_query_supported_append (q, "QThreadEvents+");
4714
4715       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4716         q = remote_query_supported_append (q, "no-resumed+");
4717
4718       /* Keep this one last to work around a gdbserver <= 7.10 bug in
4719          the qSupported:xmlRegisters=i386 handling.  */
4720       if (remote_support_xml != NULL)
4721         q = remote_query_supported_append (q, remote_support_xml);
4722
4723       q = reconcat (q, "qSupported:", q, (char *) NULL);
4724       putpkt (q);
4725
4726       do_cleanups (old_chain);
4727
4728       getpkt (&rs->buf, &rs->buf_size, 0);
4729
4730       /* If an error occured, warn, but do not return - just reset the
4731          buffer to empty and go on to disable features.  */
4732       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4733           == PACKET_ERROR)
4734         {
4735           warning (_("Remote failure reply: %s"), rs->buf);
4736           rs->buf[0] = 0;
4737         }
4738     }
4739
4740   memset (seen, 0, sizeof (seen));
4741
4742   next = rs->buf;
4743   while (*next)
4744     {
4745       enum packet_support is_supported;
4746       char *p, *end, *name_end, *value;
4747
4748       /* First separate out this item from the rest of the packet.  If
4749          there's another item after this, we overwrite the separator
4750          (terminated strings are much easier to work with).  */
4751       p = next;
4752       end = strchr (p, ';');
4753       if (end == NULL)
4754         {
4755           end = p + strlen (p);
4756           next = end;
4757         }
4758       else
4759         {
4760           *end = '\0';
4761           next = end + 1;
4762
4763           if (end == p)
4764             {
4765               warning (_("empty item in \"qSupported\" response"));
4766               continue;
4767             }
4768         }
4769
4770       name_end = strchr (p, '=');
4771       if (name_end)
4772         {
4773           /* This is a name=value entry.  */
4774           is_supported = PACKET_ENABLE;
4775           value = name_end + 1;
4776           *name_end = '\0';
4777         }
4778       else
4779         {
4780           value = NULL;
4781           switch (end[-1])
4782             {
4783             case '+':
4784               is_supported = PACKET_ENABLE;
4785               break;
4786
4787             case '-':
4788               is_supported = PACKET_DISABLE;
4789               break;
4790
4791             case '?':
4792               is_supported = PACKET_SUPPORT_UNKNOWN;
4793               break;
4794
4795             default:
4796               warning (_("unrecognized item \"%s\" "
4797                          "in \"qSupported\" response"), p);
4798               continue;
4799             }
4800           end[-1] = '\0';
4801         }
4802
4803       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4804         if (strcmp (remote_protocol_features[i].name, p) == 0)
4805           {
4806             const struct protocol_feature *feature;
4807
4808             seen[i] = 1;
4809             feature = &remote_protocol_features[i];
4810             feature->func (feature, is_supported, value);
4811             break;
4812           }
4813     }
4814
4815   /* If we increased the packet size, make sure to increase the global
4816      buffer size also.  We delay this until after parsing the entire
4817      qSupported packet, because this is the same buffer we were
4818      parsing.  */
4819   if (rs->buf_size < rs->explicit_packet_size)
4820     {
4821       rs->buf_size = rs->explicit_packet_size;
4822       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4823     }
4824
4825   /* Handle the defaults for unmentioned features.  */
4826   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4827     if (!seen[i])
4828       {
4829         const struct protocol_feature *feature;
4830
4831         feature = &remote_protocol_features[i];
4832         feature->func (feature, feature->default_support, NULL);
4833       }
4834 }
4835
4836 /* Remove any of the remote.c targets from target stack.  Upper targets depend
4837    on it so remove them first.  */
4838
4839 static void
4840 remote_unpush_target (void)
4841 {
4842   pop_all_targets_at_and_above (process_stratum);
4843 }
4844
4845 static void
4846 remote_open_1 (const char *name, int from_tty,
4847                struct target_ops *target, int extended_p)
4848 {
4849   struct remote_state *rs = get_remote_state ();
4850
4851   if (name == 0)
4852     error (_("To open a remote debug connection, you need to specify what\n"
4853            "serial device is attached to the remote system\n"
4854            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4855
4856   /* See FIXME above.  */
4857   if (!target_async_permitted)
4858     wait_forever_enabled_p = 1;
4859
4860   /* If we're connected to a running target, target_preopen will kill it.
4861      Ask this question first, before target_preopen has a chance to kill
4862      anything.  */
4863   if (rs->remote_desc != NULL && !have_inferiors ())
4864     {
4865       if (from_tty
4866           && !query (_("Already connected to a remote target.  Disconnect? ")))
4867         error (_("Still connected."));
4868     }
4869
4870   /* Here the possibly existing remote target gets unpushed.  */
4871   target_preopen (from_tty);
4872
4873   /* Make sure we send the passed signals list the next time we resume.  */
4874   xfree (rs->last_pass_packet);
4875   rs->last_pass_packet = NULL;
4876
4877   /* Make sure we send the program signals list the next time we
4878      resume.  */
4879   xfree (rs->last_program_signals_packet);
4880   rs->last_program_signals_packet = NULL;
4881
4882   remote_fileio_reset ();
4883   reopen_exec_file ();
4884   reread_symbols ();
4885
4886   rs->remote_desc = remote_serial_open (name);
4887   if (!rs->remote_desc)
4888     perror_with_name (name);
4889
4890   if (baud_rate != -1)
4891     {
4892       if (serial_setbaudrate (rs->remote_desc, baud_rate))
4893         {
4894           /* The requested speed could not be set.  Error out to
4895              top level after closing remote_desc.  Take care to
4896              set remote_desc to NULL to avoid closing remote_desc
4897              more than once.  */
4898           serial_close (rs->remote_desc);
4899           rs->remote_desc = NULL;
4900           perror_with_name (name);
4901         }
4902     }
4903
4904   serial_setparity (rs->remote_desc, serial_parity);
4905   serial_raw (rs->remote_desc);
4906
4907   /* If there is something sitting in the buffer we might take it as a
4908      response to a command, which would be bad.  */
4909   serial_flush_input (rs->remote_desc);
4910
4911   if (from_tty)
4912     {
4913       puts_filtered ("Remote debugging using ");
4914       puts_filtered (name);
4915       puts_filtered ("\n");
4916     }
4917   push_target (target);         /* Switch to using remote target now.  */
4918
4919   /* Register extra event sources in the event loop.  */
4920   remote_async_inferior_event_token
4921     = create_async_event_handler (remote_async_inferior_event_handler,
4922                                   NULL);
4923   rs->notif_state = remote_notif_state_allocate ();
4924
4925   /* Reset the target state; these things will be queried either by
4926      remote_query_supported or as they are needed.  */
4927   reset_all_packet_configs_support ();
4928   rs->cached_wait_status = 0;
4929   rs->explicit_packet_size = 0;
4930   rs->noack_mode = 0;
4931   rs->extended = extended_p;
4932   rs->waiting_for_stop_reply = 0;
4933   rs->ctrlc_pending_p = 0;
4934
4935   rs->general_thread = not_sent_ptid;
4936   rs->continue_thread = not_sent_ptid;
4937   rs->remote_traceframe_number = -1;
4938
4939   /* Probe for ability to use "ThreadInfo" query, as required.  */
4940   rs->use_threadinfo_query = 1;
4941   rs->use_threadextra_query = 1;
4942
4943   readahead_cache_invalidate ();
4944
4945   if (target_async_permitted)
4946     {
4947       /* With this target we start out by owning the terminal.  */
4948       remote_async_terminal_ours_p = 1;
4949
4950       /* FIXME: cagney/1999-09-23: During the initial connection it is
4951          assumed that the target is already ready and able to respond to
4952          requests.  Unfortunately remote_start_remote() eventually calls
4953          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
4954          around this.  Eventually a mechanism that allows
4955          wait_for_inferior() to expect/get timeouts will be
4956          implemented.  */
4957       wait_forever_enabled_p = 0;
4958     }
4959
4960   /* First delete any symbols previously loaded from shared libraries.  */
4961   no_shared_libraries (NULL, 0);
4962
4963   /* Start afresh.  */
4964   init_thread_list ();
4965
4966   /* Start the remote connection.  If error() or QUIT, discard this
4967      target (we'd otherwise be in an inconsistent state) and then
4968      propogate the error on up the exception chain.  This ensures that
4969      the caller doesn't stumble along blindly assuming that the
4970      function succeeded.  The CLI doesn't have this problem but other
4971      UI's, such as MI do.
4972
4973      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4974      this function should return an error indication letting the
4975      caller restore the previous state.  Unfortunately the command
4976      ``target remote'' is directly wired to this function making that
4977      impossible.  On a positive note, the CLI side of this problem has
4978      been fixed - the function set_cmd_context() makes it possible for
4979      all the ``target ....'' commands to share a common callback
4980      function.  See cli-dump.c.  */
4981   {
4982
4983     TRY
4984       {
4985         remote_start_remote (from_tty, target, extended_p);
4986       }
4987     CATCH (ex, RETURN_MASK_ALL)
4988       {
4989         /* Pop the partially set up target - unless something else did
4990            already before throwing the exception.  */
4991         if (rs->remote_desc != NULL)
4992           remote_unpush_target ();
4993         if (target_async_permitted)
4994           wait_forever_enabled_p = 1;
4995         throw_exception (ex);
4996       }
4997     END_CATCH
4998   }
4999
5000   remote_btrace_reset ();
5001
5002   if (target_async_permitted)
5003     wait_forever_enabled_p = 1;
5004 }
5005
5006 /* Detach the specified process.  */
5007
5008 static void
5009 remote_detach_pid (int pid)
5010 {
5011   struct remote_state *rs = get_remote_state ();
5012
5013   if (remote_multi_process_p (rs))
5014     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5015   else
5016     strcpy (rs->buf, "D");
5017
5018   putpkt (rs->buf);
5019   getpkt (&rs->buf, &rs->buf_size, 0);
5020
5021   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5022     ;
5023   else if (rs->buf[0] == '\0')
5024     error (_("Remote doesn't know how to detach"));
5025   else
5026     error (_("Can't detach process."));
5027 }
5028
5029 /* This detaches a program to which we previously attached, using
5030    inferior_ptid to identify the process.  After this is done, GDB
5031    can be used to debug some other program.  We better not have left
5032    any breakpoints in the target program or it'll die when it hits
5033    one.  */
5034
5035 static void
5036 remote_detach_1 (const char *args, int from_tty)
5037 {
5038   int pid = ptid_get_pid (inferior_ptid);
5039   struct remote_state *rs = get_remote_state ();
5040   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5041   int is_fork_parent;
5042
5043   if (args)
5044     error (_("Argument given to \"detach\" when remotely debugging."));
5045
5046   if (!target_has_execution)
5047     error (_("No process to detach from."));
5048
5049   if (from_tty)
5050     {
5051       char *exec_file = get_exec_file (0);
5052       if (exec_file == NULL)
5053         exec_file = "";
5054       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
5055                          target_pid_to_str (pid_to_ptid (pid)));
5056       gdb_flush (gdb_stdout);
5057     }
5058
5059   /* Tell the remote target to detach.  */
5060   remote_detach_pid (pid);
5061
5062   /* Exit only if this is the only active inferior.  */
5063   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5064     puts_filtered (_("Ending remote debugging.\n"));
5065
5066   /* Check to see if we are detaching a fork parent.  Note that if we
5067      are detaching a fork child, tp == NULL.  */
5068   is_fork_parent = (tp != NULL
5069                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5070
5071   /* If doing detach-on-fork, we don't mourn, because that will delete
5072      breakpoints that should be available for the followed inferior.  */
5073   if (!is_fork_parent)
5074     target_mourn_inferior ();
5075   else
5076     {
5077       inferior_ptid = null_ptid;
5078       detach_inferior (pid);
5079     }
5080 }
5081
5082 static void
5083 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5084 {
5085   remote_detach_1 (args, from_tty);
5086 }
5087
5088 static void
5089 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5090 {
5091   remote_detach_1 (args, from_tty);
5092 }
5093
5094 /* Target follow-fork function for remote targets.  On entry, and
5095    at return, the current inferior is the fork parent.
5096
5097    Note that although this is currently only used for extended-remote,
5098    it is named remote_follow_fork in anticipation of using it for the
5099    remote target as well.  */
5100
5101 static int
5102 remote_follow_fork (struct target_ops *ops, int follow_child,
5103                     int detach_fork)
5104 {
5105   struct remote_state *rs = get_remote_state ();
5106   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5107
5108   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5109       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5110     {
5111       /* When following the parent and detaching the child, we detach
5112          the child here.  For the case of following the child and
5113          detaching the parent, the detach is done in the target-
5114          independent follow fork code in infrun.c.  We can't use
5115          target_detach when detaching an unfollowed child because
5116          the client side doesn't know anything about the child.  */
5117       if (detach_fork && !follow_child)
5118         {
5119           /* Detach the fork child.  */
5120           ptid_t child_ptid;
5121           pid_t child_pid;
5122
5123           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5124           child_pid = ptid_get_pid (child_ptid);
5125
5126           remote_detach_pid (child_pid);
5127           detach_inferior (child_pid);
5128         }
5129     }
5130   return 0;
5131 }
5132
5133 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5134    in the program space of the new inferior.  On entry and at return the
5135    current inferior is the exec'ing inferior.  INF is the new exec'd
5136    inferior, which may be the same as the exec'ing inferior unless
5137    follow-exec-mode is "new".  */
5138
5139 static void
5140 remote_follow_exec (struct target_ops *ops,
5141                     struct inferior *inf, char *execd_pathname)
5142 {
5143   /* We know that this is a target file name, so if it has the "target:"
5144      prefix we strip it off before saving it in the program space.  */
5145   if (is_target_filename (execd_pathname))
5146     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5147
5148   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5149 }
5150
5151 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5152
5153 static void
5154 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5155 {
5156   if (args)
5157     error (_("Argument given to \"disconnect\" when remotely debugging."));
5158
5159   /* Make sure we unpush even the extended remote targets.  Calling
5160      target_mourn_inferior won't unpush, and remote_mourn won't
5161      unpush if there is more than one inferior left.  */
5162   unpush_target (target);
5163   generic_mourn_inferior ();
5164
5165   if (from_tty)
5166     puts_filtered ("Ending remote debugging.\n");
5167 }
5168
5169 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5170    be chatty about it.  */
5171
5172 static void
5173 extended_remote_attach (struct target_ops *target, const char *args,
5174                         int from_tty)
5175 {
5176   struct remote_state *rs = get_remote_state ();
5177   int pid;
5178   char *wait_status = NULL;
5179
5180   pid = parse_pid_to_attach (args);
5181
5182   /* Remote PID can be freely equal to getpid, do not check it here the same
5183      way as in other targets.  */
5184
5185   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5186     error (_("This target does not support attaching to a process"));
5187
5188   if (from_tty)
5189     {
5190       char *exec_file = get_exec_file (0);
5191
5192       if (exec_file)
5193         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5194                            target_pid_to_str (pid_to_ptid (pid)));
5195       else
5196         printf_unfiltered (_("Attaching to %s\n"),
5197                            target_pid_to_str (pid_to_ptid (pid)));
5198
5199       gdb_flush (gdb_stdout);
5200     }
5201
5202   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5203   putpkt (rs->buf);
5204   getpkt (&rs->buf, &rs->buf_size, 0);
5205
5206   switch (packet_ok (rs->buf,
5207                      &remote_protocol_packets[PACKET_vAttach]))
5208     {
5209     case PACKET_OK:
5210       if (!target_is_non_stop_p ())
5211         {
5212           /* Save the reply for later.  */
5213           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5214           strcpy (wait_status, rs->buf);
5215         }
5216       else if (strcmp (rs->buf, "OK") != 0)
5217         error (_("Attaching to %s failed with: %s"),
5218                target_pid_to_str (pid_to_ptid (pid)),
5219                rs->buf);
5220       break;
5221     case PACKET_UNKNOWN:
5222       error (_("This target does not support attaching to a process"));
5223     default:
5224       error (_("Attaching to %s failed"),
5225              target_pid_to_str (pid_to_ptid (pid)));
5226     }
5227
5228   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5229
5230   inferior_ptid = pid_to_ptid (pid);
5231
5232   if (target_is_non_stop_p ())
5233     {
5234       struct thread_info *thread;
5235
5236       /* Get list of threads.  */
5237       remote_update_thread_list (target);
5238
5239       thread = first_thread_of_process (pid);
5240       if (thread)
5241         inferior_ptid = thread->ptid;
5242       else
5243         inferior_ptid = pid_to_ptid (pid);
5244
5245       /* Invalidate our notion of the remote current thread.  */
5246       record_currthread (rs, minus_one_ptid);
5247     }
5248   else
5249     {
5250       /* Now, if we have thread information, update inferior_ptid.  */
5251       inferior_ptid = remote_current_thread (inferior_ptid);
5252
5253       /* Add the main thread to the thread list.  */
5254       add_thread_silent (inferior_ptid);
5255     }
5256
5257   /* Next, if the target can specify a description, read it.  We do
5258      this before anything involving memory or registers.  */
5259   target_find_description ();
5260
5261   if (!target_is_non_stop_p ())
5262     {
5263       /* Use the previously fetched status.  */
5264       gdb_assert (wait_status != NULL);
5265
5266       if (target_can_async_p ())
5267         {
5268           struct notif_event *reply
5269             =  remote_notif_parse (&notif_client_stop, wait_status);
5270
5271           push_stop_reply ((struct stop_reply *) reply);
5272
5273           target_async (1);
5274         }
5275       else
5276         {
5277           gdb_assert (wait_status != NULL);
5278           strcpy (rs->buf, wait_status);
5279           rs->cached_wait_status = 1;
5280         }
5281     }
5282   else
5283     gdb_assert (wait_status == NULL);
5284 }
5285
5286 /* Implementation of the to_post_attach method.  */
5287
5288 static void
5289 extended_remote_post_attach (struct target_ops *ops, int pid)
5290 {
5291   /* Get text, data & bss offsets.  */
5292   get_offsets ();
5293
5294   /* In certain cases GDB might not have had the chance to start
5295      symbol lookup up until now.  This could happen if the debugged
5296      binary is not using shared libraries, the vsyscall page is not
5297      present (on Linux) and the binary itself hadn't changed since the
5298      debugging process was started.  */
5299   if (symfile_objfile != NULL)
5300     remote_check_symbols();
5301 }
5302
5303 \f
5304 /* Check for the availability of vCont.  This function should also check
5305    the response.  */
5306
5307 static void
5308 remote_vcont_probe (struct remote_state *rs)
5309 {
5310   char *buf;
5311
5312   strcpy (rs->buf, "vCont?");
5313   putpkt (rs->buf);
5314   getpkt (&rs->buf, &rs->buf_size, 0);
5315   buf = rs->buf;
5316
5317   /* Make sure that the features we assume are supported.  */
5318   if (startswith (buf, "vCont"))
5319     {
5320       char *p = &buf[5];
5321       int support_c, support_C;
5322
5323       rs->supports_vCont.s = 0;
5324       rs->supports_vCont.S = 0;
5325       support_c = 0;
5326       support_C = 0;
5327       rs->supports_vCont.t = 0;
5328       rs->supports_vCont.r = 0;
5329       while (p && *p == ';')
5330         {
5331           p++;
5332           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5333             rs->supports_vCont.s = 1;
5334           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5335             rs->supports_vCont.S = 1;
5336           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5337             support_c = 1;
5338           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5339             support_C = 1;
5340           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5341             rs->supports_vCont.t = 1;
5342           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5343             rs->supports_vCont.r = 1;
5344
5345           p = strchr (p, ';');
5346         }
5347
5348       /* If c, and C are not all supported, we can't use vCont.  Clearing
5349          BUF will make packet_ok disable the packet.  */
5350       if (!support_c || !support_C)
5351         buf[0] = 0;
5352     }
5353
5354   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5355 }
5356
5357 /* Helper function for building "vCont" resumptions.  Write a
5358    resumption to P.  ENDP points to one-passed-the-end of the buffer
5359    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5360    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5361    resumed thread should be single-stepped and/or signalled.  If PTID
5362    equals minus_one_ptid, then all threads are resumed; if PTID
5363    represents a process, then all threads of the process are resumed;
5364    the thread to be stepped and/or signalled is given in the global
5365    INFERIOR_PTID.  */
5366
5367 static char *
5368 append_resumption (char *p, char *endp,
5369                    ptid_t ptid, int step, enum gdb_signal siggnal)
5370 {
5371   struct remote_state *rs = get_remote_state ();
5372
5373   if (step && siggnal != GDB_SIGNAL_0)
5374     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5375   else if (step
5376            /* GDB is willing to range step.  */
5377            && use_range_stepping
5378            /* Target supports range stepping.  */
5379            && rs->supports_vCont.r
5380            /* We don't currently support range stepping multiple
5381               threads with a wildcard (though the protocol allows it,
5382               so stubs shouldn't make an active effort to forbid
5383               it).  */
5384            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5385     {
5386       struct thread_info *tp;
5387
5388       if (ptid_equal (ptid, minus_one_ptid))
5389         {
5390           /* If we don't know about the target thread's tid, then
5391              we're resuming magic_null_ptid (see caller).  */
5392           tp = find_thread_ptid (magic_null_ptid);
5393         }
5394       else
5395         tp = find_thread_ptid (ptid);
5396       gdb_assert (tp != NULL);
5397
5398       if (tp->control.may_range_step)
5399         {
5400           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5401
5402           p += xsnprintf (p, endp - p, ";r%s,%s",
5403                           phex_nz (tp->control.step_range_start,
5404                                    addr_size),
5405                           phex_nz (tp->control.step_range_end,
5406                                    addr_size));
5407         }
5408       else
5409         p += xsnprintf (p, endp - p, ";s");
5410     }
5411   else if (step)
5412     p += xsnprintf (p, endp - p, ";s");
5413   else if (siggnal != GDB_SIGNAL_0)
5414     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5415   else
5416     p += xsnprintf (p, endp - p, ";c");
5417
5418   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5419     {
5420       ptid_t nptid;
5421
5422       /* All (-1) threads of process.  */
5423       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5424
5425       p += xsnprintf (p, endp - p, ":");
5426       p = write_ptid (p, endp, nptid);
5427     }
5428   else if (!ptid_equal (ptid, minus_one_ptid))
5429     {
5430       p += xsnprintf (p, endp - p, ":");
5431       p = write_ptid (p, endp, ptid);
5432     }
5433
5434   return p;
5435 }
5436
5437 /* Clear the thread's private info on resume.  */
5438
5439 static void
5440 resume_clear_thread_private_info (struct thread_info *thread)
5441 {
5442   if (thread->priv != NULL)
5443     {
5444       thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5445       thread->priv->watch_data_address = 0;
5446     }
5447 }
5448
5449 /* Append a vCont continue-with-signal action for threads that have a
5450    non-zero stop signal.  */
5451
5452 static char *
5453 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5454 {
5455   struct thread_info *thread;
5456
5457   ALL_NON_EXITED_THREADS (thread)
5458     if (ptid_match (thread->ptid, ptid)
5459         && !ptid_equal (inferior_ptid, thread->ptid)
5460         && thread->suspend.stop_signal != GDB_SIGNAL_0)
5461       {
5462         p = append_resumption (p, endp, thread->ptid,
5463                                0, thread->suspend.stop_signal);
5464         thread->suspend.stop_signal = GDB_SIGNAL_0;
5465         resume_clear_thread_private_info (thread);
5466       }
5467
5468   return p;
5469 }
5470
5471 /* Resume the remote inferior by using a "vCont" packet.  The thread
5472    to be resumed is PTID; STEP and SIGGNAL indicate whether the
5473    resumed thread should be single-stepped and/or signalled.  If PTID
5474    equals minus_one_ptid, then all threads are resumed; the thread to
5475    be stepped and/or signalled is given in the global INFERIOR_PTID.
5476    This function returns non-zero iff it resumes the inferior.
5477
5478    This function issues a strict subset of all possible vCont commands at the
5479    moment.  */
5480
5481 static int
5482 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5483 {
5484   struct remote_state *rs = get_remote_state ();
5485   char *p;
5486   char *endp;
5487
5488   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5489     remote_vcont_probe (rs);
5490
5491   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5492     return 0;
5493
5494   p = rs->buf;
5495   endp = rs->buf + get_remote_packet_size ();
5496
5497   /* If we could generate a wider range of packets, we'd have to worry
5498      about overflowing BUF.  Should there be a generic
5499      "multi-part-packet" packet?  */
5500
5501   p += xsnprintf (p, endp - p, "vCont");
5502
5503   if (ptid_equal (ptid, magic_null_ptid))
5504     {
5505       /* MAGIC_NULL_PTID means that we don't have any active threads,
5506          so we don't have any TID numbers the inferior will
5507          understand.  Make sure to only send forms that do not specify
5508          a TID.  */
5509       append_resumption (p, endp, minus_one_ptid, step, siggnal);
5510     }
5511   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5512     {
5513       /* Resume all threads (of all processes, or of a single
5514          process), with preference for INFERIOR_PTID.  This assumes
5515          inferior_ptid belongs to the set of all threads we are about
5516          to resume.  */
5517       if (step || siggnal != GDB_SIGNAL_0)
5518         {
5519           /* Step inferior_ptid, with or without signal.  */
5520           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5521         }
5522
5523       /* Also pass down any pending signaled resumption for other
5524          threads not the current.  */
5525       p = append_pending_thread_resumptions (p, endp, ptid);
5526
5527       /* And continue others without a signal.  */
5528       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5529     }
5530   else
5531     {
5532       /* Scheduler locking; resume only PTID.  */
5533       append_resumption (p, endp, ptid, step, siggnal);
5534     }
5535
5536   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5537   putpkt (rs->buf);
5538
5539   if (target_is_non_stop_p ())
5540     {
5541       /* In non-stop, the stub replies to vCont with "OK".  The stop
5542          reply will be reported asynchronously by means of a `%Stop'
5543          notification.  */
5544       getpkt (&rs->buf, &rs->buf_size, 0);
5545       if (strcmp (rs->buf, "OK") != 0)
5546         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5547     }
5548
5549   return 1;
5550 }
5551
5552 /* Tell the remote machine to resume.  */
5553
5554 static void
5555 remote_resume (struct target_ops *ops,
5556                ptid_t ptid, int step, enum gdb_signal siggnal)
5557 {
5558   struct remote_state *rs = get_remote_state ();
5559   char *buf;
5560   struct thread_info *thread;
5561
5562   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5563      (explained in remote-notif.c:handle_notification) so
5564      remote_notif_process is not called.  We need find a place where
5565      it is safe to start a 'vNotif' sequence.  It is good to do it
5566      before resuming inferior, because inferior was stopped and no RSP
5567      traffic at that moment.  */
5568   if (!target_is_non_stop_p ())
5569     remote_notif_process (rs->notif_state, &notif_client_stop);
5570
5571   rs->last_sent_signal = siggnal;
5572   rs->last_sent_step = step;
5573
5574   /* The vCont packet doesn't need to specify threads via Hc.  */
5575   /* No reverse support (yet) for vCont.  */
5576   if (execution_direction != EXEC_REVERSE)
5577     if (remote_vcont_resume (ptid, step, siggnal))
5578       goto done;
5579
5580   /* All other supported resume packets do use Hc, so set the continue
5581      thread.  */
5582   if (ptid_equal (ptid, minus_one_ptid))
5583     set_continue_thread (any_thread_ptid);
5584   else
5585     set_continue_thread (ptid);
5586
5587   ALL_NON_EXITED_THREADS (thread)
5588     resume_clear_thread_private_info (thread);
5589
5590   buf = rs->buf;
5591   if (execution_direction == EXEC_REVERSE)
5592     {
5593       /* We don't pass signals to the target in reverse exec mode.  */
5594       if (info_verbose && siggnal != GDB_SIGNAL_0)
5595         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5596                  siggnal);
5597
5598       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5599         error (_("Remote reverse-step not supported."));
5600       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5601         error (_("Remote reverse-continue not supported."));
5602
5603       strcpy (buf, step ? "bs" : "bc");
5604     }
5605   else if (siggnal != GDB_SIGNAL_0)
5606     {
5607       buf[0] = step ? 'S' : 'C';
5608       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5609       buf[2] = tohex (((int) siggnal) & 0xf);
5610       buf[3] = '\0';
5611     }
5612   else
5613     strcpy (buf, step ? "s" : "c");
5614
5615   putpkt (buf);
5616
5617  done:
5618   /* We are about to start executing the inferior, let's register it
5619      with the event loop.  NOTE: this is the one place where all the
5620      execution commands end up.  We could alternatively do this in each
5621      of the execution commands in infcmd.c.  */
5622   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5623      into infcmd.c in order to allow inferior function calls to work
5624      NOT asynchronously.  */
5625   if (target_can_async_p ())
5626     target_async (1);
5627
5628   /* We've just told the target to resume.  The remote server will
5629      wait for the inferior to stop, and then send a stop reply.  In
5630      the mean time, we can't start another command/query ourselves
5631      because the stub wouldn't be ready to process it.  This applies
5632      only to the base all-stop protocol, however.  In non-stop (which
5633      only supports vCont), the stub replies with an "OK", and is
5634      immediate able to process further serial input.  */
5635   if (!target_is_non_stop_p ())
5636     rs->waiting_for_stop_reply = 1;
5637 }
5638 \f
5639
5640 /* Set up the signal handler for SIGINT, while the target is
5641    executing, ovewriting the 'regular' SIGINT signal handler.  */
5642 static void
5643 async_initialize_sigint_signal_handler (void)
5644 {
5645   signal (SIGINT, async_handle_remote_sigint);
5646 }
5647
5648 /* Signal handler for SIGINT, while the target is executing.  */
5649 static void
5650 async_handle_remote_sigint (int sig)
5651 {
5652   signal (sig, async_handle_remote_sigint_twice);
5653   /* Note we need to go through gdb_call_async_signal_handler in order
5654      to wake up the event loop on Windows.  */
5655   gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5656 }
5657
5658 /* Signal handler for SIGINT, installed after SIGINT has already been
5659    sent once.  It will take effect the second time that the user sends
5660    a ^C.  */
5661 static void
5662 async_handle_remote_sigint_twice (int sig)
5663 {
5664   signal (sig, async_handle_remote_sigint);
5665   /* See note in async_handle_remote_sigint.  */
5666   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5667 }
5668
5669 /* Implementation of to_check_pending_interrupt.  */
5670
5671 static void
5672 remote_check_pending_interrupt (struct target_ops *self)
5673 {
5674   struct async_signal_handler *token = async_sigint_remote_twice_token;
5675
5676   if (async_signal_handler_is_marked (token))
5677     {
5678       clear_async_signal_handler (token);
5679       call_async_signal_handler (token);
5680     }
5681 }
5682
5683 /* Perform the real interruption of the target execution, in response
5684    to a ^C.  */
5685 static void
5686 async_remote_interrupt (gdb_client_data arg)
5687 {
5688   if (remote_debug)
5689     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5690
5691   target_interrupt (inferior_ptid);
5692 }
5693
5694 /* Perform interrupt, if the first attempt did not succeed.  Just give
5695    up on the target alltogether.  */
5696 static void
5697 async_remote_interrupt_twice (gdb_client_data arg)
5698 {
5699   if (remote_debug)
5700     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5701
5702   interrupt_query ();
5703 }
5704
5705 /* Reinstall the usual SIGINT handlers, after the target has
5706    stopped.  */
5707 static void
5708 async_cleanup_sigint_signal_handler (void *dummy)
5709 {
5710   signal (SIGINT, handle_sigint);
5711 }
5712
5713 /* Send ^C to target to halt it.  Target will respond, and send us a
5714    packet.  */
5715 static void (*ofunc) (int);
5716
5717 /* The command line interface's interrupt routine.  This function is installed
5718    as a signal handler for SIGINT.  The first time a user requests an
5719    interrupt, we call remote_interrupt to send a break or ^C.  If there is no
5720    response from the target (it didn't stop when the user requested it),
5721    we ask the user if he'd like to detach from the target.  */
5722
5723 static void
5724 sync_remote_interrupt (int signo)
5725 {
5726   /* If this doesn't work, try more severe steps.  */
5727   signal (signo, sync_remote_interrupt_twice);
5728
5729   gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5730 }
5731
5732 /* The user typed ^C twice.  */
5733
5734 static void
5735 sync_remote_interrupt_twice (int signo)
5736 {
5737   signal (signo, ofunc);
5738   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5739   signal (signo, sync_remote_interrupt);
5740 }
5741
5742 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
5743    thread, all threads of a remote process, or all threads of all
5744    processes.  */
5745
5746 static void
5747 remote_stop_ns (ptid_t ptid)
5748 {
5749   struct remote_state *rs = get_remote_state ();
5750   char *p = rs->buf;
5751   char *endp = rs->buf + get_remote_packet_size ();
5752
5753   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5754     remote_vcont_probe (rs);
5755
5756   if (!rs->supports_vCont.t)
5757     error (_("Remote server does not support stopping threads"));
5758
5759   if (ptid_equal (ptid, minus_one_ptid)
5760       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5761     p += xsnprintf (p, endp - p, "vCont;t");
5762   else
5763     {
5764       ptid_t nptid;
5765
5766       p += xsnprintf (p, endp - p, "vCont;t:");
5767
5768       if (ptid_is_pid (ptid))
5769           /* All (-1) threads of process.  */
5770         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5771       else
5772         {
5773           /* Small optimization: if we already have a stop reply for
5774              this thread, no use in telling the stub we want this
5775              stopped.  */
5776           if (peek_stop_reply (ptid))
5777             return;
5778
5779           nptid = ptid;
5780         }
5781
5782       write_ptid (p, endp, nptid);
5783     }
5784
5785   /* In non-stop, we get an immediate OK reply.  The stop reply will
5786      come in asynchronously by notification.  */
5787   putpkt (rs->buf);
5788   getpkt (&rs->buf, &rs->buf_size, 0);
5789   if (strcmp (rs->buf, "OK") != 0)
5790     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5791 }
5792
5793 /* All-stop version of target_interrupt.  Sends a break or a ^C to
5794    interrupt the remote target.  It is undefined which thread of which
5795    process reports the interrupt.  */
5796
5797 static void
5798 remote_interrupt_as (void)
5799 {
5800   struct remote_state *rs = get_remote_state ();
5801
5802   rs->ctrlc_pending_p = 1;
5803
5804   /* If the inferior is stopped already, but the core didn't know
5805      about it yet, just ignore the request.  The cached wait status
5806      will be collected in remote_wait.  */
5807   if (rs->cached_wait_status)
5808     return;
5809
5810   /* Send interrupt_sequence to remote target.  */
5811   send_interrupt_sequence ();
5812 }
5813
5814 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
5815    the remote target.  It is undefined which thread of which process
5816    reports the interrupt.  Throws an error if the packet is not
5817    supported by the server.  */
5818
5819 static void
5820 remote_interrupt_ns (void)
5821 {
5822   struct remote_state *rs = get_remote_state ();
5823   char *p = rs->buf;
5824   char *endp = rs->buf + get_remote_packet_size ();
5825
5826   xsnprintf (p, endp - p, "vCtrlC");
5827
5828   /* In non-stop, we get an immediate OK reply.  The stop reply will
5829      come in asynchronously by notification.  */
5830   putpkt (rs->buf);
5831   getpkt (&rs->buf, &rs->buf_size, 0);
5832
5833   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5834     {
5835     case PACKET_OK:
5836       break;
5837     case PACKET_UNKNOWN:
5838       error (_("No support for interrupting the remote target."));
5839     case PACKET_ERROR:
5840       error (_("Interrupting target failed: %s"), rs->buf);
5841     }
5842 }
5843
5844 /* Implement the to_stop function for the remote targets.  */
5845
5846 static void
5847 remote_stop (struct target_ops *self, ptid_t ptid)
5848 {
5849   if (remote_debug)
5850     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5851
5852   if (target_is_non_stop_p ())
5853     remote_stop_ns (ptid);
5854   else
5855     {
5856       /* We don't currently have a way to transparently pause the
5857          remote target in all-stop mode.  Interrupt it instead.  */
5858       remote_interrupt_as ();
5859     }
5860 }
5861
5862 /* Implement the to_interrupt function for the remote targets.  */
5863
5864 static void
5865 remote_interrupt (struct target_ops *self, ptid_t ptid)
5866 {
5867   struct remote_state *rs = get_remote_state ();
5868
5869   if (remote_debug)
5870     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5871
5872   if (target_is_non_stop_p ())
5873     remote_interrupt_ns ();
5874   else
5875     remote_interrupt_as ();
5876 }
5877
5878 /* Ask the user what to do when an interrupt is received.  */
5879
5880 static void
5881 interrupt_query (void)
5882 {
5883   struct remote_state *rs = get_remote_state ();
5884   struct cleanup *old_chain;
5885
5886   old_chain = make_cleanup_restore_target_terminal ();
5887   target_terminal_ours ();
5888
5889   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5890     {
5891       if (query (_("The target is not responding to interrupt requests.\n"
5892                    "Stop debugging it? ")))
5893         {
5894           remote_unpush_target ();
5895           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5896         }
5897     }
5898   else
5899     {
5900       if (query (_("Interrupted while waiting for the program.\n"
5901                    "Give up waiting? ")))
5902         quit ();
5903     }
5904
5905   do_cleanups (old_chain);
5906 }
5907
5908 /* Enable/disable target terminal ownership.  Most targets can use
5909    terminal groups to control terminal ownership.  Remote targets are
5910    different in that explicit transfer of ownership to/from GDB/target
5911    is required.  */
5912
5913 static void
5914 remote_terminal_inferior (struct target_ops *self)
5915 {
5916   if (!target_async_permitted)
5917     /* Nothing to do.  */
5918     return;
5919
5920   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5921      idempotent.  The event-loop GDB talking to an asynchronous target
5922      with a synchronous command calls this function from both
5923      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
5924      transfer the terminal to the target when it shouldn't this guard
5925      can go away.  */
5926   if (!remote_async_terminal_ours_p)
5927     return;
5928   delete_file_handler (input_fd);
5929   remote_async_terminal_ours_p = 0;
5930   async_initialize_sigint_signal_handler ();
5931   /* NOTE: At this point we could also register our selves as the
5932      recipient of all input.  Any characters typed could then be
5933      passed on down to the target.  */
5934 }
5935
5936 static void
5937 remote_terminal_ours (struct target_ops *self)
5938 {
5939   if (!target_async_permitted)
5940     /* Nothing to do.  */
5941     return;
5942
5943   /* See FIXME in remote_terminal_inferior.  */
5944   if (remote_async_terminal_ours_p)
5945     return;
5946   async_cleanup_sigint_signal_handler (NULL);
5947   add_file_handler (input_fd, stdin_event_handler, 0);
5948   remote_async_terminal_ours_p = 1;
5949 }
5950
5951 static void
5952 remote_console_output (char *msg)
5953 {
5954   char *p;
5955
5956   for (p = msg; p[0] && p[1]; p += 2)
5957     {
5958       char tb[2];
5959       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5960
5961       tb[0] = c;
5962       tb[1] = 0;
5963       fputs_unfiltered (tb, gdb_stdtarg);
5964     }
5965   gdb_flush (gdb_stdtarg);
5966 }
5967
5968 typedef struct cached_reg
5969 {
5970   int num;
5971   gdb_byte data[MAX_REGISTER_SIZE];
5972 } cached_reg_t;
5973
5974 DEF_VEC_O(cached_reg_t);
5975
5976 typedef struct stop_reply
5977 {
5978   struct notif_event base;
5979
5980   /* The identifier of the thread about this event  */
5981   ptid_t ptid;
5982
5983   /* The remote state this event is associated with.  When the remote
5984      connection, represented by a remote_state object, is closed,
5985      all the associated stop_reply events should be released.  */
5986   struct remote_state *rs;
5987
5988   struct target_waitstatus ws;
5989
5990   /* Expedited registers.  This makes remote debugging a bit more
5991      efficient for those targets that provide critical registers as
5992      part of their normal status mechanism (as another roundtrip to
5993      fetch them is avoided).  */
5994   VEC(cached_reg_t) *regcache;
5995
5996   enum target_stop_reason stop_reason;
5997
5998   CORE_ADDR watch_data_address;
5999
6000   int core;
6001 } *stop_reply_p;
6002
6003 DECLARE_QUEUE_P (stop_reply_p);
6004 DEFINE_QUEUE_P (stop_reply_p);
6005 /* The list of already fetched and acknowledged stop events.  This
6006    queue is used for notification Stop, and other notifications
6007    don't need queue for their events, because the notification events
6008    of Stop can't be consumed immediately, so that events should be
6009    queued first, and be consumed by remote_wait_{ns,as} one per
6010    time.  Other notifications can consume their events immediately,
6011    so queue is not needed for them.  */
6012 static QUEUE (stop_reply_p) *stop_reply_queue;
6013
6014 static void
6015 stop_reply_xfree (struct stop_reply *r)
6016 {
6017   notif_event_xfree ((struct notif_event *) r);
6018 }
6019
6020 /* Return the length of the stop reply queue.  */
6021
6022 static int
6023 stop_reply_queue_length (void)
6024 {
6025   return QUEUE_length (stop_reply_p, stop_reply_queue);
6026 }
6027
6028 static void
6029 remote_notif_stop_parse (struct notif_client *self, char *buf,
6030                          struct notif_event *event)
6031 {
6032   remote_parse_stop_reply (buf, (struct stop_reply *) event);
6033 }
6034
6035 static void
6036 remote_notif_stop_ack (struct notif_client *self, char *buf,
6037                        struct notif_event *event)
6038 {
6039   struct stop_reply *stop_reply = (struct stop_reply *) event;
6040
6041   /* acknowledge */
6042   putpkt ((char *) self->ack_command);
6043
6044   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6045       /* We got an unknown stop reply.  */
6046       error (_("Unknown stop reply"));
6047
6048   push_stop_reply (stop_reply);
6049 }
6050
6051 static int
6052 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6053 {
6054   /* We can't get pending events in remote_notif_process for
6055      notification stop, and we have to do this in remote_wait_ns
6056      instead.  If we fetch all queued events from stub, remote stub
6057      may exit and we have no chance to process them back in
6058      remote_wait_ns.  */
6059   mark_async_event_handler (remote_async_inferior_event_token);
6060   return 0;
6061 }
6062
6063 static void
6064 stop_reply_dtr (struct notif_event *event)
6065 {
6066   struct stop_reply *r = (struct stop_reply *) event;
6067
6068   VEC_free (cached_reg_t, r->regcache);
6069 }
6070
6071 static struct notif_event *
6072 remote_notif_stop_alloc_reply (void)
6073 {
6074   /* We cast to a pointer to the "base class".  */
6075   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6076
6077   r->dtr = stop_reply_dtr;
6078
6079   return r;
6080 }
6081
6082 /* A client of notification Stop.  */
6083
6084 struct notif_client notif_client_stop =
6085 {
6086   "Stop",
6087   "vStopped",
6088   remote_notif_stop_parse,
6089   remote_notif_stop_ack,
6090   remote_notif_stop_can_get_pending_events,
6091   remote_notif_stop_alloc_reply,
6092   REMOTE_NOTIF_STOP,
6093 };
6094
6095 /* A parameter to pass data in and out.  */
6096
6097 struct queue_iter_param
6098 {
6099   void *input;
6100   struct stop_reply *output;
6101 };
6102
6103 /* Determine if THREAD is a pending fork parent thread.  ARG contains
6104    the pid of the process that owns the threads we want to check, or
6105    -1 if we want to check all threads.  */
6106
6107 static int
6108 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6109                         ptid_t thread_ptid)
6110 {
6111   if (ws->kind == TARGET_WAITKIND_FORKED
6112       || ws->kind == TARGET_WAITKIND_VFORKED)
6113     {
6114       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6115         return 1;
6116     }
6117
6118   return 0;
6119 }
6120
6121 /* Check whether EVENT is a fork event, and if it is, remove the
6122    fork child from the context list passed in DATA.  */
6123
6124 static int
6125 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6126                               QUEUE_ITER (stop_reply_p) *iter,
6127                               stop_reply_p event,
6128                               void *data)
6129 {
6130   struct queue_iter_param *param = (struct queue_iter_param *) data;
6131   struct threads_listing_context *context
6132     = (struct threads_listing_context *) param->input;
6133
6134   if (event->ws.kind == TARGET_WAITKIND_FORKED
6135       || event->ws.kind == TARGET_WAITKIND_VFORKED
6136       || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6137     threads_listing_context_remove (&event->ws, context);
6138
6139   return 1;
6140 }
6141
6142 /* If CONTEXT contains any fork child threads that have not been
6143    reported yet, remove them from the CONTEXT list.  If such a
6144    thread exists it is because we are stopped at a fork catchpoint
6145    and have not yet called follow_fork, which will set up the
6146    host-side data structures for the new process.  */
6147
6148 static void
6149 remove_new_fork_children (struct threads_listing_context *context)
6150 {
6151   struct thread_info * thread;
6152   int pid = -1;
6153   struct notif_client *notif = &notif_client_stop;
6154   struct queue_iter_param param;
6155
6156   /* For any threads stopped at a fork event, remove the corresponding
6157      fork child threads from the CONTEXT list.  */
6158   ALL_NON_EXITED_THREADS (thread)
6159     {
6160       struct target_waitstatus *ws;
6161
6162       if (thread->suspend.waitstatus_pending_p)
6163         ws = &thread->suspend.waitstatus;
6164       else
6165         ws = &thread->pending_follow;
6166
6167       if (is_pending_fork_parent (ws, pid, thread->ptid))
6168         {
6169           threads_listing_context_remove (ws, context);
6170         }
6171     }
6172
6173   /* Check for any pending fork events (not reported or processed yet)
6174      in process PID and remove those fork child threads from the
6175      CONTEXT list as well.  */
6176   remote_notif_get_pending_events (notif);
6177   param.input = context;
6178   param.output = NULL;
6179   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6180                  remove_child_of_pending_fork, &param);
6181 }
6182
6183 /* Remove stop replies in the queue if its pid is equal to the given
6184    inferior's pid.  */
6185
6186 static int
6187 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6188                                 QUEUE_ITER (stop_reply_p) *iter,
6189                                 stop_reply_p event,
6190                                 void *data)
6191 {
6192   struct queue_iter_param *param = (struct queue_iter_param *) data;
6193   struct inferior *inf = (struct inferior *) param->input;
6194
6195   if (ptid_get_pid (event->ptid) == inf->pid)
6196     {
6197       stop_reply_xfree (event);
6198       QUEUE_remove_elem (stop_reply_p, q, iter);
6199     }
6200
6201   return 1;
6202 }
6203
6204 /* Discard all pending stop replies of inferior INF.  */
6205
6206 static void
6207 discard_pending_stop_replies (struct inferior *inf)
6208 {
6209   struct queue_iter_param param;
6210   struct stop_reply *reply;
6211   struct remote_state *rs = get_remote_state ();
6212   struct remote_notif_state *rns = rs->notif_state;
6213
6214   /* This function can be notified when an inferior exists.  When the
6215      target is not remote, the notification state is NULL.  */
6216   if (rs->remote_desc == NULL)
6217     return;
6218
6219   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6220
6221   /* Discard the in-flight notification.  */
6222   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6223     {
6224       stop_reply_xfree (reply);
6225       rns->pending_event[notif_client_stop.id] = NULL;
6226     }
6227
6228   param.input = inf;
6229   param.output = NULL;
6230   /* Discard the stop replies we have already pulled with
6231      vStopped.  */
6232   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6233                  remove_stop_reply_for_inferior, &param);
6234 }
6235
6236 /* If its remote state is equal to the given remote state,
6237    remove EVENT from the stop reply queue.  */
6238
6239 static int
6240 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6241                                    QUEUE_ITER (stop_reply_p) *iter,
6242                                    stop_reply_p event,
6243                                    void *data)
6244 {
6245   struct queue_iter_param *param = (struct queue_iter_param *) data;
6246   struct remote_state *rs = (struct remote_state *) param->input;
6247
6248   if (event->rs == rs)
6249     {
6250       stop_reply_xfree (event);
6251       QUEUE_remove_elem (stop_reply_p, q, iter);
6252     }
6253
6254   return 1;
6255 }
6256
6257 /* Discard the stop replies for RS in stop_reply_queue.  */
6258
6259 static void
6260 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6261 {
6262   struct queue_iter_param param;
6263
6264   param.input = rs;
6265   param.output = NULL;
6266   /* Discard the stop replies we have already pulled with
6267      vStopped.  */
6268   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6269                  remove_stop_reply_of_remote_state, &param);
6270 }
6271
6272 /* A parameter to pass data in and out.  */
6273
6274 static int
6275 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6276                                    QUEUE_ITER (stop_reply_p) *iter,
6277                                    stop_reply_p event,
6278                                    void *data)
6279 {
6280   struct queue_iter_param *param = (struct queue_iter_param *) data;
6281   ptid_t *ptid = (ptid_t *) param->input;
6282
6283   if (ptid_match (event->ptid, *ptid))
6284     {
6285       param->output = event;
6286       QUEUE_remove_elem (stop_reply_p, q, iter);
6287       return 0;
6288     }
6289
6290   return 1;
6291 }
6292
6293 /* Remove the first reply in 'stop_reply_queue' which matches
6294    PTID.  */
6295
6296 static struct stop_reply *
6297 remote_notif_remove_queued_reply (ptid_t ptid)
6298 {
6299   struct queue_iter_param param;
6300
6301   param.input = &ptid;
6302   param.output = NULL;
6303
6304   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6305                  remote_notif_remove_once_on_match, &param);
6306   if (notif_debug)
6307     fprintf_unfiltered (gdb_stdlog,
6308                         "notif: discard queued event: 'Stop' in %s\n",
6309                         target_pid_to_str (ptid));
6310
6311   return param.output;
6312 }
6313
6314 /* Look for a queued stop reply belonging to PTID.  If one is found,
6315    remove it from the queue, and return it.  Returns NULL if none is
6316    found.  If there are still queued events left to process, tell the
6317    event loop to get back to target_wait soon.  */
6318
6319 static struct stop_reply *
6320 queued_stop_reply (ptid_t ptid)
6321 {
6322   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6323
6324   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6325     /* There's still at least an event left.  */
6326     mark_async_event_handler (remote_async_inferior_event_token);
6327
6328   return r;
6329 }
6330
6331 /* Push a fully parsed stop reply in the stop reply queue.  Since we
6332    know that we now have at least one queued event left to pass to the
6333    core side, tell the event loop to get back to target_wait soon.  */
6334
6335 static void
6336 push_stop_reply (struct stop_reply *new_event)
6337 {
6338   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6339
6340   if (notif_debug)
6341     fprintf_unfiltered (gdb_stdlog,
6342                         "notif: push 'Stop' %s to queue %d\n",
6343                         target_pid_to_str (new_event->ptid),
6344                         QUEUE_length (stop_reply_p,
6345                                       stop_reply_queue));
6346
6347   mark_async_event_handler (remote_async_inferior_event_token);
6348 }
6349
6350 static int
6351 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6352                               QUEUE_ITER (stop_reply_p) *iter,
6353                               struct stop_reply *event,
6354                               void *data)
6355 {
6356   ptid_t *ptid = (ptid_t *) data;
6357
6358   return !(ptid_equal (*ptid, event->ptid)
6359            && event->ws.kind == TARGET_WAITKIND_STOPPED);
6360 }
6361
6362 /* Returns true if we have a stop reply for PTID.  */
6363
6364 static int
6365 peek_stop_reply (ptid_t ptid)
6366 {
6367   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6368                          stop_reply_match_ptid_and_ws, &ptid);
6369 }
6370
6371 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
6372    starting with P and ending with PEND matches PREFIX.  */
6373
6374 static int
6375 strprefix (const char *p, const char *pend, const char *prefix)
6376 {
6377   for ( ; p < pend; p++, prefix++)
6378     if (*p != *prefix)
6379       return 0;
6380   return *prefix == '\0';
6381 }
6382
6383 /* Parse the stop reply in BUF.  Either the function succeeds, and the
6384    result is stored in EVENT, or throws an error.  */
6385
6386 static void
6387 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6388 {
6389   struct remote_arch_state *rsa = get_remote_arch_state ();
6390   ULONGEST addr;
6391   char *p;
6392   int skipregs = 0;
6393
6394   event->ptid = null_ptid;
6395   event->rs = get_remote_state ();
6396   event->ws.kind = TARGET_WAITKIND_IGNORE;
6397   event->ws.value.integer = 0;
6398   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6399   event->regcache = NULL;
6400   event->core = -1;
6401
6402   switch (buf[0])
6403     {
6404     case 'T':           /* Status with PC, SP, FP, ...  */
6405       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
6406       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
6407             ss = signal number
6408             n... = register number
6409             r... = register contents
6410       */
6411
6412       p = &buf[3];      /* after Txx */
6413       while (*p)
6414         {
6415           char *p1;
6416           int fieldsize;
6417
6418           p1 = strchr (p, ':');
6419           if (p1 == NULL)
6420             error (_("Malformed packet(a) (missing colon): %s\n\
6421 Packet: '%s'\n"),
6422                    p, buf);
6423           if (p == p1)
6424             error (_("Malformed packet(a) (missing register number): %s\n\
6425 Packet: '%s'\n"),
6426                    p, buf);
6427
6428           /* Some "registers" are actually extended stop information.
6429              Note if you're adding a new entry here: GDB 7.9 and
6430              earlier assume that all register "numbers" that start
6431              with an hex digit are real register numbers.  Make sure
6432              the server only sends such a packet if it knows the
6433              client understands it.  */
6434
6435           if (strprefix (p, p1, "thread"))
6436             event->ptid = read_ptid (++p1, &p);
6437           else if (strprefix (p, p1, "syscall_entry"))
6438             {
6439               ULONGEST sysno;
6440
6441               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6442               p = unpack_varlen_hex (++p1, &sysno);
6443               event->ws.value.syscall_number = (int) sysno;
6444             }
6445           else if (strprefix (p, p1, "syscall_return"))
6446             {
6447               ULONGEST sysno;
6448
6449               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6450               p = unpack_varlen_hex (++p1, &sysno);
6451               event->ws.value.syscall_number = (int) sysno;
6452             }
6453           else if (strprefix (p, p1, "watch")
6454                    || strprefix (p, p1, "rwatch")
6455                    || strprefix (p, p1, "awatch"))
6456             {
6457               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6458               p = unpack_varlen_hex (++p1, &addr);
6459               event->watch_data_address = (CORE_ADDR) addr;
6460             }
6461           else if (strprefix (p, p1, "swbreak"))
6462             {
6463               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6464
6465               /* Make sure the stub doesn't forget to indicate support
6466                  with qSupported.  */
6467               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6468                 error (_("Unexpected swbreak stop reason"));
6469
6470               /* The value part is documented as "must be empty",
6471                  though we ignore it, in case we ever decide to make
6472                  use of it in a backward compatible way.  */
6473               p = strchrnul (p1 + 1, ';');
6474             }
6475           else if (strprefix (p, p1, "hwbreak"))
6476             {
6477               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6478
6479               /* Make sure the stub doesn't forget to indicate support
6480                  with qSupported.  */
6481               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6482                 error (_("Unexpected hwbreak stop reason"));
6483
6484               /* See above.  */
6485               p = strchrnul (p1 + 1, ';');
6486             }
6487           else if (strprefix (p, p1, "library"))
6488             {
6489               event->ws.kind = TARGET_WAITKIND_LOADED;
6490               p = strchrnul (p1 + 1, ';');
6491             }
6492           else if (strprefix (p, p1, "replaylog"))
6493             {
6494               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6495               /* p1 will indicate "begin" or "end", but it makes
6496                  no difference for now, so ignore it.  */
6497               p = strchrnul (p1 + 1, ';');
6498             }
6499           else if (strprefix (p, p1, "core"))
6500             {
6501               ULONGEST c;
6502
6503               p = unpack_varlen_hex (++p1, &c);
6504               event->core = c;
6505             }
6506           else if (strprefix (p, p1, "fork"))
6507             {
6508               event->ws.value.related_pid = read_ptid (++p1, &p);
6509               event->ws.kind = TARGET_WAITKIND_FORKED;
6510             }
6511           else if (strprefix (p, p1, "vfork"))
6512             {
6513               event->ws.value.related_pid = read_ptid (++p1, &p);
6514               event->ws.kind = TARGET_WAITKIND_VFORKED;
6515             }
6516           else if (strprefix (p, p1, "vforkdone"))
6517             {
6518               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6519               p = strchrnul (p1 + 1, ';');
6520             }
6521           else if (strprefix (p, p1, "exec"))
6522             {
6523               ULONGEST ignored;
6524               char pathname[PATH_MAX];
6525               int pathlen;
6526
6527               /* Determine the length of the execd pathname.  */
6528               p = unpack_varlen_hex (++p1, &ignored);
6529               pathlen = (p - p1) / 2;
6530
6531               /* Save the pathname for event reporting and for
6532                  the next run command.  */
6533               hex2bin (p1, (gdb_byte *) pathname, pathlen);
6534               pathname[pathlen] = '\0';
6535
6536               /* This is freed during event handling.  */
6537               event->ws.value.execd_pathname = xstrdup (pathname);
6538               event->ws.kind = TARGET_WAITKIND_EXECD;
6539
6540               /* Skip the registers included in this packet, since
6541                  they may be for an architecture different from the
6542                  one used by the original program.  */
6543               skipregs = 1;
6544             }
6545           else if (strprefix (p, p1, "create"))
6546             {
6547               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6548               p = strchrnul (p1 + 1, ';');
6549             }
6550           else
6551             {
6552               ULONGEST pnum;
6553               char *p_temp;
6554
6555               if (skipregs)
6556                 {
6557                   p = strchrnul (p1 + 1, ';');
6558                   p++;
6559                   continue;
6560                 }
6561
6562               /* Maybe a real ``P'' register number.  */
6563               p_temp = unpack_varlen_hex (p, &pnum);
6564               /* If the first invalid character is the colon, we got a
6565                  register number.  Otherwise, it's an unknown stop
6566                  reason.  */
6567               if (p_temp == p1)
6568                 {
6569                   struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6570                   cached_reg_t cached_reg;
6571
6572                   if (reg == NULL)
6573                     error (_("Remote sent bad register number %s: %s\n\
6574 Packet: '%s'\n"),
6575                            hex_string (pnum), p, buf);
6576
6577                   cached_reg.num = reg->regnum;
6578
6579                   p = p1 + 1;
6580                   fieldsize = hex2bin (p, cached_reg.data,
6581                                        register_size (target_gdbarch (),
6582                                                       reg->regnum));
6583                   p += 2 * fieldsize;
6584                   if (fieldsize < register_size (target_gdbarch (),
6585                                                  reg->regnum))
6586                     warning (_("Remote reply is too short: %s"), buf);
6587
6588                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6589                 }
6590               else
6591                 {
6592                   /* Not a number.  Silently skip unknown optional
6593                      info.  */
6594                   p = strchrnul (p1 + 1, ';');
6595                 }
6596             }
6597
6598           if (*p != ';')
6599             error (_("Remote register badly formatted: %s\nhere: %s"),
6600                    buf, p);
6601           ++p;
6602         }
6603
6604       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6605         break;
6606
6607       /* fall through */
6608     case 'S':           /* Old style status, just signal only.  */
6609       {
6610         int sig;
6611
6612         event->ws.kind = TARGET_WAITKIND_STOPPED;
6613         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6614         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6615           event->ws.value.sig = (enum gdb_signal) sig;
6616         else
6617           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6618       }
6619       break;
6620     case 'w':           /* Thread exited.  */
6621       {
6622         char *p;
6623         ULONGEST value;
6624
6625         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6626         p = unpack_varlen_hex (&buf[1], &value);
6627         event->ws.value.integer = value;
6628         if (*p != ';')
6629           error (_("stop reply packet badly formatted: %s"), buf);
6630         event->ptid = read_ptid (++p, NULL);
6631         break;
6632       }
6633     case 'W':           /* Target exited.  */
6634     case 'X':
6635       {
6636         char *p;
6637         int pid;
6638         ULONGEST value;
6639
6640         /* GDB used to accept only 2 hex chars here.  Stubs should
6641            only send more if they detect GDB supports multi-process
6642            support.  */
6643         p = unpack_varlen_hex (&buf[1], &value);
6644
6645         if (buf[0] == 'W')
6646           {
6647             /* The remote process exited.  */
6648             event->ws.kind = TARGET_WAITKIND_EXITED;
6649             event->ws.value.integer = value;
6650           }
6651         else
6652           {
6653             /* The remote process exited with a signal.  */
6654             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6655             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6656               event->ws.value.sig = (enum gdb_signal) value;
6657             else
6658               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6659           }
6660
6661         /* If no process is specified, assume inferior_ptid.  */
6662         pid = ptid_get_pid (inferior_ptid);
6663         if (*p == '\0')
6664           ;
6665         else if (*p == ';')
6666           {
6667             p++;
6668
6669             if (*p == '\0')
6670               ;
6671             else if (startswith (p, "process:"))
6672               {
6673                 ULONGEST upid;
6674
6675                 p += sizeof ("process:") - 1;
6676                 unpack_varlen_hex (p, &upid);
6677                 pid = upid;
6678               }
6679             else
6680               error (_("unknown stop reply packet: %s"), buf);
6681           }
6682         else
6683           error (_("unknown stop reply packet: %s"), buf);
6684         event->ptid = pid_to_ptid (pid);
6685       }
6686       break;
6687     case 'N':
6688       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6689       event->ptid = minus_one_ptid;
6690       break;
6691     }
6692
6693   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6694     error (_("No process or thread specified in stop reply: %s"), buf);
6695 }
6696
6697 /* When the stub wants to tell GDB about a new notification reply, it
6698    sends a notification (%Stop, for example).  Those can come it at
6699    any time, hence, we have to make sure that any pending
6700    putpkt/getpkt sequence we're making is finished, before querying
6701    the stub for more events with the corresponding ack command
6702    (vStopped, for example).  E.g., if we started a vStopped sequence
6703    immediately upon receiving the notification, something like this
6704    could happen:
6705
6706     1.1) --> Hg 1
6707     1.2) <-- OK
6708     1.3) --> g
6709     1.4) <-- %Stop
6710     1.5) --> vStopped
6711     1.6) <-- (registers reply to step #1.3)
6712
6713    Obviously, the reply in step #1.6 would be unexpected to a vStopped
6714    query.
6715
6716    To solve this, whenever we parse a %Stop notification successfully,
6717    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6718    doing whatever we were doing:
6719
6720     2.1) --> Hg 1
6721     2.2) <-- OK
6722     2.3) --> g
6723     2.4) <-- %Stop
6724       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6725     2.5) <-- (registers reply to step #2.3)
6726
6727    Eventualy after step #2.5, we return to the event loop, which
6728    notices there's an event on the
6729    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6730    associated callback --- the function below.  At this point, we're
6731    always safe to start a vStopped sequence. :
6732
6733     2.6) --> vStopped
6734     2.7) <-- T05 thread:2
6735     2.8) --> vStopped
6736     2.9) --> OK
6737 */
6738
6739 void
6740 remote_notif_get_pending_events (struct notif_client *nc)
6741 {
6742   struct remote_state *rs = get_remote_state ();
6743
6744   if (rs->notif_state->pending_event[nc->id] != NULL)
6745     {
6746       if (notif_debug)
6747         fprintf_unfiltered (gdb_stdlog,
6748                             "notif: process: '%s' ack pending event\n",
6749                             nc->name);
6750
6751       /* acknowledge */
6752       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6753       rs->notif_state->pending_event[nc->id] = NULL;
6754
6755       while (1)
6756         {
6757           getpkt (&rs->buf, &rs->buf_size, 0);
6758           if (strcmp (rs->buf, "OK") == 0)
6759             break;
6760           else
6761             remote_notif_ack (nc, rs->buf);
6762         }
6763     }
6764   else
6765     {
6766       if (notif_debug)
6767         fprintf_unfiltered (gdb_stdlog,
6768                             "notif: process: '%s' no pending reply\n",
6769                             nc->name);
6770     }
6771 }
6772
6773 /* Called when it is decided that STOP_REPLY holds the info of the
6774    event that is to be returned to the core.  This function always
6775    destroys STOP_REPLY.  */
6776
6777 static ptid_t
6778 process_stop_reply (struct stop_reply *stop_reply,
6779                     struct target_waitstatus *status)
6780 {
6781   ptid_t ptid;
6782
6783   *status = stop_reply->ws;
6784   ptid = stop_reply->ptid;
6785
6786   /* If no thread/process was reported by the stub, assume the current
6787      inferior.  */
6788   if (ptid_equal (ptid, null_ptid))
6789     ptid = inferior_ptid;
6790
6791   if (status->kind != TARGET_WAITKIND_EXITED
6792       && status->kind != TARGET_WAITKIND_SIGNALLED
6793       && status->kind != TARGET_WAITKIND_NO_RESUMED)
6794     {
6795       struct private_thread_info *remote_thr;
6796
6797       /* Expedited registers.  */
6798       if (stop_reply->regcache)
6799         {
6800           struct regcache *regcache
6801             = get_thread_arch_regcache (ptid, target_gdbarch ());
6802           cached_reg_t *reg;
6803           int ix;
6804
6805           for (ix = 0;
6806                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6807                ix++)
6808             regcache_raw_supply (regcache, reg->num, reg->data);
6809           VEC_free (cached_reg_t, stop_reply->regcache);
6810         }
6811
6812       remote_notice_new_inferior (ptid, 0);
6813       remote_thr = demand_private_info (ptid);
6814       remote_thr->core = stop_reply->core;
6815       remote_thr->stop_reason = stop_reply->stop_reason;
6816       remote_thr->watch_data_address = stop_reply->watch_data_address;
6817     }
6818
6819   stop_reply_xfree (stop_reply);
6820   return ptid;
6821 }
6822
6823 /* The non-stop mode version of target_wait.  */
6824
6825 static ptid_t
6826 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6827 {
6828   struct remote_state *rs = get_remote_state ();
6829   struct stop_reply *stop_reply;
6830   int ret;
6831   int is_notif = 0;
6832
6833   /* If in non-stop mode, get out of getpkt even if a
6834      notification is received.  */
6835
6836   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6837                               0 /* forever */, &is_notif);
6838   while (1)
6839     {
6840       if (ret != -1 && !is_notif)
6841         switch (rs->buf[0])
6842           {
6843           case 'E':             /* Error of some sort.  */
6844             /* We're out of sync with the target now.  Did it continue
6845                or not?  We can't tell which thread it was in non-stop,
6846                so just ignore this.  */
6847             warning (_("Remote failure reply: %s"), rs->buf);
6848             break;
6849           case 'O':             /* Console output.  */
6850             remote_console_output (rs->buf + 1);
6851             break;
6852           default:
6853             warning (_("Invalid remote reply: %s"), rs->buf);
6854             break;
6855           }
6856
6857       /* Acknowledge a pending stop reply that may have arrived in the
6858          mean time.  */
6859       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6860         remote_notif_get_pending_events (&notif_client_stop);
6861
6862       /* If indeed we noticed a stop reply, we're done.  */
6863       stop_reply = queued_stop_reply (ptid);
6864       if (stop_reply != NULL)
6865         return process_stop_reply (stop_reply, status);
6866
6867       /* Still no event.  If we're just polling for an event, then
6868          return to the event loop.  */
6869       if (options & TARGET_WNOHANG)
6870         {
6871           status->kind = TARGET_WAITKIND_IGNORE;
6872           return minus_one_ptid;
6873         }
6874
6875       /* Otherwise do a blocking wait.  */
6876       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6877                                   1 /* forever */, &is_notif);
6878     }
6879 }
6880
6881 /* Wait until the remote machine stops, then return, storing status in
6882    STATUS just as `wait' would.  */
6883
6884 static ptid_t
6885 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6886 {
6887   struct remote_state *rs = get_remote_state ();
6888   ptid_t event_ptid = null_ptid;
6889   char *buf;
6890   struct stop_reply *stop_reply;
6891
6892  again:
6893
6894   status->kind = TARGET_WAITKIND_IGNORE;
6895   status->value.integer = 0;
6896
6897   stop_reply = queued_stop_reply (ptid);
6898   if (stop_reply != NULL)
6899     return process_stop_reply (stop_reply, status);
6900
6901   if (rs->cached_wait_status)
6902     /* Use the cached wait status, but only once.  */
6903     rs->cached_wait_status = 0;
6904   else
6905     {
6906       int ret;
6907       int is_notif;
6908       int forever = ((options & TARGET_WNOHANG) == 0
6909                      && wait_forever_enabled_p);
6910
6911       if (!rs->waiting_for_stop_reply)
6912         {
6913           status->kind = TARGET_WAITKIND_NO_RESUMED;
6914           return minus_one_ptid;
6915         }
6916
6917       if (!target_is_async_p ())
6918         {
6919           ofunc = signal (SIGINT, sync_remote_interrupt);
6920           /* If the user hit C-c before this packet, or between packets,
6921              pretend that it was hit right here.  */
6922           if (check_quit_flag ())
6923             sync_remote_interrupt (SIGINT);
6924         }
6925
6926       /* FIXME: cagney/1999-09-27: If we're in async mode we should
6927          _never_ wait for ever -> test on target_is_async_p().
6928          However, before we do that we need to ensure that the caller
6929          knows how to take the target into/out of async mode.  */
6930       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6931                                   forever, &is_notif);
6932
6933       if (!target_is_async_p ())
6934         signal (SIGINT, ofunc);
6935
6936       /* GDB gets a notification.  Return to core as this event is
6937          not interesting.  */
6938       if (ret != -1 && is_notif)
6939         return minus_one_ptid;
6940
6941       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6942         return minus_one_ptid;
6943     }
6944
6945   buf = rs->buf;
6946
6947   /* Assume that the target has acknowledged Ctrl-C unless we receive
6948      an 'F' or 'O' packet.  */
6949   if (buf[0] != 'F' && buf[0] != 'O')
6950     rs->ctrlc_pending_p = 0;
6951
6952   switch (buf[0])
6953     {
6954     case 'E':           /* Error of some sort.  */
6955       /* We're out of sync with the target now.  Did it continue or
6956          not?  Not is more likely, so report a stop.  */
6957       rs->waiting_for_stop_reply = 0;
6958
6959       warning (_("Remote failure reply: %s"), buf);
6960       status->kind = TARGET_WAITKIND_STOPPED;
6961       status->value.sig = GDB_SIGNAL_0;
6962       break;
6963     case 'F':           /* File-I/O request.  */
6964       /* GDB may access the inferior memory while handling the File-I/O
6965          request, but we don't want GDB accessing memory while waiting
6966          for a stop reply.  See the comments in putpkt_binary.  Set
6967          waiting_for_stop_reply to 0 temporarily.  */
6968       rs->waiting_for_stop_reply = 0;
6969       remote_fileio_request (buf, rs->ctrlc_pending_p);
6970       rs->ctrlc_pending_p = 0;
6971       /* GDB handled the File-I/O request, and the target is running
6972          again.  Keep waiting for events.  */
6973       rs->waiting_for_stop_reply = 1;
6974       break;
6975     case 'N': case 'T': case 'S': case 'X': case 'W':
6976       {
6977         struct stop_reply *stop_reply;
6978
6979         /* There is a stop reply to handle.  */
6980         rs->waiting_for_stop_reply = 0;
6981
6982         stop_reply
6983           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6984                                                       rs->buf);
6985
6986         event_ptid = process_stop_reply (stop_reply, status);
6987         break;
6988       }
6989     case 'O':           /* Console output.  */
6990       remote_console_output (buf + 1);
6991       break;
6992     case '\0':
6993       if (rs->last_sent_signal != GDB_SIGNAL_0)
6994         {
6995           /* Zero length reply means that we tried 'S' or 'C' and the
6996              remote system doesn't support it.  */
6997           target_terminal_ours_for_output ();
6998           printf_filtered
6999             ("Can't send signals to this remote system.  %s not sent.\n",
7000              gdb_signal_to_name (rs->last_sent_signal));
7001           rs->last_sent_signal = GDB_SIGNAL_0;
7002           target_terminal_inferior ();
7003
7004           strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
7005           putpkt ((char *) buf);
7006           break;
7007         }
7008       /* else fallthrough */
7009     default:
7010       warning (_("Invalid remote reply: %s"), buf);
7011       break;
7012     }
7013
7014   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7015     return minus_one_ptid;
7016   else if (status->kind == TARGET_WAITKIND_IGNORE)
7017     {
7018       /* Nothing interesting happened.  If we're doing a non-blocking
7019          poll, we're done.  Otherwise, go back to waiting.  */
7020       if (options & TARGET_WNOHANG)
7021         return minus_one_ptid;
7022       else
7023         goto again;
7024     }
7025   else if (status->kind != TARGET_WAITKIND_EXITED
7026            && status->kind != TARGET_WAITKIND_SIGNALLED)
7027     {
7028       if (!ptid_equal (event_ptid, null_ptid))
7029         record_currthread (rs, event_ptid);
7030       else
7031         event_ptid = inferior_ptid;
7032     }
7033   else
7034     /* A process exit.  Invalidate our notion of current thread.  */
7035     record_currthread (rs, minus_one_ptid);
7036
7037   return event_ptid;
7038 }
7039
7040 /* Wait until the remote machine stops, then return, storing status in
7041    STATUS just as `wait' would.  */
7042
7043 static ptid_t
7044 remote_wait (struct target_ops *ops,
7045              ptid_t ptid, struct target_waitstatus *status, int options)
7046 {
7047   ptid_t event_ptid;
7048
7049   if (target_is_non_stop_p ())
7050     event_ptid = remote_wait_ns (ptid, status, options);
7051   else
7052     event_ptid = remote_wait_as (ptid, status, options);
7053
7054   if (target_is_async_p ())
7055     {
7056       /* If there are are events left in the queue tell the event loop
7057          to return here.  */
7058       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7059         mark_async_event_handler (remote_async_inferior_event_token);
7060     }
7061
7062   return event_ptid;
7063 }
7064
7065 /* Fetch a single register using a 'p' packet.  */
7066
7067 static int
7068 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7069 {
7070   struct remote_state *rs = get_remote_state ();
7071   char *buf, *p;
7072   char regp[MAX_REGISTER_SIZE];
7073   int i;
7074
7075   if (packet_support (PACKET_p) == PACKET_DISABLE)
7076     return 0;
7077
7078   if (reg->pnum == -1)
7079     return 0;
7080
7081   p = rs->buf;
7082   *p++ = 'p';
7083   p += hexnumstr (p, reg->pnum);
7084   *p++ = '\0';
7085   putpkt (rs->buf);
7086   getpkt (&rs->buf, &rs->buf_size, 0);
7087
7088   buf = rs->buf;
7089
7090   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7091     {
7092     case PACKET_OK:
7093       break;
7094     case PACKET_UNKNOWN:
7095       return 0;
7096     case PACKET_ERROR:
7097       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7098              gdbarch_register_name (get_regcache_arch (regcache), 
7099                                     reg->regnum), 
7100              buf);
7101     }
7102
7103   /* If this register is unfetchable, tell the regcache.  */
7104   if (buf[0] == 'x')
7105     {
7106       regcache_raw_supply (regcache, reg->regnum, NULL);
7107       return 1;
7108     }
7109
7110   /* Otherwise, parse and supply the value.  */
7111   p = buf;
7112   i = 0;
7113   while (p[0] != 0)
7114     {
7115       if (p[1] == 0)
7116         error (_("fetch_register_using_p: early buf termination"));
7117
7118       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7119       p += 2;
7120     }
7121   regcache_raw_supply (regcache, reg->regnum, regp);
7122   return 1;
7123 }
7124
7125 /* Fetch the registers included in the target's 'g' packet.  */
7126
7127 static int
7128 send_g_packet (void)
7129 {
7130   struct remote_state *rs = get_remote_state ();
7131   int buf_len;
7132
7133   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7134   remote_send (&rs->buf, &rs->buf_size);
7135
7136   /* We can get out of synch in various cases.  If the first character
7137      in the buffer is not a hex character, assume that has happened
7138      and try to fetch another packet to read.  */
7139   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7140          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7141          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7142          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
7143     {
7144       if (remote_debug)
7145         fprintf_unfiltered (gdb_stdlog,
7146                             "Bad register packet; fetching a new packet\n");
7147       getpkt (&rs->buf, &rs->buf_size, 0);
7148     }
7149
7150   buf_len = strlen (rs->buf);
7151
7152   /* Sanity check the received packet.  */
7153   if (buf_len % 2 != 0)
7154     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7155
7156   return buf_len / 2;
7157 }
7158
7159 static void
7160 process_g_packet (struct regcache *regcache)
7161 {
7162   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7163   struct remote_state *rs = get_remote_state ();
7164   struct remote_arch_state *rsa = get_remote_arch_state ();
7165   int i, buf_len;
7166   char *p;
7167   char *regs;
7168
7169   buf_len = strlen (rs->buf);
7170
7171   /* Further sanity checks, with knowledge of the architecture.  */
7172   if (buf_len > 2 * rsa->sizeof_g_packet)
7173     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7174
7175   /* Save the size of the packet sent to us by the target.  It is used
7176      as a heuristic when determining the max size of packets that the
7177      target can safely receive.  */
7178   if (rsa->actual_register_packet_size == 0)
7179     rsa->actual_register_packet_size = buf_len;
7180
7181   /* If this is smaller than we guessed the 'g' packet would be,
7182      update our records.  A 'g' reply that doesn't include a register's
7183      value implies either that the register is not available, or that
7184      the 'p' packet must be used.  */
7185   if (buf_len < 2 * rsa->sizeof_g_packet)
7186     {
7187       rsa->sizeof_g_packet = buf_len / 2;
7188
7189       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7190         {
7191           if (rsa->regs[i].pnum == -1)
7192             continue;
7193
7194           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7195             rsa->regs[i].in_g_packet = 0;
7196           else
7197             rsa->regs[i].in_g_packet = 1;
7198         }
7199     }
7200
7201   regs = (char *) alloca (rsa->sizeof_g_packet);
7202
7203   /* Unimplemented registers read as all bits zero.  */
7204   memset (regs, 0, rsa->sizeof_g_packet);
7205
7206   /* Reply describes registers byte by byte, each byte encoded as two
7207      hex characters.  Suck them all up, then supply them to the
7208      register cacheing/storage mechanism.  */
7209
7210   p = rs->buf;
7211   for (i = 0; i < rsa->sizeof_g_packet; i++)
7212     {
7213       if (p[0] == 0 || p[1] == 0)
7214         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
7215         internal_error (__FILE__, __LINE__,
7216                         _("unexpected end of 'g' packet reply"));
7217
7218       if (p[0] == 'x' && p[1] == 'x')
7219         regs[i] = 0;            /* 'x' */
7220       else
7221         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7222       p += 2;
7223     }
7224
7225   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7226     {
7227       struct packet_reg *r = &rsa->regs[i];
7228
7229       if (r->in_g_packet)
7230         {
7231           if (r->offset * 2 >= strlen (rs->buf))
7232             /* This shouldn't happen - we adjusted in_g_packet above.  */
7233             internal_error (__FILE__, __LINE__,
7234                             _("unexpected end of 'g' packet reply"));
7235           else if (rs->buf[r->offset * 2] == 'x')
7236             {
7237               gdb_assert (r->offset * 2 < strlen (rs->buf));
7238               /* The register isn't available, mark it as such (at
7239                  the same time setting the value to zero).  */
7240               regcache_raw_supply (regcache, r->regnum, NULL);
7241             }
7242           else
7243             regcache_raw_supply (regcache, r->regnum,
7244                                  regs + r->offset);
7245         }
7246     }
7247 }
7248
7249 static void
7250 fetch_registers_using_g (struct regcache *regcache)
7251 {
7252   send_g_packet ();
7253   process_g_packet (regcache);
7254 }
7255
7256 /* Make the remote selected traceframe match GDB's selected
7257    traceframe.  */
7258
7259 static void
7260 set_remote_traceframe (void)
7261 {
7262   int newnum;
7263   struct remote_state *rs = get_remote_state ();
7264
7265   if (rs->remote_traceframe_number == get_traceframe_number ())
7266     return;
7267
7268   /* Avoid recursion, remote_trace_find calls us again.  */
7269   rs->remote_traceframe_number = get_traceframe_number ();
7270
7271   newnum = target_trace_find (tfind_number,
7272                               get_traceframe_number (), 0, 0, NULL);
7273
7274   /* Should not happen.  If it does, all bets are off.  */
7275   if (newnum != get_traceframe_number ())
7276     warning (_("could not set remote traceframe"));
7277 }
7278
7279 static void
7280 remote_fetch_registers (struct target_ops *ops,
7281                         struct regcache *regcache, int regnum)
7282 {
7283   struct remote_arch_state *rsa = get_remote_arch_state ();
7284   int i;
7285
7286   set_remote_traceframe ();
7287   set_general_thread (inferior_ptid);
7288
7289   if (regnum >= 0)
7290     {
7291       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7292
7293       gdb_assert (reg != NULL);
7294
7295       /* If this register might be in the 'g' packet, try that first -
7296          we are likely to read more than one register.  If this is the
7297          first 'g' packet, we might be overly optimistic about its
7298          contents, so fall back to 'p'.  */
7299       if (reg->in_g_packet)
7300         {
7301           fetch_registers_using_g (regcache);
7302           if (reg->in_g_packet)
7303             return;
7304         }
7305
7306       if (fetch_register_using_p (regcache, reg))
7307         return;
7308
7309       /* This register is not available.  */
7310       regcache_raw_supply (regcache, reg->regnum, NULL);
7311
7312       return;
7313     }
7314
7315   fetch_registers_using_g (regcache);
7316
7317   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7318     if (!rsa->regs[i].in_g_packet)
7319       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7320         {
7321           /* This register is not available.  */
7322           regcache_raw_supply (regcache, i, NULL);
7323         }
7324 }
7325
7326 /* Prepare to store registers.  Since we may send them all (using a
7327    'G' request), we have to read out the ones we don't want to change
7328    first.  */
7329
7330 static void
7331 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7332 {
7333   struct remote_arch_state *rsa = get_remote_arch_state ();
7334   int i;
7335   gdb_byte buf[MAX_REGISTER_SIZE];
7336
7337   /* Make sure the entire registers array is valid.  */
7338   switch (packet_support (PACKET_P))
7339     {
7340     case PACKET_DISABLE:
7341     case PACKET_SUPPORT_UNKNOWN:
7342       /* Make sure all the necessary registers are cached.  */
7343       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7344         if (rsa->regs[i].in_g_packet)
7345           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7346       break;
7347     case PACKET_ENABLE:
7348       break;
7349     }
7350 }
7351
7352 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
7353    packet was not recognized.  */
7354
7355 static int
7356 store_register_using_P (const struct regcache *regcache, 
7357                         struct packet_reg *reg)
7358 {
7359   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7360   struct remote_state *rs = get_remote_state ();
7361   /* Try storing a single register.  */
7362   char *buf = rs->buf;
7363   gdb_byte regp[MAX_REGISTER_SIZE];
7364   char *p;
7365
7366   if (packet_support (PACKET_P) == PACKET_DISABLE)
7367     return 0;
7368
7369   if (reg->pnum == -1)
7370     return 0;
7371
7372   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7373   p = buf + strlen (buf);
7374   regcache_raw_collect (regcache, reg->regnum, regp);
7375   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7376   putpkt (rs->buf);
7377   getpkt (&rs->buf, &rs->buf_size, 0);
7378
7379   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7380     {
7381     case PACKET_OK:
7382       return 1;
7383     case PACKET_ERROR:
7384       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7385              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7386     case PACKET_UNKNOWN:
7387       return 0;
7388     default:
7389       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7390     }
7391 }
7392
7393 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7394    contents of the register cache buffer.  FIXME: ignores errors.  */
7395
7396 static void
7397 store_registers_using_G (const struct regcache *regcache)
7398 {
7399   struct remote_state *rs = get_remote_state ();
7400   struct remote_arch_state *rsa = get_remote_arch_state ();
7401   gdb_byte *regs;
7402   char *p;
7403
7404   /* Extract all the registers in the regcache copying them into a
7405      local buffer.  */
7406   {
7407     int i;
7408
7409     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7410     memset (regs, 0, rsa->sizeof_g_packet);
7411     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7412       {
7413         struct packet_reg *r = &rsa->regs[i];
7414
7415         if (r->in_g_packet)
7416           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7417       }
7418   }
7419
7420   /* Command describes registers byte by byte,
7421      each byte encoded as two hex characters.  */
7422   p = rs->buf;
7423   *p++ = 'G';
7424   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7425      updated.  */
7426   bin2hex (regs, p, rsa->sizeof_g_packet);
7427   putpkt (rs->buf);
7428   getpkt (&rs->buf, &rs->buf_size, 0);
7429   if (packet_check_result (rs->buf) == PACKET_ERROR)
7430     error (_("Could not write registers; remote failure reply '%s'"), 
7431            rs->buf);
7432 }
7433
7434 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7435    of the register cache buffer.  FIXME: ignores errors.  */
7436
7437 static void
7438 remote_store_registers (struct target_ops *ops,
7439                         struct regcache *regcache, int regnum)
7440 {
7441   struct remote_arch_state *rsa = get_remote_arch_state ();
7442   int i;
7443
7444   set_remote_traceframe ();
7445   set_general_thread (inferior_ptid);
7446
7447   if (regnum >= 0)
7448     {
7449       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7450
7451       gdb_assert (reg != NULL);
7452
7453       /* Always prefer to store registers using the 'P' packet if
7454          possible; we often change only a small number of registers.
7455          Sometimes we change a larger number; we'd need help from a
7456          higher layer to know to use 'G'.  */
7457       if (store_register_using_P (regcache, reg))
7458         return;
7459
7460       /* For now, don't complain if we have no way to write the
7461          register.  GDB loses track of unavailable registers too
7462          easily.  Some day, this may be an error.  We don't have
7463          any way to read the register, either...  */
7464       if (!reg->in_g_packet)
7465         return;
7466
7467       store_registers_using_G (regcache);
7468       return;
7469     }
7470
7471   store_registers_using_G (regcache);
7472
7473   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7474     if (!rsa->regs[i].in_g_packet)
7475       if (!store_register_using_P (regcache, &rsa->regs[i]))
7476         /* See above for why we do not issue an error here.  */
7477         continue;
7478 }
7479 \f
7480
7481 /* Return the number of hex digits in num.  */
7482
7483 static int
7484 hexnumlen (ULONGEST num)
7485 {
7486   int i;
7487
7488   for (i = 0; num != 0; i++)
7489     num >>= 4;
7490
7491   return max (i, 1);
7492 }
7493
7494 /* Set BUF to the minimum number of hex digits representing NUM.  */
7495
7496 static int
7497 hexnumstr (char *buf, ULONGEST num)
7498 {
7499   int len = hexnumlen (num);
7500
7501   return hexnumnstr (buf, num, len);
7502 }
7503
7504
7505 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
7506
7507 static int
7508 hexnumnstr (char *buf, ULONGEST num, int width)
7509 {
7510   int i;
7511
7512   buf[width] = '\0';
7513
7514   for (i = width - 1; i >= 0; i--)
7515     {
7516       buf[i] = "0123456789abcdef"[(num & 0xf)];
7517       num >>= 4;
7518     }
7519
7520   return width;
7521 }
7522
7523 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
7524
7525 static CORE_ADDR
7526 remote_address_masked (CORE_ADDR addr)
7527 {
7528   unsigned int address_size = remote_address_size;
7529
7530   /* If "remoteaddresssize" was not set, default to target address size.  */
7531   if (!address_size)
7532     address_size = gdbarch_addr_bit (target_gdbarch ());
7533
7534   if (address_size > 0
7535       && address_size < (sizeof (ULONGEST) * 8))
7536     {
7537       /* Only create a mask when that mask can safely be constructed
7538          in a ULONGEST variable.  */
7539       ULONGEST mask = 1;
7540
7541       mask = (mask << address_size) - 1;
7542       addr &= mask;
7543     }
7544   return addr;
7545 }
7546
7547 /* Determine whether the remote target supports binary downloading.
7548    This is accomplished by sending a no-op memory write of zero length
7549    to the target at the specified address. It does not suffice to send
7550    the whole packet, since many stubs strip the eighth bit and
7551    subsequently compute a wrong checksum, which causes real havoc with
7552    remote_write_bytes.
7553
7554    NOTE: This can still lose if the serial line is not eight-bit
7555    clean.  In cases like this, the user should clear "remote
7556    X-packet".  */
7557
7558 static void
7559 check_binary_download (CORE_ADDR addr)
7560 {
7561   struct remote_state *rs = get_remote_state ();
7562
7563   switch (packet_support (PACKET_X))
7564     {
7565     case PACKET_DISABLE:
7566       break;
7567     case PACKET_ENABLE:
7568       break;
7569     case PACKET_SUPPORT_UNKNOWN:
7570       {
7571         char *p;
7572
7573         p = rs->buf;
7574         *p++ = 'X';
7575         p += hexnumstr (p, (ULONGEST) addr);
7576         *p++ = ',';
7577         p += hexnumstr (p, (ULONGEST) 0);
7578         *p++ = ':';
7579         *p = '\0';
7580
7581         putpkt_binary (rs->buf, (int) (p - rs->buf));
7582         getpkt (&rs->buf, &rs->buf_size, 0);
7583
7584         if (rs->buf[0] == '\0')
7585           {
7586             if (remote_debug)
7587               fprintf_unfiltered (gdb_stdlog,
7588                                   "binary downloading NOT "
7589                                   "supported by target\n");
7590             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7591           }
7592         else
7593           {
7594             if (remote_debug)
7595               fprintf_unfiltered (gdb_stdlog,
7596                                   "binary downloading supported by target\n");
7597             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7598           }
7599         break;
7600       }
7601     }
7602 }
7603
7604 /* Helper function to resize the payload in order to try to get a good
7605    alignment.  We try to write an amount of data such that the next write will
7606    start on an address aligned on REMOTE_ALIGN_WRITES.  */
7607
7608 static int
7609 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7610 {
7611   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7612 }
7613
7614 /* Write memory data directly to the remote machine.
7615    This does not inform the data cache; the data cache uses this.
7616    HEADER is the starting part of the packet.
7617    MEMADDR is the address in the remote memory space.
7618    MYADDR is the address of the buffer in our space.
7619    LEN_UNITS is the number of addressable units to write.
7620    UNIT_SIZE is the length in bytes of an addressable unit.
7621    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7622    should send data as binary ('X'), or hex-encoded ('M').
7623
7624    The function creates packet of the form
7625        <HEADER><ADDRESS>,<LENGTH>:<DATA>
7626
7627    where encoding of <DATA> is terminated by PACKET_FORMAT.
7628
7629    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7630    are omitted.
7631
7632    Return the transferred status, error or OK (an
7633    'enum target_xfer_status' value).  Save the number of addressable units
7634    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
7635
7636    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7637    exchange between gdb and the stub could look like (?? in place of the
7638    checksum):
7639
7640    -> $m1000,4#??
7641    <- aaaabbbbccccdddd
7642
7643    -> $M1000,3:eeeeffffeeee#??
7644    <- OK
7645
7646    -> $m1000,4#??
7647    <- eeeeffffeeeedddd  */
7648
7649 static enum target_xfer_status
7650 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7651                         const gdb_byte *myaddr, ULONGEST len_units,
7652                         int unit_size, ULONGEST *xfered_len_units,
7653                         char packet_format, int use_length)
7654 {
7655   struct remote_state *rs = get_remote_state ();
7656   char *p;
7657   char *plen = NULL;
7658   int plenlen = 0;
7659   int todo_units;
7660   int units_written;
7661   int payload_capacity_bytes;
7662   int payload_length_bytes;
7663
7664   if (packet_format != 'X' && packet_format != 'M')
7665     internal_error (__FILE__, __LINE__,
7666                     _("remote_write_bytes_aux: bad packet format"));
7667
7668   if (len_units == 0)
7669     return TARGET_XFER_EOF;
7670
7671   payload_capacity_bytes = get_memory_write_packet_size ();
7672
7673   /* The packet buffer will be large enough for the payload;
7674      get_memory_packet_size ensures this.  */
7675   rs->buf[0] = '\0';
7676
7677   /* Compute the size of the actual payload by subtracting out the
7678      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
7679
7680   payload_capacity_bytes -= strlen ("$,:#NN");
7681   if (!use_length)
7682     /* The comma won't be used.  */
7683     payload_capacity_bytes += 1;
7684   payload_capacity_bytes -= strlen (header);
7685   payload_capacity_bytes -= hexnumlen (memaddr);
7686
7687   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
7688
7689   strcat (rs->buf, header);
7690   p = rs->buf + strlen (header);
7691
7692   /* Compute a best guess of the number of bytes actually transfered.  */
7693   if (packet_format == 'X')
7694     {
7695       /* Best guess at number of bytes that will fit.  */
7696       todo_units = min (len_units, payload_capacity_bytes / unit_size);
7697       if (use_length)
7698         payload_capacity_bytes -= hexnumlen (todo_units);
7699       todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7700     }
7701   else
7702     {
7703       /* Number of bytes that will fit.  */
7704       todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7705       if (use_length)
7706         payload_capacity_bytes -= hexnumlen (todo_units);
7707       todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7708     }
7709
7710   if (todo_units <= 0)
7711     internal_error (__FILE__, __LINE__,
7712                     _("minimum packet size too small to write data"));
7713
7714   /* If we already need another packet, then try to align the end
7715      of this packet to a useful boundary.  */
7716   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7717     todo_units = align_for_efficient_write (todo_units, memaddr);
7718
7719   /* Append "<memaddr>".  */
7720   memaddr = remote_address_masked (memaddr);
7721   p += hexnumstr (p, (ULONGEST) memaddr);
7722
7723   if (use_length)
7724     {
7725       /* Append ",".  */
7726       *p++ = ',';
7727
7728       /* Append the length and retain its location and size.  It may need to be
7729          adjusted once the packet body has been created.  */
7730       plen = p;
7731       plenlen = hexnumstr (p, (ULONGEST) todo_units);
7732       p += plenlen;
7733     }
7734
7735   /* Append ":".  */
7736   *p++ = ':';
7737   *p = '\0';
7738
7739   /* Append the packet body.  */
7740   if (packet_format == 'X')
7741     {
7742       /* Binary mode.  Send target system values byte by byte, in
7743          increasing byte addresses.  Only escape certain critical
7744          characters.  */
7745       payload_length_bytes =
7746           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7747                                 &units_written, payload_capacity_bytes);
7748
7749       /* If not all TODO units fit, then we'll need another packet.  Make
7750          a second try to keep the end of the packet aligned.  Don't do
7751          this if the packet is tiny.  */
7752       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7753         {
7754           int new_todo_units;
7755
7756           new_todo_units = align_for_efficient_write (units_written, memaddr);
7757
7758           if (new_todo_units != units_written)
7759             payload_length_bytes =
7760                 remote_escape_output (myaddr, new_todo_units, unit_size,
7761                                       (gdb_byte *) p, &units_written,
7762                                       payload_capacity_bytes);
7763         }
7764
7765       p += payload_length_bytes;
7766       if (use_length && units_written < todo_units)
7767         {
7768           /* Escape chars have filled up the buffer prematurely,
7769              and we have actually sent fewer units than planned.
7770              Fix-up the length field of the packet.  Use the same
7771              number of characters as before.  */
7772           plen += hexnumnstr (plen, (ULONGEST) units_written,
7773                               plenlen);
7774           *plen = ':';  /* overwrite \0 from hexnumnstr() */
7775         }
7776     }
7777   else
7778     {
7779       /* Normal mode: Send target system values byte by byte, in
7780          increasing byte addresses.  Each byte is encoded as a two hex
7781          value.  */
7782       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7783       units_written = todo_units;
7784     }
7785
7786   putpkt_binary (rs->buf, (int) (p - rs->buf));
7787   getpkt (&rs->buf, &rs->buf_size, 0);
7788
7789   if (rs->buf[0] == 'E')
7790     return TARGET_XFER_E_IO;
7791
7792   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7793      send fewer units than we'd planned.  */
7794   *xfered_len_units = (ULONGEST) units_written;
7795   return TARGET_XFER_OK;
7796 }
7797
7798 /* Write memory data directly to the remote machine.
7799    This does not inform the data cache; the data cache uses this.
7800    MEMADDR is the address in the remote memory space.
7801    MYADDR is the address of the buffer in our space.
7802    LEN is the number of bytes.
7803
7804    Return the transferred status, error or OK (an
7805    'enum target_xfer_status' value).  Save the number of bytes
7806    transferred in *XFERED_LEN.  Only transfer a single packet.  */
7807
7808 static enum target_xfer_status
7809 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7810                     int unit_size, ULONGEST *xfered_len)
7811 {
7812   char *packet_format = 0;
7813
7814   /* Check whether the target supports binary download.  */
7815   check_binary_download (memaddr);
7816
7817   switch (packet_support (PACKET_X))
7818     {
7819     case PACKET_ENABLE:
7820       packet_format = "X";
7821       break;
7822     case PACKET_DISABLE:
7823       packet_format = "M";
7824       break;
7825     case PACKET_SUPPORT_UNKNOWN:
7826       internal_error (__FILE__, __LINE__,
7827                       _("remote_write_bytes: bad internal state"));
7828     default:
7829       internal_error (__FILE__, __LINE__, _("bad switch"));
7830     }
7831
7832   return remote_write_bytes_aux (packet_format,
7833                                  memaddr, myaddr, len, unit_size, xfered_len,
7834                                  packet_format[0], 1);
7835 }
7836
7837 /* Read memory data directly from the remote machine.
7838    This does not use the data cache; the data cache uses this.
7839    MEMADDR is the address in the remote memory space.
7840    MYADDR is the address of the buffer in our space.
7841    LEN_UNITS is the number of addressable memory units to read..
7842    UNIT_SIZE is the length in bytes of an addressable unit.
7843
7844    Return the transferred status, error or OK (an
7845    'enum target_xfer_status' value).  Save the number of bytes
7846    transferred in *XFERED_LEN_UNITS.
7847
7848    See the comment of remote_write_bytes_aux for an example of
7849    memory read/write exchange between gdb and the stub.  */
7850
7851 static enum target_xfer_status
7852 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7853                      int unit_size, ULONGEST *xfered_len_units)
7854 {
7855   struct remote_state *rs = get_remote_state ();
7856   int buf_size_bytes;           /* Max size of packet output buffer.  */
7857   char *p;
7858   int todo_units;
7859   int decoded_bytes;
7860
7861   buf_size_bytes = get_memory_read_packet_size ();
7862   /* The packet buffer will be large enough for the payload;
7863      get_memory_packet_size ensures this.  */
7864
7865   /* Number of units that will fit.  */
7866   todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7867
7868   /* Construct "m"<memaddr>","<len>".  */
7869   memaddr = remote_address_masked (memaddr);
7870   p = rs->buf;
7871   *p++ = 'm';
7872   p += hexnumstr (p, (ULONGEST) memaddr);
7873   *p++ = ',';
7874   p += hexnumstr (p, (ULONGEST) todo_units);
7875   *p = '\0';
7876   putpkt (rs->buf);
7877   getpkt (&rs->buf, &rs->buf_size, 0);
7878   if (rs->buf[0] == 'E'
7879       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7880       && rs->buf[3] == '\0')
7881     return TARGET_XFER_E_IO;
7882   /* Reply describes memory byte by byte, each byte encoded as two hex
7883      characters.  */
7884   p = rs->buf;
7885   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7886   /* Return what we have.  Let higher layers handle partial reads.  */
7887   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7888   return TARGET_XFER_OK;
7889 }
7890
7891 /* Using the set of read-only target sections of remote, read live
7892    read-only memory.
7893
7894    For interface/parameters/return description see target.h,
7895    to_xfer_partial.  */
7896
7897 static enum target_xfer_status
7898 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7899                                    ULONGEST memaddr, ULONGEST len,
7900                                    int unit_size, ULONGEST *xfered_len)
7901 {
7902   struct target_section *secp;
7903   struct target_section_table *table;
7904
7905   secp = target_section_by_addr (ops, memaddr);
7906   if (secp != NULL
7907       && (bfd_get_section_flags (secp->the_bfd_section->owner,
7908                                  secp->the_bfd_section)
7909           & SEC_READONLY))
7910     {
7911       struct target_section *p;
7912       ULONGEST memend = memaddr + len;
7913
7914       table = target_get_section_table (ops);
7915
7916       for (p = table->sections; p < table->sections_end; p++)
7917         {
7918           if (memaddr >= p->addr)
7919             {
7920               if (memend <= p->endaddr)
7921                 {
7922                   /* Entire transfer is within this section.  */
7923                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7924                                               xfered_len);
7925                 }
7926               else if (memaddr >= p->endaddr)
7927                 {
7928                   /* This section ends before the transfer starts.  */
7929                   continue;
7930                 }
7931               else
7932                 {
7933                   /* This section overlaps the transfer.  Just do half.  */
7934                   len = p->endaddr - memaddr;
7935                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7936                                               xfered_len);
7937                 }
7938             }
7939         }
7940     }
7941
7942   return TARGET_XFER_EOF;
7943 }
7944
7945 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7946    first if the requested memory is unavailable in traceframe.
7947    Otherwise, fall back to remote_read_bytes_1.  */
7948
7949 static enum target_xfer_status
7950 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7951                    gdb_byte *myaddr, ULONGEST len, int unit_size,
7952                    ULONGEST *xfered_len)
7953 {
7954   if (len == 0)
7955     return TARGET_XFER_EOF;
7956
7957   if (get_traceframe_number () != -1)
7958     {
7959       VEC(mem_range_s) *available;
7960
7961       /* If we fail to get the set of available memory, then the
7962          target does not support querying traceframe info, and so we
7963          attempt reading from the traceframe anyway (assuming the
7964          target implements the old QTro packet then).  */
7965       if (traceframe_available_memory (&available, memaddr, len))
7966         {
7967           struct cleanup *old_chain;
7968
7969           old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7970
7971           if (VEC_empty (mem_range_s, available)
7972               || VEC_index (mem_range_s, available, 0)->start != memaddr)
7973             {
7974               enum target_xfer_status res;
7975
7976               /* Don't read into the traceframe's available
7977                  memory.  */
7978               if (!VEC_empty (mem_range_s, available))
7979                 {
7980                   LONGEST oldlen = len;
7981
7982                   len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7983                   gdb_assert (len <= oldlen);
7984                 }
7985
7986               do_cleanups (old_chain);
7987
7988               /* This goes through the topmost target again.  */
7989               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7990                                                        len, unit_size, xfered_len);
7991               if (res == TARGET_XFER_OK)
7992                 return TARGET_XFER_OK;
7993               else
7994                 {
7995                   /* No use trying further, we know some memory starting
7996                      at MEMADDR isn't available.  */
7997                   *xfered_len = len;
7998                   return TARGET_XFER_UNAVAILABLE;
7999                 }
8000             }
8001
8002           /* Don't try to read more than how much is available, in
8003              case the target implements the deprecated QTro packet to
8004              cater for older GDBs (the target's knowledge of read-only
8005              sections may be outdated by now).  */
8006           len = VEC_index (mem_range_s, available, 0)->length;
8007
8008           do_cleanups (old_chain);
8009         }
8010     }
8011
8012   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8013 }
8014
8015 \f
8016
8017 /* Sends a packet with content determined by the printf format string
8018    FORMAT and the remaining arguments, then gets the reply.  Returns
8019    whether the packet was a success, a failure, or unknown.  */
8020
8021 static enum packet_result remote_send_printf (const char *format, ...)
8022   ATTRIBUTE_PRINTF (1, 2);
8023
8024 static enum packet_result
8025 remote_send_printf (const char *format, ...)
8026 {
8027   struct remote_state *rs = get_remote_state ();
8028   int max_size = get_remote_packet_size ();
8029   va_list ap;
8030
8031   va_start (ap, format);
8032
8033   rs->buf[0] = '\0';
8034   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8035     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8036
8037   if (putpkt (rs->buf) < 0)
8038     error (_("Communication problem with target."));
8039
8040   rs->buf[0] = '\0';
8041   getpkt (&rs->buf, &rs->buf_size, 0);
8042
8043   return packet_check_result (rs->buf);
8044 }
8045
8046 static void
8047 restore_remote_timeout (void *p)
8048 {
8049   int value = *(int *)p;
8050
8051   remote_timeout = value;
8052 }
8053
8054 /* Flash writing can take quite some time.  We'll set
8055    effectively infinite timeout for flash operations.
8056    In future, we'll need to decide on a better approach.  */
8057 static const int remote_flash_timeout = 1000;
8058
8059 static void
8060 remote_flash_erase (struct target_ops *ops,
8061                     ULONGEST address, LONGEST length)
8062 {
8063   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8064   int saved_remote_timeout = remote_timeout;
8065   enum packet_result ret;
8066   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8067                                           &saved_remote_timeout);
8068
8069   remote_timeout = remote_flash_timeout;
8070
8071   ret = remote_send_printf ("vFlashErase:%s,%s",
8072                             phex (address, addr_size),
8073                             phex (length, 4));
8074   switch (ret)
8075     {
8076     case PACKET_UNKNOWN:
8077       error (_("Remote target does not support flash erase"));
8078     case PACKET_ERROR:
8079       error (_("Error erasing flash with vFlashErase packet"));
8080     default:
8081       break;
8082     }
8083
8084   do_cleanups (back_to);
8085 }
8086
8087 static enum target_xfer_status
8088 remote_flash_write (struct target_ops *ops, ULONGEST address,
8089                     ULONGEST length, ULONGEST *xfered_len,
8090                     const gdb_byte *data)
8091 {
8092   int saved_remote_timeout = remote_timeout;
8093   enum target_xfer_status ret;
8094   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8095                                           &saved_remote_timeout);
8096
8097   remote_timeout = remote_flash_timeout;
8098   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8099                                 xfered_len,'X', 0);
8100   do_cleanups (back_to);
8101
8102   return ret;
8103 }
8104
8105 static void
8106 remote_flash_done (struct target_ops *ops)
8107 {
8108   int saved_remote_timeout = remote_timeout;
8109   int ret;
8110   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8111                                           &saved_remote_timeout);
8112
8113   remote_timeout = remote_flash_timeout;
8114   ret = remote_send_printf ("vFlashDone");
8115   do_cleanups (back_to);
8116
8117   switch (ret)
8118     {
8119     case PACKET_UNKNOWN:
8120       error (_("Remote target does not support vFlashDone"));
8121     case PACKET_ERROR:
8122       error (_("Error finishing flash operation"));
8123     default:
8124       break;
8125     }
8126 }
8127
8128 static void
8129 remote_files_info (struct target_ops *ignore)
8130 {
8131   puts_filtered ("Debugging a target over a serial line.\n");
8132 }
8133 \f
8134 /* Stuff for dealing with the packets which are part of this protocol.
8135    See comment at top of file for details.  */
8136
8137 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8138    error to higher layers.  Called when a serial error is detected.
8139    The exception message is STRING, followed by a colon and a blank,
8140    the system error message for errno at function entry and final dot
8141    for output compatibility with throw_perror_with_name.  */
8142
8143 static void
8144 unpush_and_perror (const char *string)
8145 {
8146   int saved_errno = errno;
8147
8148   remote_unpush_target ();
8149   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8150                safe_strerror (saved_errno));
8151 }
8152
8153 /* Read a single character from the remote end.  */
8154
8155 static int
8156 readchar (int timeout)
8157 {
8158   int ch;
8159   struct remote_state *rs = get_remote_state ();
8160
8161   ch = serial_readchar (rs->remote_desc, timeout);
8162
8163   if (ch >= 0)
8164     return ch;
8165
8166   switch ((enum serial_rc) ch)
8167     {
8168     case SERIAL_EOF:
8169       remote_unpush_target ();
8170       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8171       /* no return */
8172     case SERIAL_ERROR:
8173       unpush_and_perror (_("Remote communication error.  "
8174                            "Target disconnected."));
8175       /* no return */
8176     case SERIAL_TIMEOUT:
8177       break;
8178     }
8179   return ch;
8180 }
8181
8182 /* Wrapper for serial_write that closes the target and throws if
8183    writing fails.  */
8184
8185 static void
8186 remote_serial_write (const char *str, int len)
8187 {
8188   struct remote_state *rs = get_remote_state ();
8189
8190   if (serial_write (rs->remote_desc, str, len))
8191     {
8192       unpush_and_perror (_("Remote communication error.  "
8193                            "Target disconnected."));
8194     }
8195 }
8196
8197 /* Send the command in *BUF to the remote machine, and read the reply
8198    into *BUF.  Report an error if we get an error reply.  Resize
8199    *BUF using xrealloc if necessary to hold the result, and update
8200    *SIZEOF_BUF.  */
8201
8202 static void
8203 remote_send (char **buf,
8204              long *sizeof_buf)
8205 {
8206   putpkt (*buf);
8207   getpkt (buf, sizeof_buf, 0);
8208
8209   if ((*buf)[0] == 'E')
8210     error (_("Remote failure reply: %s"), *buf);
8211 }
8212
8213 /* Return a pointer to an xmalloc'ed string representing an escaped
8214    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
8215    etc.  The caller is responsible for releasing the returned
8216    memory.  */
8217
8218 static char *
8219 escape_buffer (const char *buf, int n)
8220 {
8221   struct cleanup *old_chain;
8222   struct ui_file *stb;
8223   char *str;
8224
8225   stb = mem_fileopen ();
8226   old_chain = make_cleanup_ui_file_delete (stb);
8227
8228   fputstrn_unfiltered (buf, n, '\\', stb);
8229   str = ui_file_xstrdup (stb, NULL);
8230   do_cleanups (old_chain);
8231   return str;
8232 }
8233
8234 /* Display a null-terminated packet on stdout, for debugging, using C
8235    string notation.  */
8236
8237 static void
8238 print_packet (const char *buf)
8239 {
8240   puts_filtered ("\"");
8241   fputstr_filtered (buf, '"', gdb_stdout);
8242   puts_filtered ("\"");
8243 }
8244
8245 int
8246 putpkt (const char *buf)
8247 {
8248   return putpkt_binary (buf, strlen (buf));
8249 }
8250
8251 /* Send a packet to the remote machine, with error checking.  The data
8252    of the packet is in BUF.  The string in BUF can be at most
8253    get_remote_packet_size () - 5 to account for the $, # and checksum,
8254    and for a possible /0 if we are debugging (remote_debug) and want
8255    to print the sent packet as a string.  */
8256
8257 static int
8258 putpkt_binary (const char *buf, int cnt)
8259 {
8260   struct remote_state *rs = get_remote_state ();
8261   int i;
8262   unsigned char csum = 0;
8263   char *buf2 = (char *) xmalloc (cnt + 6);
8264   struct cleanup *old_chain = make_cleanup (xfree, buf2);
8265
8266   int ch;
8267   int tcount = 0;
8268   char *p;
8269
8270   /* Catch cases like trying to read memory or listing threads while
8271      we're waiting for a stop reply.  The remote server wouldn't be
8272      ready to handle this request, so we'd hang and timeout.  We don't
8273      have to worry about this in synchronous mode, because in that
8274      case it's not possible to issue a command while the target is
8275      running.  This is not a problem in non-stop mode, because in that
8276      case, the stub is always ready to process serial input.  */
8277   if (!target_is_non_stop_p ()
8278       && target_is_async_p ()
8279       && rs->waiting_for_stop_reply)
8280     {
8281       error (_("Cannot execute this command while the target is running.\n"
8282                "Use the \"interrupt\" command to stop the target\n"
8283                "and then try again."));
8284     }
8285
8286   /* We're sending out a new packet.  Make sure we don't look at a
8287      stale cached response.  */
8288   rs->cached_wait_status = 0;
8289
8290   /* Copy the packet into buffer BUF2, encapsulating it
8291      and giving it a checksum.  */
8292
8293   p = buf2;
8294   *p++ = '$';
8295
8296   for (i = 0; i < cnt; i++)
8297     {
8298       csum += buf[i];
8299       *p++ = buf[i];
8300     }
8301   *p++ = '#';
8302   *p++ = tohex ((csum >> 4) & 0xf);
8303   *p++ = tohex (csum & 0xf);
8304
8305   /* Send it over and over until we get a positive ack.  */
8306
8307   while (1)
8308     {
8309       int started_error_output = 0;
8310
8311       if (remote_debug)
8312         {
8313           struct cleanup *old_chain;
8314           char *str;
8315
8316           *p = '\0';
8317           str = escape_buffer (buf2, p - buf2);
8318           old_chain = make_cleanup (xfree, str);
8319           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8320           gdb_flush (gdb_stdlog);
8321           do_cleanups (old_chain);
8322         }
8323       remote_serial_write (buf2, p - buf2);
8324
8325       /* If this is a no acks version of the remote protocol, send the
8326          packet and move on.  */
8327       if (rs->noack_mode)
8328         break;
8329
8330       /* Read until either a timeout occurs (-2) or '+' is read.
8331          Handle any notification that arrives in the mean time.  */
8332       while (1)
8333         {
8334           ch = readchar (remote_timeout);
8335
8336           if (remote_debug)
8337             {
8338               switch (ch)
8339                 {
8340                 case '+':
8341                 case '-':
8342                 case SERIAL_TIMEOUT:
8343                 case '$':
8344                 case '%':
8345                   if (started_error_output)
8346                     {
8347                       putchar_unfiltered ('\n');
8348                       started_error_output = 0;
8349                     }
8350                 }
8351             }
8352
8353           switch (ch)
8354             {
8355             case '+':
8356               if (remote_debug)
8357                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8358               do_cleanups (old_chain);
8359               return 1;
8360             case '-':
8361               if (remote_debug)
8362                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8363               /* FALLTHROUGH */
8364             case SERIAL_TIMEOUT:
8365               tcount++;
8366               if (tcount > 3)
8367                 {
8368                   do_cleanups (old_chain);
8369                   return 0;
8370                 }
8371               break;            /* Retransmit buffer.  */
8372             case '$':
8373               {
8374                 if (remote_debug)
8375                   fprintf_unfiltered (gdb_stdlog,
8376                                       "Packet instead of Ack, ignoring it\n");
8377                 /* It's probably an old response sent because an ACK
8378                    was lost.  Gobble up the packet and ack it so it
8379                    doesn't get retransmitted when we resend this
8380                    packet.  */
8381                 skip_frame ();
8382                 remote_serial_write ("+", 1);
8383                 continue;       /* Now, go look for +.  */
8384               }
8385
8386             case '%':
8387               {
8388                 int val;
8389
8390                 /* If we got a notification, handle it, and go back to looking
8391                    for an ack.  */
8392                 /* We've found the start of a notification.  Now
8393                    collect the data.  */
8394                 val = read_frame (&rs->buf, &rs->buf_size);
8395                 if (val >= 0)
8396                   {
8397                     if (remote_debug)
8398                       {
8399                         struct cleanup *old_chain;
8400                         char *str;
8401
8402                         str = escape_buffer (rs->buf, val);
8403                         old_chain = make_cleanup (xfree, str);
8404                         fprintf_unfiltered (gdb_stdlog,
8405                                             "  Notification received: %s\n",
8406                                             str);
8407                         do_cleanups (old_chain);
8408                       }
8409                     handle_notification (rs->notif_state, rs->buf);
8410                     /* We're in sync now, rewait for the ack.  */
8411                     tcount = 0;
8412                   }
8413                 else
8414                   {
8415                     if (remote_debug)
8416                       {
8417                         if (!started_error_output)
8418                           {
8419                             started_error_output = 1;
8420                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8421                           }
8422                         fputc_unfiltered (ch & 0177, gdb_stdlog);
8423                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8424                       }
8425                   }
8426                 continue;
8427               }
8428               /* fall-through */
8429             default:
8430               if (remote_debug)
8431                 {
8432                   if (!started_error_output)
8433                     {
8434                       started_error_output = 1;
8435                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8436                     }
8437                   fputc_unfiltered (ch & 0177, gdb_stdlog);
8438                 }
8439               continue;
8440             }
8441           break;                /* Here to retransmit.  */
8442         }
8443
8444 #if 0
8445       /* This is wrong.  If doing a long backtrace, the user should be
8446          able to get out next time we call QUIT, without anything as
8447          violent as interrupt_query.  If we want to provide a way out of
8448          here without getting to the next QUIT, it should be based on
8449          hitting ^C twice as in remote_wait.  */
8450       if (quit_flag)
8451         {
8452           quit_flag = 0;
8453           interrupt_query ();
8454         }
8455 #endif
8456     }
8457
8458   do_cleanups (old_chain);
8459   return 0;
8460 }
8461
8462 /* Come here after finding the start of a frame when we expected an
8463    ack.  Do our best to discard the rest of this packet.  */
8464
8465 static void
8466 skip_frame (void)
8467 {
8468   int c;
8469
8470   while (1)
8471     {
8472       c = readchar (remote_timeout);
8473       switch (c)
8474         {
8475         case SERIAL_TIMEOUT:
8476           /* Nothing we can do.  */
8477           return;
8478         case '#':
8479           /* Discard the two bytes of checksum and stop.  */
8480           c = readchar (remote_timeout);
8481           if (c >= 0)
8482             c = readchar (remote_timeout);
8483
8484           return;
8485         case '*':               /* Run length encoding.  */
8486           /* Discard the repeat count.  */
8487           c = readchar (remote_timeout);
8488           if (c < 0)
8489             return;
8490           break;
8491         default:
8492           /* A regular character.  */
8493           break;
8494         }
8495     }
8496 }
8497
8498 /* Come here after finding the start of the frame.  Collect the rest
8499    into *BUF, verifying the checksum, length, and handling run-length
8500    compression.  NUL terminate the buffer.  If there is not enough room,
8501    expand *BUF using xrealloc.
8502
8503    Returns -1 on error, number of characters in buffer (ignoring the
8504    trailing NULL) on success. (could be extended to return one of the
8505    SERIAL status indications).  */
8506
8507 static long
8508 read_frame (char **buf_p,
8509             long *sizeof_buf)
8510 {
8511   unsigned char csum;
8512   long bc;
8513   int c;
8514   char *buf = *buf_p;
8515   struct remote_state *rs = get_remote_state ();
8516
8517   csum = 0;
8518   bc = 0;
8519
8520   while (1)
8521     {
8522       c = readchar (remote_timeout);
8523       switch (c)
8524         {
8525         case SERIAL_TIMEOUT:
8526           if (remote_debug)
8527             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8528           return -1;
8529         case '$':
8530           if (remote_debug)
8531             fputs_filtered ("Saw new packet start in middle of old one\n",
8532                             gdb_stdlog);
8533           return -1;            /* Start a new packet, count retries.  */
8534         case '#':
8535           {
8536             unsigned char pktcsum;
8537             int check_0 = 0;
8538             int check_1 = 0;
8539
8540             buf[bc] = '\0';
8541
8542             check_0 = readchar (remote_timeout);
8543             if (check_0 >= 0)
8544               check_1 = readchar (remote_timeout);
8545
8546             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8547               {
8548                 if (remote_debug)
8549                   fputs_filtered ("Timeout in checksum, retrying\n",
8550                                   gdb_stdlog);
8551                 return -1;
8552               }
8553             else if (check_0 < 0 || check_1 < 0)
8554               {
8555                 if (remote_debug)
8556                   fputs_filtered ("Communication error in checksum\n",
8557                                   gdb_stdlog);
8558                 return -1;
8559               }
8560
8561             /* Don't recompute the checksum; with no ack packets we
8562                don't have any way to indicate a packet retransmission
8563                is necessary.  */
8564             if (rs->noack_mode)
8565               return bc;
8566
8567             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8568             if (csum == pktcsum)
8569               return bc;
8570
8571             if (remote_debug)
8572               {
8573                 struct cleanup *old_chain;
8574                 char *str;
8575
8576                 str = escape_buffer (buf, bc);
8577                 old_chain = make_cleanup (xfree, str);
8578                 fprintf_unfiltered (gdb_stdlog,
8579                                     "Bad checksum, sentsum=0x%x, "
8580                                     "csum=0x%x, buf=%s\n",
8581                                     pktcsum, csum, str);
8582                 do_cleanups (old_chain);
8583               }
8584             /* Number of characters in buffer ignoring trailing
8585                NULL.  */
8586             return -1;
8587           }
8588         case '*':               /* Run length encoding.  */
8589           {
8590             int repeat;
8591
8592             csum += c;
8593             c = readchar (remote_timeout);
8594             csum += c;
8595             repeat = c - ' ' + 3;       /* Compute repeat count.  */
8596
8597             /* The character before ``*'' is repeated.  */
8598
8599             if (repeat > 0 && repeat <= 255 && bc > 0)
8600               {
8601                 if (bc + repeat - 1 >= *sizeof_buf - 1)
8602                   {
8603                     /* Make some more room in the buffer.  */
8604                     *sizeof_buf += repeat;
8605                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8606                     buf = *buf_p;
8607                   }
8608
8609                 memset (&buf[bc], buf[bc - 1], repeat);
8610                 bc += repeat;
8611                 continue;
8612               }
8613
8614             buf[bc] = '\0';
8615             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8616             return -1;
8617           }
8618         default:
8619           if (bc >= *sizeof_buf - 1)
8620             {
8621               /* Make some more room in the buffer.  */
8622               *sizeof_buf *= 2;
8623               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8624               buf = *buf_p;
8625             }
8626
8627           buf[bc++] = c;
8628           csum += c;
8629           continue;
8630         }
8631     }
8632 }
8633
8634 /* Read a packet from the remote machine, with error checking, and
8635    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8636    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8637    rather than timing out; this is used (in synchronous mode) to wait
8638    for a target that is is executing user code to stop.  */
8639 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8640    don't have to change all the calls to getpkt to deal with the
8641    return value, because at the moment I don't know what the right
8642    thing to do it for those.  */
8643 void
8644 getpkt (char **buf,
8645         long *sizeof_buf,
8646         int forever)
8647 {
8648   getpkt_sane (buf, sizeof_buf, forever);
8649 }
8650
8651
8652 /* Read a packet from the remote machine, with error checking, and
8653    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8654    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8655    rather than timing out; this is used (in synchronous mode) to wait
8656    for a target that is is executing user code to stop.  If FOREVER ==
8657    0, this function is allowed to time out gracefully and return an
8658    indication of this to the caller.  Otherwise return the number of
8659    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
8660    enough reason to return to the caller.  *IS_NOTIF is an output
8661    boolean that indicates whether *BUF holds a notification or not
8662    (a regular packet).  */
8663
8664 static int
8665 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8666                         int expecting_notif, int *is_notif)
8667 {
8668   struct remote_state *rs = get_remote_state ();
8669   int c;
8670   int tries;
8671   int timeout;
8672   int val = -1;
8673
8674   /* We're reading a new response.  Make sure we don't look at a
8675      previously cached response.  */
8676   rs->cached_wait_status = 0;
8677
8678   strcpy (*buf, "timeout");
8679
8680   if (forever)
8681     timeout = watchdog > 0 ? watchdog : -1;
8682   else if (expecting_notif)
8683     timeout = 0; /* There should already be a char in the buffer.  If
8684                     not, bail out.  */
8685   else
8686     timeout = remote_timeout;
8687
8688 #define MAX_TRIES 3
8689
8690   /* Process any number of notifications, and then return when
8691      we get a packet.  */
8692   for (;;)
8693     {
8694       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8695          times.  */
8696       for (tries = 1; tries <= MAX_TRIES; tries++)
8697         {
8698           /* This can loop forever if the remote side sends us
8699              characters continuously, but if it pauses, we'll get
8700              SERIAL_TIMEOUT from readchar because of timeout.  Then
8701              we'll count that as a retry.
8702
8703              Note that even when forever is set, we will only wait
8704              forever prior to the start of a packet.  After that, we
8705              expect characters to arrive at a brisk pace.  They should
8706              show up within remote_timeout intervals.  */
8707           do
8708             c = readchar (timeout);
8709           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8710
8711           if (c == SERIAL_TIMEOUT)
8712             {
8713               if (expecting_notif)
8714                 return -1; /* Don't complain, it's normal to not get
8715                               anything in this case.  */
8716
8717               if (forever)      /* Watchdog went off?  Kill the target.  */
8718                 {
8719                   QUIT;
8720                   remote_unpush_target ();
8721                   throw_error (TARGET_CLOSE_ERROR,
8722                                _("Watchdog timeout has expired.  "
8723                                  "Target detached."));
8724                 }
8725               if (remote_debug)
8726                 fputs_filtered ("Timed out.\n", gdb_stdlog);
8727             }
8728           else
8729             {
8730               /* We've found the start of a packet or notification.
8731                  Now collect the data.  */
8732               val = read_frame (buf, sizeof_buf);
8733               if (val >= 0)
8734                 break;
8735             }
8736
8737           remote_serial_write ("-", 1);
8738         }
8739
8740       if (tries > MAX_TRIES)
8741         {
8742           /* We have tried hard enough, and just can't receive the
8743              packet/notification.  Give up.  */
8744           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8745
8746           /* Skip the ack char if we're in no-ack mode.  */
8747           if (!rs->noack_mode)
8748             remote_serial_write ("+", 1);
8749           return -1;
8750         }
8751
8752       /* If we got an ordinary packet, return that to our caller.  */
8753       if (c == '$')
8754         {
8755           if (remote_debug)
8756             {
8757              struct cleanup *old_chain;
8758              char *str;
8759
8760              str = escape_buffer (*buf, val);
8761              old_chain = make_cleanup (xfree, str);
8762              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8763              do_cleanups (old_chain);
8764             }
8765
8766           /* Skip the ack char if we're in no-ack mode.  */
8767           if (!rs->noack_mode)
8768             remote_serial_write ("+", 1);
8769           if (is_notif != NULL)
8770             *is_notif = 0;
8771           return val;
8772         }
8773
8774        /* If we got a notification, handle it, and go back to looking
8775          for a packet.  */
8776       else
8777         {
8778           gdb_assert (c == '%');
8779
8780           if (remote_debug)
8781             {
8782               struct cleanup *old_chain;
8783               char *str;
8784
8785               str = escape_buffer (*buf, val);
8786               old_chain = make_cleanup (xfree, str);
8787               fprintf_unfiltered (gdb_stdlog,
8788                                   "  Notification received: %s\n",
8789                                   str);
8790               do_cleanups (old_chain);
8791             }
8792           if (is_notif != NULL)
8793             *is_notif = 1;
8794
8795           handle_notification (rs->notif_state, *buf);
8796
8797           /* Notifications require no acknowledgement.  */
8798
8799           if (expecting_notif)
8800             return val;
8801         }
8802     }
8803 }
8804
8805 static int
8806 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8807 {
8808   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8809 }
8810
8811 static int
8812 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8813                       int *is_notif)
8814 {
8815   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8816                                  is_notif);
8817 }
8818
8819 /* Check whether EVENT is a fork event for the process specified
8820    by the pid passed in DATA, and if it is, kill the fork child.  */
8821
8822 static int
8823 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8824                             QUEUE_ITER (stop_reply_p) *iter,
8825                             stop_reply_p event,
8826                             void *data)
8827 {
8828   struct queue_iter_param *param = (struct queue_iter_param *) data;
8829   int parent_pid = *(int *) param->input;
8830
8831   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8832     {
8833       struct remote_state *rs = get_remote_state ();
8834       int child_pid = ptid_get_pid (event->ws.value.related_pid);
8835       int res;
8836
8837       res = remote_vkill (child_pid, rs);
8838       if (res != 0)
8839         error (_("Can't kill fork child process %d"), child_pid);
8840     }
8841
8842   return 1;
8843 }
8844
8845 /* Kill any new fork children of process PID that haven't been
8846    processed by follow_fork.  */
8847
8848 static void
8849 kill_new_fork_children (int pid, struct remote_state *rs)
8850 {
8851   struct thread_info *thread;
8852   struct notif_client *notif = &notif_client_stop;
8853   struct queue_iter_param param;
8854
8855   /* Kill the fork child threads of any threads in process PID
8856      that are stopped at a fork event.  */
8857   ALL_NON_EXITED_THREADS (thread)
8858     {
8859       struct target_waitstatus *ws = &thread->pending_follow;
8860
8861       if (is_pending_fork_parent (ws, pid, thread->ptid))
8862         {
8863           struct remote_state *rs = get_remote_state ();
8864           int child_pid = ptid_get_pid (ws->value.related_pid);
8865           int res;
8866
8867           res = remote_vkill (child_pid, rs);
8868           if (res != 0)
8869             error (_("Can't kill fork child process %d"), child_pid);
8870         }
8871     }
8872
8873   /* Check for any pending fork events (not reported or processed yet)
8874      in process PID and kill those fork child threads as well.  */
8875   remote_notif_get_pending_events (notif);
8876   param.input = &pid;
8877   param.output = NULL;
8878   QUEUE_iterate (stop_reply_p, stop_reply_queue,
8879                  kill_child_of_pending_fork, &param);
8880 }
8881
8882 \f
8883 /* Target hook to kill the current inferior.  */
8884
8885 static void
8886 remote_kill (struct target_ops *ops)
8887 {
8888   int res = -1;
8889   int pid = ptid_get_pid (inferior_ptid);
8890   struct remote_state *rs = get_remote_state ();
8891
8892   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
8893     {
8894       /* If we're stopped while forking and we haven't followed yet,
8895          kill the child task.  We need to do this before killing the
8896          parent task because if this is a vfork then the parent will
8897          be sleeping.  */
8898       kill_new_fork_children (pid, rs);
8899
8900       res = remote_vkill (pid, rs);
8901       if (res == 0)
8902         {
8903           target_mourn_inferior ();
8904           return;
8905         }
8906     }
8907
8908   /* If we are in 'target remote' mode and we are killing the only
8909      inferior, then we will tell gdbserver to exit and unpush the
8910      target.  */
8911   if (res == -1 && !remote_multi_process_p (rs)
8912       && number_of_live_inferiors () == 1)
8913     {
8914       remote_kill_k ();
8915
8916       /* We've killed the remote end, we get to mourn it.  If we are
8917          not in extended mode, mourning the inferior also unpushes
8918          remote_ops from the target stack, which closes the remote
8919          connection.  */
8920       target_mourn_inferior ();
8921
8922       return;
8923     }
8924
8925   error (_("Can't kill process"));
8926 }
8927
8928 /* Send a kill request to the target using the 'vKill' packet.  */
8929
8930 static int
8931 remote_vkill (int pid, struct remote_state *rs)
8932 {
8933   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8934     return -1;
8935
8936   /* Tell the remote target to detach.  */
8937   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8938   putpkt (rs->buf);
8939   getpkt (&rs->buf, &rs->buf_size, 0);
8940
8941   switch (packet_ok (rs->buf,
8942                      &remote_protocol_packets[PACKET_vKill]))
8943     {
8944     case PACKET_OK:
8945       return 0;
8946     case PACKET_ERROR:
8947       return 1;
8948     case PACKET_UNKNOWN:
8949       return -1;
8950     default:
8951       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8952     }
8953 }
8954
8955 /* Send a kill request to the target using the 'k' packet.  */
8956
8957 static void
8958 remote_kill_k (void)
8959 {
8960   /* Catch errors so the user can quit from gdb even when we
8961      aren't on speaking terms with the remote system.  */
8962   TRY
8963     {
8964       putpkt ("k");
8965     }
8966   CATCH (ex, RETURN_MASK_ERROR)
8967     {
8968       if (ex.error == TARGET_CLOSE_ERROR)
8969         {
8970           /* If we got an (EOF) error that caused the target
8971              to go away, then we're done, that's what we wanted.
8972              "k" is susceptible to cause a premature EOF, given
8973              that the remote server isn't actually required to
8974              reply to "k", and it can happen that it doesn't
8975              even get to reply ACK to the "k".  */
8976           return;
8977         }
8978
8979       /* Otherwise, something went wrong.  We didn't actually kill
8980          the target.  Just propagate the exception, and let the
8981          user or higher layers decide what to do.  */
8982       throw_exception (ex);
8983     }
8984   END_CATCH
8985 }
8986
8987 static void
8988 remote_mourn (struct target_ops *target)
8989 {
8990   struct remote_state *rs = get_remote_state ();
8991
8992   /* In 'target remote' mode with one inferior, we close the connection.  */
8993   if (!rs->extended && number_of_live_inferiors () <= 1)
8994     {
8995       unpush_target (target);
8996
8997       /* remote_close takes care of doing most of the clean up.  */
8998       generic_mourn_inferior ();
8999       return;
9000     }
9001
9002   /* In case we got here due to an error, but we're going to stay
9003      connected.  */
9004   rs->waiting_for_stop_reply = 0;
9005
9006   /* If the current general thread belonged to the process we just
9007      detached from or has exited, the remote side current general
9008      thread becomes undefined.  Considering a case like this:
9009
9010      - We just got here due to a detach.
9011      - The process that we're detaching from happens to immediately
9012        report a global breakpoint being hit in non-stop mode, in the
9013        same thread we had selected before.
9014      - GDB attaches to this process again.
9015      - This event happens to be the next event we handle.
9016
9017      GDB would consider that the current general thread didn't need to
9018      be set on the stub side (with Hg), since for all it knew,
9019      GENERAL_THREAD hadn't changed.
9020
9021      Notice that although in all-stop mode, the remote server always
9022      sets the current thread to the thread reporting the stop event,
9023      that doesn't happen in non-stop mode; in non-stop, the stub *must
9024      not* change the current thread when reporting a breakpoint hit,
9025      due to the decoupling of event reporting and event handling.
9026
9027      To keep things simple, we always invalidate our notion of the
9028      current thread.  */
9029   record_currthread (rs, minus_one_ptid);
9030
9031   /* Call common code to mark the inferior as not running.  */
9032   generic_mourn_inferior ();
9033
9034   if (!have_inferiors ())
9035     {
9036       if (!remote_multi_process_p (rs))
9037         {
9038           /* Check whether the target is running now - some remote stubs
9039              automatically restart after kill.  */
9040           putpkt ("?");
9041           getpkt (&rs->buf, &rs->buf_size, 0);
9042
9043           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9044             {
9045               /* Assume that the target has been restarted.  Set
9046                  inferior_ptid so that bits of core GDB realizes
9047                  there's something here, e.g., so that the user can
9048                  say "kill" again.  */
9049               inferior_ptid = magic_null_ptid;
9050             }
9051         }
9052     }
9053 }
9054
9055 static int
9056 extended_remote_supports_disable_randomization (struct target_ops *self)
9057 {
9058   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9059 }
9060
9061 static void
9062 extended_remote_disable_randomization (int val)
9063 {
9064   struct remote_state *rs = get_remote_state ();
9065   char *reply;
9066
9067   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9068              val);
9069   putpkt (rs->buf);
9070   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9071   if (*reply == '\0')
9072     error (_("Target does not support QDisableRandomization."));
9073   if (strcmp (reply, "OK") != 0)
9074     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9075 }
9076
9077 static int
9078 extended_remote_run (char *args)
9079 {
9080   struct remote_state *rs = get_remote_state ();
9081   int len;
9082   const char *remote_exec_file = get_remote_exec_file ();
9083
9084   /* If the user has disabled vRun support, or we have detected that
9085      support is not available, do not try it.  */
9086   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9087     return -1;
9088
9089   strcpy (rs->buf, "vRun;");
9090   len = strlen (rs->buf);
9091
9092   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9093     error (_("Remote file name too long for run packet"));
9094   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9095                       strlen (remote_exec_file));
9096
9097   gdb_assert (args != NULL);
9098   if (*args)
9099     {
9100       struct cleanup *back_to;
9101       int i;
9102       char **argv;
9103
9104       argv = gdb_buildargv (args);
9105       back_to = make_cleanup_freeargv (argv);
9106       for (i = 0; argv[i] != NULL; i++)
9107         {
9108           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9109             error (_("Argument list too long for run packet"));
9110           rs->buf[len++] = ';';
9111           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9112                               strlen (argv[i]));
9113         }
9114       do_cleanups (back_to);
9115     }
9116
9117   rs->buf[len++] = '\0';
9118
9119   putpkt (rs->buf);
9120   getpkt (&rs->buf, &rs->buf_size, 0);
9121
9122   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9123     {
9124     case PACKET_OK:
9125       /* We have a wait response.  All is well.  */
9126       return 0;
9127     case PACKET_UNKNOWN:
9128       return -1;
9129     case PACKET_ERROR:
9130       if (remote_exec_file[0] == '\0')
9131         error (_("Running the default executable on the remote target failed; "
9132                  "try \"set remote exec-file\"?"));
9133       else
9134         error (_("Running \"%s\" on the remote target failed"),
9135                remote_exec_file);
9136     default:
9137       gdb_assert_not_reached (_("bad switch"));
9138     }
9139 }
9140
9141 /* In the extended protocol we want to be able to do things like
9142    "run" and have them basically work as expected.  So we need
9143    a special create_inferior function.  We support changing the
9144    executable file and the command line arguments, but not the
9145    environment.  */
9146
9147 static void
9148 extended_remote_create_inferior (struct target_ops *ops,
9149                                  char *exec_file, char *args,
9150                                  char **env, int from_tty)
9151 {
9152   int run_worked;
9153   char *stop_reply;
9154   struct remote_state *rs = get_remote_state ();
9155   const char *remote_exec_file = get_remote_exec_file ();
9156
9157   /* If running asynchronously, register the target file descriptor
9158      with the event loop.  */
9159   if (target_can_async_p ())
9160     target_async (1);
9161
9162   /* Disable address space randomization if requested (and supported).  */
9163   if (extended_remote_supports_disable_randomization (ops))
9164     extended_remote_disable_randomization (disable_randomization);
9165
9166   /* Now restart the remote server.  */
9167   run_worked = extended_remote_run (args) != -1;
9168   if (!run_worked)
9169     {
9170       /* vRun was not supported.  Fail if we need it to do what the
9171          user requested.  */
9172       if (remote_exec_file[0])
9173         error (_("Remote target does not support \"set remote exec-file\""));
9174       if (args[0])
9175         error (_("Remote target does not support \"set args\" or run <ARGS>"));
9176
9177       /* Fall back to "R".  */
9178       extended_remote_restart ();
9179     }
9180
9181   if (!have_inferiors ())
9182     {
9183       /* Clean up from the last time we ran, before we mark the target
9184          running again.  This will mark breakpoints uninserted, and
9185          get_offsets may insert breakpoints.  */
9186       init_thread_list ();
9187       init_wait_for_inferior ();
9188     }
9189
9190   /* vRun's success return is a stop reply.  */
9191   stop_reply = run_worked ? rs->buf : NULL;
9192   add_current_inferior_and_thread (stop_reply);
9193
9194   /* Get updated offsets, if the stub uses qOffsets.  */
9195   get_offsets ();
9196 }
9197 \f
9198
9199 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
9200    the list of conditions (in agent expression bytecode format), if any, the
9201    target needs to evaluate.  The output is placed into the packet buffer
9202    started from BUF and ended at BUF_END.  */
9203
9204 static int
9205 remote_add_target_side_condition (struct gdbarch *gdbarch,
9206                                   struct bp_target_info *bp_tgt, char *buf,
9207                                   char *buf_end)
9208 {
9209   struct agent_expr *aexpr = NULL;
9210   int i, ix;
9211
9212   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9213     return 0;
9214
9215   buf += strlen (buf);
9216   xsnprintf (buf, buf_end - buf, "%s", ";");
9217   buf++;
9218
9219   /* Send conditions to the target and free the vector.  */
9220   for (ix = 0;
9221        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9222        ix++)
9223     {
9224       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9225       buf += strlen (buf);
9226       for (i = 0; i < aexpr->len; ++i)
9227         buf = pack_hex_byte (buf, aexpr->buf[i]);
9228       *buf = '\0';
9229     }
9230   return 0;
9231 }
9232
9233 static void
9234 remote_add_target_side_commands (struct gdbarch *gdbarch,
9235                                  struct bp_target_info *bp_tgt, char *buf)
9236 {
9237   struct agent_expr *aexpr = NULL;
9238   int i, ix;
9239
9240   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9241     return;
9242
9243   buf += strlen (buf);
9244
9245   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9246   buf += strlen (buf);
9247
9248   /* Concatenate all the agent expressions that are commands into the
9249      cmds parameter.  */
9250   for (ix = 0;
9251        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9252        ix++)
9253     {
9254       sprintf (buf, "X%x,", aexpr->len);
9255       buf += strlen (buf);
9256       for (i = 0; i < aexpr->len; ++i)
9257         buf = pack_hex_byte (buf, aexpr->buf[i]);
9258       *buf = '\0';
9259     }
9260 }
9261
9262 /* Insert a breakpoint.  On targets that have software breakpoint
9263    support, we ask the remote target to do the work; on targets
9264    which don't, we insert a traditional memory breakpoint.  */
9265
9266 static int
9267 remote_insert_breakpoint (struct target_ops *ops,
9268                           struct gdbarch *gdbarch,
9269                           struct bp_target_info *bp_tgt)
9270 {
9271   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9272      If it succeeds, then set the support to PACKET_ENABLE.  If it
9273      fails, and the user has explicitly requested the Z support then
9274      report an error, otherwise, mark it disabled and go on.  */
9275
9276   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9277     {
9278       CORE_ADDR addr = bp_tgt->reqstd_address;
9279       struct remote_state *rs;
9280       char *p, *endbuf;
9281       int bpsize;
9282
9283       /* Make sure the remote is pointing at the right process, if
9284          necessary.  */
9285       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9286         set_general_process ();
9287
9288       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9289
9290       rs = get_remote_state ();
9291       p = rs->buf;
9292       endbuf = rs->buf + get_remote_packet_size ();
9293
9294       *(p++) = 'Z';
9295       *(p++) = '0';
9296       *(p++) = ',';
9297       addr = (ULONGEST) remote_address_masked (addr);
9298       p += hexnumstr (p, addr);
9299       xsnprintf (p, endbuf - p, ",%d", bpsize);
9300
9301       if (remote_supports_cond_breakpoints (ops))
9302         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9303
9304       if (remote_can_run_breakpoint_commands (ops))
9305         remote_add_target_side_commands (gdbarch, bp_tgt, p);
9306
9307       putpkt (rs->buf);
9308       getpkt (&rs->buf, &rs->buf_size, 0);
9309
9310       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9311         {
9312         case PACKET_ERROR:
9313           return -1;
9314         case PACKET_OK:
9315           bp_tgt->placed_address = addr;
9316           bp_tgt->placed_size = bpsize;
9317           return 0;
9318         case PACKET_UNKNOWN:
9319           break;
9320         }
9321     }
9322
9323   /* If this breakpoint has target-side commands but this stub doesn't
9324      support Z0 packets, throw error.  */
9325   if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9326     throw_error (NOT_SUPPORTED_ERROR, _("\
9327 Target doesn't support breakpoints that have target side commands."));
9328
9329   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9330 }
9331
9332 static int
9333 remote_remove_breakpoint (struct target_ops *ops,
9334                           struct gdbarch *gdbarch,
9335                           struct bp_target_info *bp_tgt)
9336 {
9337   CORE_ADDR addr = bp_tgt->placed_address;
9338   struct remote_state *rs = get_remote_state ();
9339
9340   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9341     {
9342       char *p = rs->buf;
9343       char *endbuf = rs->buf + get_remote_packet_size ();
9344
9345       /* Make sure the remote is pointing at the right process, if
9346          necessary.  */
9347       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9348         set_general_process ();
9349
9350       *(p++) = 'z';
9351       *(p++) = '0';
9352       *(p++) = ',';
9353
9354       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9355       p += hexnumstr (p, addr);
9356       xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9357
9358       putpkt (rs->buf);
9359       getpkt (&rs->buf, &rs->buf_size, 0);
9360
9361       return (rs->buf[0] == 'E');
9362     }
9363
9364   return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9365 }
9366
9367 static enum Z_packet_type
9368 watchpoint_to_Z_packet (int type)
9369 {
9370   switch (type)
9371     {
9372     case hw_write:
9373       return Z_PACKET_WRITE_WP;
9374       break;
9375     case hw_read:
9376       return Z_PACKET_READ_WP;
9377       break;
9378     case hw_access:
9379       return Z_PACKET_ACCESS_WP;
9380       break;
9381     default:
9382       internal_error (__FILE__, __LINE__,
9383                       _("hw_bp_to_z: bad watchpoint type %d"), type);
9384     }
9385 }
9386
9387 static int
9388 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9389                           enum target_hw_bp_type type, struct expression *cond)
9390 {
9391   struct remote_state *rs = get_remote_state ();
9392   char *endbuf = rs->buf + get_remote_packet_size ();
9393   char *p;
9394   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9395
9396   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9397     return 1;
9398
9399   /* Make sure the remote is pointing at the right process, if
9400      necessary.  */
9401   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9402     set_general_process ();
9403
9404   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9405   p = strchr (rs->buf, '\0');
9406   addr = remote_address_masked (addr);
9407   p += hexnumstr (p, (ULONGEST) addr);
9408   xsnprintf (p, endbuf - p, ",%x", len);
9409
9410   putpkt (rs->buf);
9411   getpkt (&rs->buf, &rs->buf_size, 0);
9412
9413   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9414     {
9415     case PACKET_ERROR:
9416       return -1;
9417     case PACKET_UNKNOWN:
9418       return 1;
9419     case PACKET_OK:
9420       return 0;
9421     }
9422   internal_error (__FILE__, __LINE__,
9423                   _("remote_insert_watchpoint: reached end of function"));
9424 }
9425
9426 static int
9427 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9428                                      CORE_ADDR start, int length)
9429 {
9430   CORE_ADDR diff = remote_address_masked (addr - start);
9431
9432   return diff < length;
9433 }
9434
9435
9436 static int
9437 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9438                           enum target_hw_bp_type type, struct expression *cond)
9439 {
9440   struct remote_state *rs = get_remote_state ();
9441   char *endbuf = rs->buf + get_remote_packet_size ();
9442   char *p;
9443   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9444
9445   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9446     return -1;
9447
9448   /* Make sure the remote is pointing at the right process, if
9449      necessary.  */
9450   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9451     set_general_process ();
9452
9453   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9454   p = strchr (rs->buf, '\0');
9455   addr = remote_address_masked (addr);
9456   p += hexnumstr (p, (ULONGEST) addr);
9457   xsnprintf (p, endbuf - p, ",%x", len);
9458   putpkt (rs->buf);
9459   getpkt (&rs->buf, &rs->buf_size, 0);
9460
9461   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9462     {
9463     case PACKET_ERROR:
9464     case PACKET_UNKNOWN:
9465       return -1;
9466     case PACKET_OK:
9467       return 0;
9468     }
9469   internal_error (__FILE__, __LINE__,
9470                   _("remote_remove_watchpoint: reached end of function"));
9471 }
9472
9473
9474 int remote_hw_watchpoint_limit = -1;
9475 int remote_hw_watchpoint_length_limit = -1;
9476 int remote_hw_breakpoint_limit = -1;
9477
9478 static int
9479 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9480                                     CORE_ADDR addr, int len)
9481 {
9482   if (remote_hw_watchpoint_length_limit == 0)
9483     return 0;
9484   else if (remote_hw_watchpoint_length_limit < 0)
9485     return 1;
9486   else if (len <= remote_hw_watchpoint_length_limit)
9487     return 1;
9488   else
9489     return 0;
9490 }
9491
9492 static int
9493 remote_check_watch_resources (struct target_ops *self,
9494                               enum bptype type, int cnt, int ot)
9495 {
9496   if (type == bp_hardware_breakpoint)
9497     {
9498       if (remote_hw_breakpoint_limit == 0)
9499         return 0;
9500       else if (remote_hw_breakpoint_limit < 0)
9501         return 1;
9502       else if (cnt <= remote_hw_breakpoint_limit)
9503         return 1;
9504     }
9505   else
9506     {
9507       if (remote_hw_watchpoint_limit == 0)
9508         return 0;
9509       else if (remote_hw_watchpoint_limit < 0)
9510         return 1;
9511       else if (ot)
9512         return -1;
9513       else if (cnt <= remote_hw_watchpoint_limit)
9514         return 1;
9515     }
9516   return -1;
9517 }
9518
9519 /* The to_stopped_by_sw_breakpoint method of target remote.  */
9520
9521 static int
9522 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9523 {
9524   struct thread_info *thread = inferior_thread ();
9525
9526   return (thread->priv != NULL
9527           && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9528 }
9529
9530 /* The to_supports_stopped_by_sw_breakpoint method of target
9531    remote.  */
9532
9533 static int
9534 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9535 {
9536   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9537 }
9538
9539 /* The to_stopped_by_hw_breakpoint method of target remote.  */
9540
9541 static int
9542 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9543 {
9544   struct thread_info *thread = inferior_thread ();
9545
9546   return (thread->priv != NULL
9547           && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9548 }
9549
9550 /* The to_supports_stopped_by_hw_breakpoint method of target
9551    remote.  */
9552
9553 static int
9554 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9555 {
9556   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9557 }
9558
9559 static int
9560 remote_stopped_by_watchpoint (struct target_ops *ops)
9561 {
9562   struct thread_info *thread = inferior_thread ();
9563
9564   return (thread->priv != NULL
9565           && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9566 }
9567
9568 static int
9569 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9570 {
9571   struct thread_info *thread = inferior_thread ();
9572
9573   if (thread->priv != NULL
9574       && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9575     {
9576       *addr_p = thread->priv->watch_data_address;
9577       return 1;
9578     }
9579
9580   return 0;
9581 }
9582
9583
9584 static int
9585 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9586                              struct bp_target_info *bp_tgt)
9587 {
9588   CORE_ADDR addr = bp_tgt->reqstd_address;
9589   struct remote_state *rs;
9590   char *p, *endbuf;
9591   char *message;
9592   int bpsize;
9593
9594   /* The length field should be set to the size of a breakpoint
9595      instruction, even though we aren't inserting one ourselves.  */
9596
9597   gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9598
9599   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9600     return -1;
9601
9602   /* Make sure the remote is pointing at the right process, if
9603      necessary.  */
9604   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9605     set_general_process ();
9606
9607   rs = get_remote_state ();
9608   p = rs->buf;
9609   endbuf = rs->buf + get_remote_packet_size ();
9610
9611   *(p++) = 'Z';
9612   *(p++) = '1';
9613   *(p++) = ',';
9614
9615   addr = remote_address_masked (addr);
9616   p += hexnumstr (p, (ULONGEST) addr);
9617   xsnprintf (p, endbuf - p, ",%x", bpsize);
9618
9619   if (remote_supports_cond_breakpoints (self))
9620     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9621
9622   if (remote_can_run_breakpoint_commands (self))
9623     remote_add_target_side_commands (gdbarch, bp_tgt, p);
9624
9625   putpkt (rs->buf);
9626   getpkt (&rs->buf, &rs->buf_size, 0);
9627
9628   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9629     {
9630     case PACKET_ERROR:
9631       if (rs->buf[1] == '.')
9632         {
9633           message = strchr (rs->buf + 2, '.');
9634           if (message)
9635             error (_("Remote failure reply: %s"), message + 1);
9636         }
9637       return -1;
9638     case PACKET_UNKNOWN:
9639       return -1;
9640     case PACKET_OK:
9641       bp_tgt->placed_address = addr;
9642       bp_tgt->placed_size = bpsize;
9643       return 0;
9644     }
9645   internal_error (__FILE__, __LINE__,
9646                   _("remote_insert_hw_breakpoint: reached end of function"));
9647 }
9648
9649
9650 static int
9651 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9652                              struct bp_target_info *bp_tgt)
9653 {
9654   CORE_ADDR addr;
9655   struct remote_state *rs = get_remote_state ();
9656   char *p = rs->buf;
9657   char *endbuf = rs->buf + get_remote_packet_size ();
9658
9659   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9660     return -1;
9661
9662   /* Make sure the remote is pointing at the right process, if
9663      necessary.  */
9664   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9665     set_general_process ();
9666
9667   *(p++) = 'z';
9668   *(p++) = '1';
9669   *(p++) = ',';
9670
9671   addr = remote_address_masked (bp_tgt->placed_address);
9672   p += hexnumstr (p, (ULONGEST) addr);
9673   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);
9674
9675   putpkt (rs->buf);
9676   getpkt (&rs->buf, &rs->buf_size, 0);
9677
9678   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9679     {
9680     case PACKET_ERROR:
9681     case PACKET_UNKNOWN:
9682       return -1;
9683     case PACKET_OK:
9684       return 0;
9685     }
9686   internal_error (__FILE__, __LINE__,
9687                   _("remote_remove_hw_breakpoint: reached end of function"));
9688 }
9689
9690 /* Verify memory using the "qCRC:" request.  */
9691
9692 static int
9693 remote_verify_memory (struct target_ops *ops,
9694                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9695 {
9696   struct remote_state *rs = get_remote_state ();
9697   unsigned long host_crc, target_crc;
9698   char *tmp;
9699
9700   /* It doesn't make sense to use qCRC if the remote target is
9701      connected but not running.  */
9702   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9703     {
9704       enum packet_result result;
9705
9706       /* Make sure the remote is pointing at the right process.  */
9707       set_general_process ();
9708
9709       /* FIXME: assumes lma can fit into long.  */
9710       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9711                  (long) lma, (long) size);
9712       putpkt (rs->buf);
9713
9714       /* Be clever; compute the host_crc before waiting for target
9715          reply.  */
9716       host_crc = xcrc32 (data, size, 0xffffffff);
9717
9718       getpkt (&rs->buf, &rs->buf_size, 0);
9719
9720       result = packet_ok (rs->buf,
9721                           &remote_protocol_packets[PACKET_qCRC]);
9722       if (result == PACKET_ERROR)
9723         return -1;
9724       else if (result == PACKET_OK)
9725         {
9726           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9727             target_crc = target_crc * 16 + fromhex (*tmp);
9728
9729           return (host_crc == target_crc);
9730         }
9731     }
9732
9733   return simple_verify_memory (ops, data, lma, size);
9734 }
9735
9736 /* compare-sections command
9737
9738    With no arguments, compares each loadable section in the exec bfd
9739    with the same memory range on the target, and reports mismatches.
9740    Useful for verifying the image on the target against the exec file.  */
9741
9742 static void
9743 compare_sections_command (char *args, int from_tty)
9744 {
9745   asection *s;
9746   struct cleanup *old_chain;
9747   gdb_byte *sectdata;
9748   const char *sectname;
9749   bfd_size_type size;
9750   bfd_vma lma;
9751   int matched = 0;
9752   int mismatched = 0;
9753   int res;
9754   int read_only = 0;
9755
9756   if (!exec_bfd)
9757     error (_("command cannot be used without an exec file"));
9758
9759   /* Make sure the remote is pointing at the right process.  */
9760   set_general_process ();
9761
9762   if (args != NULL && strcmp (args, "-r") == 0)
9763     {
9764       read_only = 1;
9765       args = NULL;
9766     }
9767
9768   for (s = exec_bfd->sections; s; s = s->next)
9769     {
9770       if (!(s->flags & SEC_LOAD))
9771         continue;               /* Skip non-loadable section.  */
9772
9773       if (read_only && (s->flags & SEC_READONLY) == 0)
9774         continue;               /* Skip writeable sections */
9775
9776       size = bfd_get_section_size (s);
9777       if (size == 0)
9778         continue;               /* Skip zero-length section.  */
9779
9780       sectname = bfd_get_section_name (exec_bfd, s);
9781       if (args && strcmp (args, sectname) != 0)
9782         continue;               /* Not the section selected by user.  */
9783
9784       matched = 1;              /* Do this section.  */
9785       lma = s->lma;
9786
9787       sectdata = (gdb_byte *) xmalloc (size);
9788       old_chain = make_cleanup (xfree, sectdata);
9789       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9790
9791       res = target_verify_memory (sectdata, lma, size);
9792
9793       if (res == -1)
9794         error (_("target memory fault, section %s, range %s -- %s"), sectname,
9795                paddress (target_gdbarch (), lma),
9796                paddress (target_gdbarch (), lma + size));
9797
9798       printf_filtered ("Section %s, range %s -- %s: ", sectname,
9799                        paddress (target_gdbarch (), lma),
9800                        paddress (target_gdbarch (), lma + size));
9801       if (res)
9802         printf_filtered ("matched.\n");
9803       else
9804         {
9805           printf_filtered ("MIS-MATCHED!\n");
9806           mismatched++;
9807         }
9808
9809       do_cleanups (old_chain);
9810     }
9811   if (mismatched > 0)
9812     warning (_("One or more sections of the target image does not match\n\
9813 the loaded file\n"));
9814   if (args && !matched)
9815     printf_filtered (_("No loaded section named '%s'.\n"), args);
9816 }
9817
9818 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9819    into remote target.  The number of bytes written to the remote
9820    target is returned, or -1 for error.  */
9821
9822 static enum target_xfer_status
9823 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9824                     const char *annex, const gdb_byte *writebuf, 
9825                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9826                     struct packet_config *packet)
9827 {
9828   int i, buf_len;
9829   ULONGEST n;
9830   struct remote_state *rs = get_remote_state ();
9831   int max_size = get_memory_write_packet_size (); 
9832
9833   if (packet->support == PACKET_DISABLE)
9834     return TARGET_XFER_E_IO;
9835
9836   /* Insert header.  */
9837   i = snprintf (rs->buf, max_size, 
9838                 "qXfer:%s:write:%s:%s:",
9839                 object_name, annex ? annex : "",
9840                 phex_nz (offset, sizeof offset));
9841   max_size -= (i + 1);
9842
9843   /* Escape as much data as fits into rs->buf.  */
9844   buf_len = remote_escape_output 
9845     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9846
9847   if (putpkt_binary (rs->buf, i + buf_len) < 0
9848       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9849       || packet_ok (rs->buf, packet) != PACKET_OK)
9850     return TARGET_XFER_E_IO;
9851
9852   unpack_varlen_hex (rs->buf, &n);
9853
9854   *xfered_len = n;
9855   return TARGET_XFER_OK;
9856 }
9857
9858 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9859    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9860    number of bytes read is returned, or 0 for EOF, or -1 for error.
9861    The number of bytes read may be less than LEN without indicating an
9862    EOF.  PACKET is checked and updated to indicate whether the remote
9863    target supports this object.  */
9864
9865 static enum target_xfer_status
9866 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9867                    const char *annex,
9868                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9869                    ULONGEST *xfered_len,
9870                    struct packet_config *packet)
9871 {
9872   struct remote_state *rs = get_remote_state ();
9873   LONGEST i, n, packet_len;
9874
9875   if (packet->support == PACKET_DISABLE)
9876     return TARGET_XFER_E_IO;
9877
9878   /* Check whether we've cached an end-of-object packet that matches
9879      this request.  */
9880   if (rs->finished_object)
9881     {
9882       if (strcmp (object_name, rs->finished_object) == 0
9883           && strcmp (annex ? annex : "", rs->finished_annex) == 0
9884           && offset == rs->finished_offset)
9885         return TARGET_XFER_EOF;
9886
9887
9888       /* Otherwise, we're now reading something different.  Discard
9889          the cache.  */
9890       xfree (rs->finished_object);
9891       xfree (rs->finished_annex);
9892       rs->finished_object = NULL;
9893       rs->finished_annex = NULL;
9894     }
9895
9896   /* Request only enough to fit in a single packet.  The actual data
9897      may not, since we don't know how much of it will need to be escaped;
9898      the target is free to respond with slightly less data.  We subtract
9899      five to account for the response type and the protocol frame.  */
9900   n = min (get_remote_packet_size () - 5, len);
9901   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9902             object_name, annex ? annex : "",
9903             phex_nz (offset, sizeof offset),
9904             phex_nz (n, sizeof n));
9905   i = putpkt (rs->buf);
9906   if (i < 0)
9907     return TARGET_XFER_E_IO;
9908
9909   rs->buf[0] = '\0';
9910   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9911   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9912     return TARGET_XFER_E_IO;
9913
9914   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9915     error (_("Unknown remote qXfer reply: %s"), rs->buf);
9916
9917   /* 'm' means there is (or at least might be) more data after this
9918      batch.  That does not make sense unless there's at least one byte
9919      of data in this reply.  */
9920   if (rs->buf[0] == 'm' && packet_len == 1)
9921     error (_("Remote qXfer reply contained no data."));
9922
9923   /* Got some data.  */
9924   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9925                              packet_len - 1, readbuf, n);
9926
9927   /* 'l' is an EOF marker, possibly including a final block of data,
9928      or possibly empty.  If we have the final block of a non-empty
9929      object, record this fact to bypass a subsequent partial read.  */
9930   if (rs->buf[0] == 'l' && offset + i > 0)
9931     {
9932       rs->finished_object = xstrdup (object_name);
9933       rs->finished_annex = xstrdup (annex ? annex : "");
9934       rs->finished_offset = offset + i;
9935     }
9936
9937   if (i == 0)
9938     return TARGET_XFER_EOF;
9939   else
9940     {
9941       *xfered_len = i;
9942       return TARGET_XFER_OK;
9943     }
9944 }
9945
9946 static enum target_xfer_status
9947 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9948                      const char *annex, gdb_byte *readbuf,
9949                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9950                      ULONGEST *xfered_len)
9951 {
9952   struct remote_state *rs;
9953   int i;
9954   char *p2;
9955   char query_type;
9956   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9957
9958   set_remote_traceframe ();
9959   set_general_thread (inferior_ptid);
9960
9961   rs = get_remote_state ();
9962
9963   /* Handle memory using the standard memory routines.  */
9964   if (object == TARGET_OBJECT_MEMORY)
9965     {
9966       /* If the remote target is connected but not running, we should
9967          pass this request down to a lower stratum (e.g. the executable
9968          file).  */
9969       if (!target_has_execution)
9970         return TARGET_XFER_EOF;
9971
9972       if (writebuf != NULL)
9973         return remote_write_bytes (offset, writebuf, len, unit_size,
9974                                    xfered_len);
9975       else
9976         return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9977                                   xfered_len);
9978     }
9979
9980   /* Handle SPU memory using qxfer packets.  */
9981   if (object == TARGET_OBJECT_SPU)
9982     {
9983       if (readbuf)
9984         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9985                                   xfered_len, &remote_protocol_packets
9986                                   [PACKET_qXfer_spu_read]);
9987       else
9988         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9989                                    xfered_len, &remote_protocol_packets
9990                                    [PACKET_qXfer_spu_write]);
9991     }
9992
9993   /* Handle extra signal info using qxfer packets.  */
9994   if (object == TARGET_OBJECT_SIGNAL_INFO)
9995     {
9996       if (readbuf)
9997         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9998                                   xfered_len, &remote_protocol_packets
9999                                   [PACKET_qXfer_siginfo_read]);
10000       else
10001         return remote_write_qxfer (ops, "siginfo", annex,
10002                                    writebuf, offset, len, xfered_len,
10003                                    &remote_protocol_packets
10004                                    [PACKET_qXfer_siginfo_write]);
10005     }
10006
10007   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10008     {
10009       if (readbuf)
10010         return remote_read_qxfer (ops, "statictrace", annex,
10011                                   readbuf, offset, len, xfered_len,
10012                                   &remote_protocol_packets
10013                                   [PACKET_qXfer_statictrace_read]);
10014       else
10015         return TARGET_XFER_E_IO;
10016     }
10017
10018   /* Only handle flash writes.  */
10019   if (writebuf != NULL)
10020     {
10021       switch (object)
10022         {
10023         case TARGET_OBJECT_FLASH:
10024           return remote_flash_write (ops, offset, len, xfered_len,
10025                                      writebuf);
10026
10027         default:
10028           return TARGET_XFER_E_IO;
10029         }
10030     }
10031
10032   /* Map pre-existing objects onto letters.  DO NOT do this for new
10033      objects!!!  Instead specify new query packets.  */
10034   switch (object)
10035     {
10036     case TARGET_OBJECT_AVR:
10037       query_type = 'R';
10038       break;
10039
10040     case TARGET_OBJECT_AUXV:
10041       gdb_assert (annex == NULL);
10042       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10043                                 xfered_len,
10044                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10045
10046     case TARGET_OBJECT_AVAILABLE_FEATURES:
10047       return remote_read_qxfer
10048         (ops, "features", annex, readbuf, offset, len, xfered_len,
10049          &remote_protocol_packets[PACKET_qXfer_features]);
10050
10051     case TARGET_OBJECT_LIBRARIES:
10052       return remote_read_qxfer
10053         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10054          &remote_protocol_packets[PACKET_qXfer_libraries]);
10055
10056     case TARGET_OBJECT_LIBRARIES_SVR4:
10057       return remote_read_qxfer
10058         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10059          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10060
10061     case TARGET_OBJECT_MEMORY_MAP:
10062       gdb_assert (annex == NULL);
10063       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10064                                  xfered_len,
10065                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10066
10067     case TARGET_OBJECT_OSDATA:
10068       /* Should only get here if we're connected.  */
10069       gdb_assert (rs->remote_desc);
10070       return remote_read_qxfer
10071         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10072         &remote_protocol_packets[PACKET_qXfer_osdata]);
10073
10074     case TARGET_OBJECT_THREADS:
10075       gdb_assert (annex == NULL);
10076       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10077                                 xfered_len,
10078                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10079
10080     case TARGET_OBJECT_TRACEFRAME_INFO:
10081       gdb_assert (annex == NULL);
10082       return remote_read_qxfer
10083         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10084          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10085
10086     case TARGET_OBJECT_FDPIC:
10087       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10088                                 xfered_len,
10089                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10090
10091     case TARGET_OBJECT_OPENVMS_UIB:
10092       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10093                                 xfered_len,
10094                                 &remote_protocol_packets[PACKET_qXfer_uib]);
10095
10096     case TARGET_OBJECT_BTRACE:
10097       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10098                                 xfered_len,
10099         &remote_protocol_packets[PACKET_qXfer_btrace]);
10100
10101     case TARGET_OBJECT_BTRACE_CONF:
10102       return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10103                                 len, xfered_len,
10104         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10105
10106     case TARGET_OBJECT_EXEC_FILE:
10107       return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10108                                 len, xfered_len,
10109         &remote_protocol_packets[PACKET_qXfer_exec_file]);
10110
10111     default:
10112       return TARGET_XFER_E_IO;
10113     }
10114
10115   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
10116      large enough let the caller deal with it.  */
10117   if (len < get_remote_packet_size ())
10118     return TARGET_XFER_E_IO;
10119   len = get_remote_packet_size ();
10120
10121   /* Except for querying the minimum buffer size, target must be open.  */
10122   if (!rs->remote_desc)
10123     error (_("remote query is only available after target open"));
10124
10125   gdb_assert (annex != NULL);
10126   gdb_assert (readbuf != NULL);
10127
10128   p2 = rs->buf;
10129   *p2++ = 'q';
10130   *p2++ = query_type;
10131
10132   /* We used one buffer char for the remote protocol q command and
10133      another for the query type.  As the remote protocol encapsulation
10134      uses 4 chars plus one extra in case we are debugging
10135      (remote_debug), we have PBUFZIZ - 7 left to pack the query
10136      string.  */
10137   i = 0;
10138   while (annex[i] && (i < (get_remote_packet_size () - 8)))
10139     {
10140       /* Bad caller may have sent forbidden characters.  */
10141       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10142       *p2++ = annex[i];
10143       i++;
10144     }
10145   *p2 = '\0';
10146   gdb_assert (annex[i] == '\0');
10147
10148   i = putpkt (rs->buf);
10149   if (i < 0)
10150     return TARGET_XFER_E_IO;
10151
10152   getpkt (&rs->buf, &rs->buf_size, 0);
10153   strcpy ((char *) readbuf, rs->buf);
10154
10155   *xfered_len = strlen ((char *) readbuf);
10156   return TARGET_XFER_OK;
10157 }
10158
10159 static int
10160 remote_search_memory (struct target_ops* ops,
10161                       CORE_ADDR start_addr, ULONGEST search_space_len,
10162                       const gdb_byte *pattern, ULONGEST pattern_len,
10163                       CORE_ADDR *found_addrp)
10164 {
10165   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10166   struct remote_state *rs = get_remote_state ();
10167   int max_size = get_memory_write_packet_size ();
10168   struct packet_config *packet =
10169     &remote_protocol_packets[PACKET_qSearch_memory];
10170   /* Number of packet bytes used to encode the pattern;
10171      this could be more than PATTERN_LEN due to escape characters.  */
10172   int escaped_pattern_len;
10173   /* Amount of pattern that was encodable in the packet.  */
10174   int used_pattern_len;
10175   int i;
10176   int found;
10177   ULONGEST found_addr;
10178
10179   /* Don't go to the target if we don't have to.
10180      This is done before checking packet->support to avoid the possibility that
10181      a success for this edge case means the facility works in general.  */
10182   if (pattern_len > search_space_len)
10183     return 0;
10184   if (pattern_len == 0)
10185     {
10186       *found_addrp = start_addr;
10187       return 1;
10188     }
10189
10190   /* If we already know the packet isn't supported, fall back to the simple
10191      way of searching memory.  */
10192
10193   if (packet_config_support (packet) == PACKET_DISABLE)
10194     {
10195       /* Target doesn't provided special support, fall back and use the
10196          standard support (copy memory and do the search here).  */
10197       return simple_search_memory (ops, start_addr, search_space_len,
10198                                    pattern, pattern_len, found_addrp);
10199     }
10200
10201   /* Make sure the remote is pointing at the right process.  */
10202   set_general_process ();
10203
10204   /* Insert header.  */
10205   i = snprintf (rs->buf, max_size, 
10206                 "qSearch:memory:%s;%s;",
10207                 phex_nz (start_addr, addr_size),
10208                 phex_nz (search_space_len, sizeof (search_space_len)));
10209   max_size -= (i + 1);
10210
10211   /* Escape as much data as fits into rs->buf.  */
10212   escaped_pattern_len =
10213     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10214                           &used_pattern_len, max_size);
10215
10216   /* Bail if the pattern is too large.  */
10217   if (used_pattern_len != pattern_len)
10218     error (_("Pattern is too large to transmit to remote target."));
10219
10220   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10221       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10222       || packet_ok (rs->buf, packet) != PACKET_OK)
10223     {
10224       /* The request may not have worked because the command is not
10225          supported.  If so, fall back to the simple way.  */
10226       if (packet->support == PACKET_DISABLE)
10227         {
10228           return simple_search_memory (ops, start_addr, search_space_len,
10229                                        pattern, pattern_len, found_addrp);
10230         }
10231       return -1;
10232     }
10233
10234   if (rs->buf[0] == '0')
10235     found = 0;
10236   else if (rs->buf[0] == '1')
10237     {
10238       found = 1;
10239       if (rs->buf[1] != ',')
10240         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10241       unpack_varlen_hex (rs->buf + 2, &found_addr);
10242       *found_addrp = found_addr;
10243     }
10244   else
10245     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10246
10247   return found;
10248 }
10249
10250 static void
10251 remote_rcmd (struct target_ops *self, const char *command,
10252              struct ui_file *outbuf)
10253 {
10254   struct remote_state *rs = get_remote_state ();
10255   char *p = rs->buf;
10256
10257   if (!rs->remote_desc)
10258     error (_("remote rcmd is only available after target open"));
10259
10260   /* Send a NULL command across as an empty command.  */
10261   if (command == NULL)
10262     command = "";
10263
10264   /* The query prefix.  */
10265   strcpy (rs->buf, "qRcmd,");
10266   p = strchr (rs->buf, '\0');
10267
10268   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10269       > get_remote_packet_size ())
10270     error (_("\"monitor\" command ``%s'' is too long."), command);
10271
10272   /* Encode the actual command.  */
10273   bin2hex ((const gdb_byte *) command, p, strlen (command));
10274
10275   if (putpkt (rs->buf) < 0)
10276     error (_("Communication problem with target."));
10277
10278   /* get/display the response */
10279   while (1)
10280     {
10281       char *buf;
10282
10283       /* XXX - see also remote_get_noisy_reply().  */
10284       QUIT;                     /* Allow user to bail out with ^C.  */
10285       rs->buf[0] = '\0';
10286       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10287         { 
10288           /* Timeout.  Continue to (try to) read responses.
10289              This is better than stopping with an error, assuming the stub
10290              is still executing the (long) monitor command.
10291              If needed, the user can interrupt gdb using C-c, obtaining
10292              an effect similar to stop on timeout.  */
10293           continue;
10294         }
10295       buf = rs->buf;
10296       if (buf[0] == '\0')
10297         error (_("Target does not support this command."));
10298       if (buf[0] == 'O' && buf[1] != 'K')
10299         {
10300           remote_console_output (buf + 1); /* 'O' message from stub.  */
10301           continue;
10302         }
10303       if (strcmp (buf, "OK") == 0)
10304         break;
10305       if (strlen (buf) == 3 && buf[0] == 'E'
10306           && isdigit (buf[1]) && isdigit (buf[2]))
10307         {
10308           error (_("Protocol error with Rcmd"));
10309         }
10310       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10311         {
10312           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10313
10314           fputc_unfiltered (c, outbuf);
10315         }
10316       break;
10317     }
10318 }
10319
10320 static VEC(mem_region_s) *
10321 remote_memory_map (struct target_ops *ops)
10322 {
10323   VEC(mem_region_s) *result = NULL;
10324   char *text = target_read_stralloc (&current_target,
10325                                      TARGET_OBJECT_MEMORY_MAP, NULL);
10326
10327   if (text)
10328     {
10329       struct cleanup *back_to = make_cleanup (xfree, text);
10330
10331       result = parse_memory_map (text);
10332       do_cleanups (back_to);
10333     }
10334
10335   return result;
10336 }
10337
10338 static void
10339 packet_command (char *args, int from_tty)
10340 {
10341   struct remote_state *rs = get_remote_state ();
10342
10343   if (!rs->remote_desc)
10344     error (_("command can only be used with remote target"));
10345
10346   if (!args)
10347     error (_("remote-packet command requires packet text as argument"));
10348
10349   puts_filtered ("sending: ");
10350   print_packet (args);
10351   puts_filtered ("\n");
10352   putpkt (args);
10353
10354   getpkt (&rs->buf, &rs->buf_size, 0);
10355   puts_filtered ("received: ");
10356   print_packet (rs->buf);
10357   puts_filtered ("\n");
10358 }
10359
10360 #if 0
10361 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10362
10363 static void display_thread_info (struct gdb_ext_thread_info *info);
10364
10365 static void threadset_test_cmd (char *cmd, int tty);
10366
10367 static void threadalive_test (char *cmd, int tty);
10368
10369 static void threadlist_test_cmd (char *cmd, int tty);
10370
10371 int get_and_display_threadinfo (threadref *ref);
10372
10373 static void threadinfo_test_cmd (char *cmd, int tty);
10374
10375 static int thread_display_step (threadref *ref, void *context);
10376
10377 static void threadlist_update_test_cmd (char *cmd, int tty);
10378
10379 static void init_remote_threadtests (void);
10380
10381 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
10382
10383 static void
10384 threadset_test_cmd (char *cmd, int tty)
10385 {
10386   int sample_thread = SAMPLE_THREAD;
10387
10388   printf_filtered (_("Remote threadset test\n"));
10389   set_general_thread (sample_thread);
10390 }
10391
10392
10393 static void
10394 threadalive_test (char *cmd, int tty)
10395 {
10396   int sample_thread = SAMPLE_THREAD;
10397   int pid = ptid_get_pid (inferior_ptid);
10398   ptid_t ptid = ptid_build (pid, sample_thread, 0);
10399
10400   if (remote_thread_alive (ptid))
10401     printf_filtered ("PASS: Thread alive test\n");
10402   else
10403     printf_filtered ("FAIL: Thread alive test\n");
10404 }
10405
10406 void output_threadid (char *title, threadref *ref);
10407
10408 void
10409 output_threadid (char *title, threadref *ref)
10410 {
10411   char hexid[20];
10412
10413   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
10414   hexid[16] = 0;
10415   printf_filtered ("%s  %s\n", title, (&hexid[0]));
10416 }
10417
10418 static void
10419 threadlist_test_cmd (char *cmd, int tty)
10420 {
10421   int startflag = 1;
10422   threadref nextthread;
10423   int done, result_count;
10424   threadref threadlist[3];
10425
10426   printf_filtered ("Remote Threadlist test\n");
10427   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10428                               &result_count, &threadlist[0]))
10429     printf_filtered ("FAIL: threadlist test\n");
10430   else
10431     {
10432       threadref *scan = threadlist;
10433       threadref *limit = scan + result_count;
10434
10435       while (scan < limit)
10436         output_threadid (" thread ", scan++);
10437     }
10438 }
10439
10440 void
10441 display_thread_info (struct gdb_ext_thread_info *info)
10442 {
10443   output_threadid ("Threadid: ", &info->threadid);
10444   printf_filtered ("Name: %s\n ", info->shortname);
10445   printf_filtered ("State: %s\n", info->display);
10446   printf_filtered ("other: %s\n\n", info->more_display);
10447 }
10448
10449 int
10450 get_and_display_threadinfo (threadref *ref)
10451 {
10452   int result;
10453   int set;
10454   struct gdb_ext_thread_info threadinfo;
10455
10456   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10457     | TAG_MOREDISPLAY | TAG_DISPLAY;
10458   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10459     display_thread_info (&threadinfo);
10460   return result;
10461 }
10462
10463 static void
10464 threadinfo_test_cmd (char *cmd, int tty)
10465 {
10466   int athread = SAMPLE_THREAD;
10467   threadref thread;
10468   int set;
10469
10470   int_to_threadref (&thread, athread);
10471   printf_filtered ("Remote Threadinfo test\n");
10472   if (!get_and_display_threadinfo (&thread))
10473     printf_filtered ("FAIL cannot get thread info\n");
10474 }
10475
10476 static int
10477 thread_display_step (threadref *ref, void *context)
10478 {
10479   /* output_threadid(" threadstep ",ref); *//* simple test */
10480   return get_and_display_threadinfo (ref);
10481 }
10482
10483 static void
10484 threadlist_update_test_cmd (char *cmd, int tty)
10485 {
10486   printf_filtered ("Remote Threadlist update test\n");
10487   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10488 }
10489
10490 static void
10491 init_remote_threadtests (void)
10492 {
10493   add_com ("tlist", class_obscure, threadlist_test_cmd,
10494            _("Fetch and print the remote list of "
10495              "thread identifiers, one pkt only"));
10496   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10497            _("Fetch and display info about one thread"));
10498   add_com ("tset", class_obscure, threadset_test_cmd,
10499            _("Test setting to a different thread"));
10500   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10501            _("Iterate through updating all remote thread info"));
10502   add_com ("talive", class_obscure, threadalive_test,
10503            _(" Remote thread alive test "));
10504 }
10505
10506 #endif /* 0 */
10507
10508 /* Convert a thread ID to a string.  Returns the string in a static
10509    buffer.  */
10510
10511 static char *
10512 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10513 {
10514   static char buf[64];
10515   struct remote_state *rs = get_remote_state ();
10516
10517   if (ptid_equal (ptid, null_ptid))
10518     return normal_pid_to_str (ptid);
10519   else if (ptid_is_pid (ptid))
10520     {
10521       /* Printing an inferior target id.  */
10522
10523       /* When multi-process extensions are off, there's no way in the
10524          remote protocol to know the remote process id, if there's any
10525          at all.  There's one exception --- when we're connected with
10526          target extended-remote, and we manually attached to a process
10527          with "attach PID".  We don't record anywhere a flag that
10528          allows us to distinguish that case from the case of
10529          connecting with extended-remote and the stub already being
10530          attached to a process, and reporting yes to qAttached, hence
10531          no smart special casing here.  */
10532       if (!remote_multi_process_p (rs))
10533         {
10534           xsnprintf (buf, sizeof buf, "Remote target");
10535           return buf;
10536         }
10537
10538       return normal_pid_to_str (ptid);
10539     }
10540   else
10541     {
10542       if (ptid_equal (magic_null_ptid, ptid))
10543         xsnprintf (buf, sizeof buf, "Thread <main>");
10544       else if (remote_multi_process_p (rs))
10545         if (ptid_get_lwp (ptid) == 0)
10546           return normal_pid_to_str (ptid);
10547         else
10548           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10549                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
10550       else
10551         xsnprintf (buf, sizeof buf, "Thread %ld",
10552                    ptid_get_lwp (ptid));
10553       return buf;
10554     }
10555 }
10556
10557 /* Get the address of the thread local variable in OBJFILE which is
10558    stored at OFFSET within the thread local storage for thread PTID.  */
10559
10560 static CORE_ADDR
10561 remote_get_thread_local_address (struct target_ops *ops,
10562                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10563 {
10564   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10565     {
10566       struct remote_state *rs = get_remote_state ();
10567       char *p = rs->buf;
10568       char *endp = rs->buf + get_remote_packet_size ();
10569       enum packet_result result;
10570
10571       strcpy (p, "qGetTLSAddr:");
10572       p += strlen (p);
10573       p = write_ptid (p, endp, ptid);
10574       *p++ = ',';
10575       p += hexnumstr (p, offset);
10576       *p++ = ',';
10577       p += hexnumstr (p, lm);
10578       *p++ = '\0';
10579
10580       putpkt (rs->buf);
10581       getpkt (&rs->buf, &rs->buf_size, 0);
10582       result = packet_ok (rs->buf,
10583                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
10584       if (result == PACKET_OK)
10585         {
10586           ULONGEST result;
10587
10588           unpack_varlen_hex (rs->buf, &result);
10589           return result;
10590         }
10591       else if (result == PACKET_UNKNOWN)
10592         throw_error (TLS_GENERIC_ERROR,
10593                      _("Remote target doesn't support qGetTLSAddr packet"));
10594       else
10595         throw_error (TLS_GENERIC_ERROR,
10596                      _("Remote target failed to process qGetTLSAddr request"));
10597     }
10598   else
10599     throw_error (TLS_GENERIC_ERROR,
10600                  _("TLS not supported or disabled on this target"));
10601   /* Not reached.  */
10602   return 0;
10603 }
10604
10605 /* Provide thread local base, i.e. Thread Information Block address.
10606    Returns 1 if ptid is found and thread_local_base is non zero.  */
10607
10608 static int
10609 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10610 {
10611   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10612     {
10613       struct remote_state *rs = get_remote_state ();
10614       char *p = rs->buf;
10615       char *endp = rs->buf + get_remote_packet_size ();
10616       enum packet_result result;
10617
10618       strcpy (p, "qGetTIBAddr:");
10619       p += strlen (p);
10620       p = write_ptid (p, endp, ptid);
10621       *p++ = '\0';
10622
10623       putpkt (rs->buf);
10624       getpkt (&rs->buf, &rs->buf_size, 0);
10625       result = packet_ok (rs->buf,
10626                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
10627       if (result == PACKET_OK)
10628         {
10629           ULONGEST result;
10630
10631           unpack_varlen_hex (rs->buf, &result);
10632           if (addr)
10633             *addr = (CORE_ADDR) result;
10634           return 1;
10635         }
10636       else if (result == PACKET_UNKNOWN)
10637         error (_("Remote target doesn't support qGetTIBAddr packet"));
10638       else
10639         error (_("Remote target failed to process qGetTIBAddr request"));
10640     }
10641   else
10642     error (_("qGetTIBAddr not supported or disabled on this target"));
10643   /* Not reached.  */
10644   return 0;
10645 }
10646
10647 /* Support for inferring a target description based on the current
10648    architecture and the size of a 'g' packet.  While the 'g' packet
10649    can have any size (since optional registers can be left off the
10650    end), some sizes are easily recognizable given knowledge of the
10651    approximate architecture.  */
10652
10653 struct remote_g_packet_guess
10654 {
10655   int bytes;
10656   const struct target_desc *tdesc;
10657 };
10658 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10659 DEF_VEC_O(remote_g_packet_guess_s);
10660
10661 struct remote_g_packet_data
10662 {
10663   VEC(remote_g_packet_guess_s) *guesses;
10664 };
10665
10666 static struct gdbarch_data *remote_g_packet_data_handle;
10667
10668 static void *
10669 remote_g_packet_data_init (struct obstack *obstack)
10670 {
10671   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10672 }
10673
10674 void
10675 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10676                                 const struct target_desc *tdesc)
10677 {
10678   struct remote_g_packet_data *data
10679     = ((struct remote_g_packet_data *)
10680        gdbarch_data (gdbarch, remote_g_packet_data_handle));
10681   struct remote_g_packet_guess new_guess, *guess;
10682   int ix;
10683
10684   gdb_assert (tdesc != NULL);
10685
10686   for (ix = 0;
10687        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10688        ix++)
10689     if (guess->bytes == bytes)
10690       internal_error (__FILE__, __LINE__,
10691                       _("Duplicate g packet description added for size %d"),
10692                       bytes);
10693
10694   new_guess.bytes = bytes;
10695   new_guess.tdesc = tdesc;
10696   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10697 }
10698
10699 /* Return 1 if remote_read_description would do anything on this target
10700    and architecture, 0 otherwise.  */
10701
10702 static int
10703 remote_read_description_p (struct target_ops *target)
10704 {
10705   struct remote_g_packet_data *data
10706     = ((struct remote_g_packet_data *)
10707        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10708
10709   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10710     return 1;
10711
10712   return 0;
10713 }
10714
10715 static const struct target_desc *
10716 remote_read_description (struct target_ops *target)
10717 {
10718   struct remote_g_packet_data *data
10719     = ((struct remote_g_packet_data *)
10720        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10721
10722   /* Do not try this during initial connection, when we do not know
10723      whether there is a running but stopped thread.  */
10724   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10725     return target->beneath->to_read_description (target->beneath);
10726
10727   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10728     {
10729       struct remote_g_packet_guess *guess;
10730       int ix;
10731       int bytes = send_g_packet ();
10732
10733       for (ix = 0;
10734            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10735            ix++)
10736         if (guess->bytes == bytes)
10737           return guess->tdesc;
10738
10739       /* We discard the g packet.  A minor optimization would be to
10740          hold on to it, and fill the register cache once we have selected
10741          an architecture, but it's too tricky to do safely.  */
10742     }
10743
10744   return target->beneath->to_read_description (target->beneath);
10745 }
10746
10747 /* Remote file transfer support.  This is host-initiated I/O, not
10748    target-initiated; for target-initiated, see remote-fileio.c.  */
10749
10750 /* If *LEFT is at least the length of STRING, copy STRING to
10751    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10752    decrease *LEFT.  Otherwise raise an error.  */
10753
10754 static void
10755 remote_buffer_add_string (char **buffer, int *left, char *string)
10756 {
10757   int len = strlen (string);
10758
10759   if (len > *left)
10760     error (_("Packet too long for target."));
10761
10762   memcpy (*buffer, string, len);
10763   *buffer += len;
10764   *left -= len;
10765
10766   /* NUL-terminate the buffer as a convenience, if there is
10767      room.  */
10768   if (*left)
10769     **buffer = '\0';
10770 }
10771
10772 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10773    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10774    decrease *LEFT.  Otherwise raise an error.  */
10775
10776 static void
10777 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10778                          int len)
10779 {
10780   if (2 * len > *left)
10781     error (_("Packet too long for target."));
10782
10783   bin2hex (bytes, *buffer, len);
10784   *buffer += 2 * len;
10785   *left -= 2 * len;
10786
10787   /* NUL-terminate the buffer as a convenience, if there is
10788      room.  */
10789   if (*left)
10790     **buffer = '\0';
10791 }
10792
10793 /* If *LEFT is large enough, convert VALUE to hex and add it to
10794    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10795    decrease *LEFT.  Otherwise raise an error.  */
10796
10797 static void
10798 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10799 {
10800   int len = hexnumlen (value);
10801
10802   if (len > *left)
10803     error (_("Packet too long for target."));
10804
10805   hexnumstr (*buffer, value);
10806   *buffer += len;
10807   *left -= len;
10808
10809   /* NUL-terminate the buffer as a convenience, if there is
10810      room.  */
10811   if (*left)
10812     **buffer = '\0';
10813 }
10814
10815 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
10816    value, *REMOTE_ERRNO to the remote error number or zero if none
10817    was included, and *ATTACHMENT to point to the start of the annex
10818    if any.  The length of the packet isn't needed here; there may
10819    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10820
10821    Return 0 if the packet could be parsed, -1 if it could not.  If
10822    -1 is returned, the other variables may not be initialized.  */
10823
10824 static int
10825 remote_hostio_parse_result (char *buffer, int *retcode,
10826                             int *remote_errno, char **attachment)
10827 {
10828   char *p, *p2;
10829
10830   *remote_errno = 0;
10831   *attachment = NULL;
10832
10833   if (buffer[0] != 'F')
10834     return -1;
10835
10836   errno = 0;
10837   *retcode = strtol (&buffer[1], &p, 16);
10838   if (errno != 0 || p == &buffer[1])
10839     return -1;
10840
10841   /* Check for ",errno".  */
10842   if (*p == ',')
10843     {
10844       errno = 0;
10845       *remote_errno = strtol (p + 1, &p2, 16);
10846       if (errno != 0 || p + 1 == p2)
10847         return -1;
10848       p = p2;
10849     }
10850
10851   /* Check for ";attachment".  If there is no attachment, the
10852      packet should end here.  */
10853   if (*p == ';')
10854     {
10855       *attachment = p + 1;
10856       return 0;
10857     }
10858   else if (*p == '\0')
10859     return 0;
10860   else
10861     return -1;
10862 }
10863
10864 /* Send a prepared I/O packet to the target and read its response.
10865    The prepared packet is in the global RS->BUF before this function
10866    is called, and the answer is there when we return.
10867
10868    COMMAND_BYTES is the length of the request to send, which may include
10869    binary data.  WHICH_PACKET is the packet configuration to check
10870    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
10871    is set to the error number and -1 is returned.  Otherwise the value
10872    returned by the function is returned.
10873
10874    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10875    attachment is expected; an error will be reported if there's a
10876    mismatch.  If one is found, *ATTACHMENT will be set to point into
10877    the packet buffer and *ATTACHMENT_LEN will be set to the
10878    attachment's length.  */
10879
10880 static int
10881 remote_hostio_send_command (int command_bytes, int which_packet,
10882                             int *remote_errno, char **attachment,
10883                             int *attachment_len)
10884 {
10885   struct remote_state *rs = get_remote_state ();
10886   int ret, bytes_read;
10887   char *attachment_tmp;
10888
10889   if (!rs->remote_desc
10890       || packet_support (which_packet) == PACKET_DISABLE)
10891     {
10892       *remote_errno = FILEIO_ENOSYS;
10893       return -1;
10894     }
10895
10896   putpkt_binary (rs->buf, command_bytes);
10897   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10898
10899   /* If it timed out, something is wrong.  Don't try to parse the
10900      buffer.  */
10901   if (bytes_read < 0)
10902     {
10903       *remote_errno = FILEIO_EINVAL;
10904       return -1;
10905     }
10906
10907   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10908     {
10909     case PACKET_ERROR:
10910       *remote_errno = FILEIO_EINVAL;
10911       return -1;
10912     case PACKET_UNKNOWN:
10913       *remote_errno = FILEIO_ENOSYS;
10914       return -1;
10915     case PACKET_OK:
10916       break;
10917     }
10918
10919   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10920                                   &attachment_tmp))
10921     {
10922       *remote_errno = FILEIO_EINVAL;
10923       return -1;
10924     }
10925
10926   /* Make sure we saw an attachment if and only if we expected one.  */
10927   if ((attachment_tmp == NULL && attachment != NULL)
10928       || (attachment_tmp != NULL && attachment == NULL))
10929     {
10930       *remote_errno = FILEIO_EINVAL;
10931       return -1;
10932     }
10933
10934   /* If an attachment was found, it must point into the packet buffer;
10935      work out how many bytes there were.  */
10936   if (attachment_tmp != NULL)
10937     {
10938       *attachment = attachment_tmp;
10939       *attachment_len = bytes_read - (*attachment - rs->buf);
10940     }
10941
10942   return ret;
10943 }
10944
10945 /* Invalidate the readahead cache.  */
10946
10947 static void
10948 readahead_cache_invalidate (void)
10949 {
10950   struct remote_state *rs = get_remote_state ();
10951
10952   rs->readahead_cache.fd = -1;
10953 }
10954
10955 /* Invalidate the readahead cache if it is holding data for FD.  */
10956
10957 static void
10958 readahead_cache_invalidate_fd (int fd)
10959 {
10960   struct remote_state *rs = get_remote_state ();
10961
10962   if (rs->readahead_cache.fd == fd)
10963     rs->readahead_cache.fd = -1;
10964 }
10965
10966 /* Set the filesystem remote_hostio functions that take FILENAME
10967    arguments will use.  Return 0 on success, or -1 if an error
10968    occurs (and set *REMOTE_ERRNO).  */
10969
10970 static int
10971 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10972 {
10973   struct remote_state *rs = get_remote_state ();
10974   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10975   char *p = rs->buf;
10976   int left = get_remote_packet_size () - 1;
10977   char arg[9];
10978   int ret;
10979
10980   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10981     return 0;
10982
10983   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10984     return 0;
10985
10986   remote_buffer_add_string (&p, &left, "vFile:setfs:");
10987
10988   xsnprintf (arg, sizeof (arg), "%x", required_pid);
10989   remote_buffer_add_string (&p, &left, arg);
10990
10991   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10992                                     remote_errno, NULL, NULL);
10993
10994   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10995     return 0;
10996
10997   if (ret == 0)
10998     rs->fs_pid = required_pid;
10999
11000   return ret;
11001 }
11002
11003 /* Implementation of to_fileio_open.  */
11004
11005 static int
11006 remote_hostio_open (struct target_ops *self,
11007                     struct inferior *inf, const char *filename,
11008                     int flags, int mode, int warn_if_slow,
11009                     int *remote_errno)
11010 {
11011   struct remote_state *rs = get_remote_state ();
11012   char *p = rs->buf;
11013   int left = get_remote_packet_size () - 1;
11014
11015   if (warn_if_slow)
11016     {
11017       static int warning_issued = 0;
11018
11019       printf_unfiltered (_("Reading %s from remote target...\n"),
11020                          filename);
11021
11022       if (!warning_issued)
11023         {
11024           warning (_("File transfers from remote targets can be slow."
11025                      " Use \"set sysroot\" to access files locally"
11026                      " instead."));
11027           warning_issued = 1;
11028         }
11029     }
11030
11031   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11032     return -1;
11033
11034   remote_buffer_add_string (&p, &left, "vFile:open:");
11035
11036   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11037                            strlen (filename));
11038   remote_buffer_add_string (&p, &left, ",");
11039
11040   remote_buffer_add_int (&p, &left, flags);
11041   remote_buffer_add_string (&p, &left, ",");
11042
11043   remote_buffer_add_int (&p, &left, mode);
11044
11045   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11046                                      remote_errno, NULL, NULL);
11047 }
11048
11049 /* Implementation of to_fileio_pwrite.  */
11050
11051 static int
11052 remote_hostio_pwrite (struct target_ops *self,
11053                       int fd, const gdb_byte *write_buf, int len,
11054                       ULONGEST offset, int *remote_errno)
11055 {
11056   struct remote_state *rs = get_remote_state ();
11057   char *p = rs->buf;
11058   int left = get_remote_packet_size ();
11059   int out_len;
11060
11061   readahead_cache_invalidate_fd (fd);
11062
11063   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11064
11065   remote_buffer_add_int (&p, &left, fd);
11066   remote_buffer_add_string (&p, &left, ",");
11067
11068   remote_buffer_add_int (&p, &left, offset);
11069   remote_buffer_add_string (&p, &left, ",");
11070
11071   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11072                              get_remote_packet_size () - (p - rs->buf));
11073
11074   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11075                                      remote_errno, NULL, NULL);
11076 }
11077
11078 /* Helper for the implementation of to_fileio_pread.  Read the file
11079    from the remote side with vFile:pread.  */
11080
11081 static int
11082 remote_hostio_pread_vFile (struct target_ops *self,
11083                            int fd, gdb_byte *read_buf, int len,
11084                            ULONGEST offset, int *remote_errno)
11085 {
11086   struct remote_state *rs = get_remote_state ();
11087   char *p = rs->buf;
11088   char *attachment;
11089   int left = get_remote_packet_size ();
11090   int ret, attachment_len;
11091   int read_len;
11092
11093   remote_buffer_add_string (&p, &left, "vFile:pread:");
11094
11095   remote_buffer_add_int (&p, &left, fd);
11096   remote_buffer_add_string (&p, &left, ",");
11097
11098   remote_buffer_add_int (&p, &left, len);
11099   remote_buffer_add_string (&p, &left, ",");
11100
11101   remote_buffer_add_int (&p, &left, offset);
11102
11103   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11104                                     remote_errno, &attachment,
11105                                     &attachment_len);
11106
11107   if (ret < 0)
11108     return ret;
11109
11110   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11111                                     read_buf, len);
11112   if (read_len != ret)
11113     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11114
11115   return ret;
11116 }
11117
11118 /* Serve pread from the readahead cache.  Returns number of bytes
11119    read, or 0 if the request can't be served from the cache.  */
11120
11121 static int
11122 remote_hostio_pread_from_cache (struct remote_state *rs,
11123                                 int fd, gdb_byte *read_buf, size_t len,
11124                                 ULONGEST offset)
11125 {
11126   struct readahead_cache *cache = &rs->readahead_cache;
11127
11128   if (cache->fd == fd
11129       && cache->offset <= offset
11130       && offset < cache->offset + cache->bufsize)
11131     {
11132       ULONGEST max = cache->offset + cache->bufsize;
11133
11134       if (offset + len > max)
11135         len = max - offset;
11136
11137       memcpy (read_buf, cache->buf + offset - cache->offset, len);
11138       return len;
11139     }
11140
11141   return 0;
11142 }
11143
11144 /* Implementation of to_fileio_pread.  */
11145
11146 static int
11147 remote_hostio_pread (struct target_ops *self,
11148                      int fd, gdb_byte *read_buf, int len,
11149                      ULONGEST offset, int *remote_errno)
11150 {
11151   int ret;
11152   struct remote_state *rs = get_remote_state ();
11153   struct readahead_cache *cache = &rs->readahead_cache;
11154
11155   ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11156   if (ret > 0)
11157     {
11158       cache->hit_count++;
11159
11160       if (remote_debug)
11161         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11162                             pulongest (cache->hit_count));
11163       return ret;
11164     }
11165
11166   cache->miss_count++;
11167   if (remote_debug)
11168     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11169                         pulongest (cache->miss_count));
11170
11171   cache->fd = fd;
11172   cache->offset = offset;
11173   cache->bufsize = get_remote_packet_size ();
11174   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11175
11176   ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11177                                    cache->offset, remote_errno);
11178   if (ret <= 0)
11179     {
11180       readahead_cache_invalidate_fd (fd);
11181       return ret;
11182     }
11183
11184   cache->bufsize = ret;
11185   return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11186 }
11187
11188 /* Implementation of to_fileio_close.  */
11189
11190 static int
11191 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11192 {
11193   struct remote_state *rs = get_remote_state ();
11194   char *p = rs->buf;
11195   int left = get_remote_packet_size () - 1;
11196
11197   readahead_cache_invalidate_fd (fd);
11198
11199   remote_buffer_add_string (&p, &left, "vFile:close:");
11200
11201   remote_buffer_add_int (&p, &left, fd);
11202
11203   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11204                                      remote_errno, NULL, NULL);
11205 }
11206
11207 /* Implementation of to_fileio_unlink.  */
11208
11209 static int
11210 remote_hostio_unlink (struct target_ops *self,
11211                       struct inferior *inf, const char *filename,
11212                       int *remote_errno)
11213 {
11214   struct remote_state *rs = get_remote_state ();
11215   char *p = rs->buf;
11216   int left = get_remote_packet_size () - 1;
11217
11218   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11219     return -1;
11220
11221   remote_buffer_add_string (&p, &left, "vFile:unlink:");
11222
11223   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11224                            strlen (filename));
11225
11226   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11227                                      remote_errno, NULL, NULL);
11228 }
11229
11230 /* Implementation of to_fileio_readlink.  */
11231
11232 static char *
11233 remote_hostio_readlink (struct target_ops *self,
11234                         struct inferior *inf, const char *filename,
11235                         int *remote_errno)
11236 {
11237   struct remote_state *rs = get_remote_state ();
11238   char *p = rs->buf;
11239   char *attachment;
11240   int left = get_remote_packet_size ();
11241   int len, attachment_len;
11242   int read_len;
11243   char *ret;
11244
11245   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11246     return NULL;
11247
11248   remote_buffer_add_string (&p, &left, "vFile:readlink:");
11249
11250   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11251                            strlen (filename));
11252
11253   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11254                                     remote_errno, &attachment,
11255                                     &attachment_len);
11256
11257   if (len < 0)
11258     return NULL;
11259
11260   ret = (char *) xmalloc (len + 1);
11261
11262   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11263                                     (gdb_byte *) ret, len);
11264   if (read_len != len)
11265     error (_("Readlink returned %d, but %d bytes."), len, read_len);
11266
11267   ret[len] = '\0';
11268   return ret;
11269 }
11270
11271 /* Implementation of to_fileio_fstat.  */
11272
11273 static int
11274 remote_hostio_fstat (struct target_ops *self,
11275                      int fd, struct stat *st,
11276                      int *remote_errno)
11277 {
11278   struct remote_state *rs = get_remote_state ();
11279   char *p = rs->buf;
11280   int left = get_remote_packet_size ();
11281   int attachment_len, ret;
11282   char *attachment;
11283   struct fio_stat fst;
11284   int read_len;
11285
11286   remote_buffer_add_string (&p, &left, "vFile:fstat:");
11287
11288   remote_buffer_add_int (&p, &left, fd);
11289
11290   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11291                                     remote_errno, &attachment,
11292                                     &attachment_len);
11293   if (ret < 0)
11294     {
11295       if (*remote_errno != FILEIO_ENOSYS)
11296         return ret;
11297
11298       /* Strictly we should return -1, ENOSYS here, but when
11299          "set sysroot remote:" was implemented in August 2008
11300          BFD's need for a stat function was sidestepped with
11301          this hack.  This was not remedied until March 2015
11302          so we retain the previous behavior to avoid breaking
11303          compatibility.
11304
11305          Note that the memset is a March 2015 addition; older
11306          GDBs set st_size *and nothing else* so the structure
11307          would have garbage in all other fields.  This might
11308          break something but retaining the previous behavior
11309          here would be just too wrong.  */
11310
11311       memset (st, 0, sizeof (struct stat));
11312       st->st_size = INT_MAX;
11313       return 0;
11314     }
11315
11316   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11317                                     (gdb_byte *) &fst, sizeof (fst));
11318
11319   if (read_len != ret)
11320     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11321
11322   if (read_len != sizeof (fst))
11323     error (_("vFile:fstat returned %d bytes, but expecting %d."),
11324            read_len, (int) sizeof (fst));
11325
11326   remote_fileio_to_host_stat (&fst, st);
11327
11328   return 0;
11329 }
11330
11331 /* Implementation of to_filesystem_is_local.  */
11332
11333 static int
11334 remote_filesystem_is_local (struct target_ops *self)
11335 {
11336   /* Valgrind GDB presents itself as a remote target but works
11337      on the local filesystem: it does not implement remote get
11338      and users are not expected to set a sysroot.  To handle
11339      this case we treat the remote filesystem as local if the
11340      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11341      does not support vFile:open.  */
11342   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11343     {
11344       enum packet_support ps = packet_support (PACKET_vFile_open);
11345
11346       if (ps == PACKET_SUPPORT_UNKNOWN)
11347         {
11348           int fd, remote_errno;
11349
11350           /* Try opening a file to probe support.  The supplied
11351              filename is irrelevant, we only care about whether
11352              the stub recognizes the packet or not.  */
11353           fd = remote_hostio_open (self, NULL, "just probing",
11354                                    FILEIO_O_RDONLY, 0700, 0,
11355                                    &remote_errno);
11356
11357           if (fd >= 0)
11358             remote_hostio_close (self, fd, &remote_errno);
11359
11360           ps = packet_support (PACKET_vFile_open);
11361         }
11362
11363       if (ps == PACKET_DISABLE)
11364         {
11365           static int warning_issued = 0;
11366
11367           if (!warning_issued)
11368             {
11369               warning (_("remote target does not support file"
11370                          " transfer, attempting to access files"
11371                          " from local filesystem."));
11372               warning_issued = 1;
11373             }
11374
11375           return 1;
11376         }
11377     }
11378
11379   return 0;
11380 }
11381
11382 static int
11383 remote_fileio_errno_to_host (int errnum)
11384 {
11385   switch (errnum)
11386     {
11387       case FILEIO_EPERM:
11388         return EPERM;
11389       case FILEIO_ENOENT:
11390         return ENOENT;
11391       case FILEIO_EINTR:
11392         return EINTR;
11393       case FILEIO_EIO:
11394         return EIO;
11395       case FILEIO_EBADF:
11396         return EBADF;
11397       case FILEIO_EACCES:
11398         return EACCES;
11399       case FILEIO_EFAULT:
11400         return EFAULT;
11401       case FILEIO_EBUSY:
11402         return EBUSY;
11403       case FILEIO_EEXIST:
11404         return EEXIST;
11405       case FILEIO_ENODEV:
11406         return ENODEV;
11407       case FILEIO_ENOTDIR:
11408         return ENOTDIR;
11409       case FILEIO_EISDIR:
11410         return EISDIR;
11411       case FILEIO_EINVAL:
11412         return EINVAL;
11413       case FILEIO_ENFILE:
11414         return ENFILE;
11415       case FILEIO_EMFILE:
11416         return EMFILE;
11417       case FILEIO_EFBIG:
11418         return EFBIG;
11419       case FILEIO_ENOSPC:
11420         return ENOSPC;
11421       case FILEIO_ESPIPE:
11422         return ESPIPE;
11423       case FILEIO_EROFS:
11424         return EROFS;
11425       case FILEIO_ENOSYS:
11426         return ENOSYS;
11427       case FILEIO_ENAMETOOLONG:
11428         return ENAMETOOLONG;
11429     }
11430   return -1;
11431 }
11432
11433 static char *
11434 remote_hostio_error (int errnum)
11435 {
11436   int host_error = remote_fileio_errno_to_host (errnum);
11437
11438   if (host_error == -1)
11439     error (_("Unknown remote I/O error %d"), errnum);
11440   else
11441     error (_("Remote I/O error: %s"), safe_strerror (host_error));
11442 }
11443
11444 static void
11445 remote_hostio_close_cleanup (void *opaque)
11446 {
11447   int fd = *(int *) opaque;
11448   int remote_errno;
11449
11450   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11451 }
11452
11453 void
11454 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11455 {
11456   struct cleanup *back_to, *close_cleanup;
11457   int retcode, fd, remote_errno, bytes, io_size;
11458   FILE *file;
11459   gdb_byte *buffer;
11460   int bytes_in_buffer;
11461   int saw_eof;
11462   ULONGEST offset;
11463   struct remote_state *rs = get_remote_state ();
11464
11465   if (!rs->remote_desc)
11466     error (_("command can only be used with remote target"));
11467
11468   file = gdb_fopen_cloexec (local_file, "rb");
11469   if (file == NULL)
11470     perror_with_name (local_file);
11471   back_to = make_cleanup_fclose (file);
11472
11473   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11474                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11475                                          | FILEIO_O_TRUNC),
11476                            0700, 0, &remote_errno);
11477   if (fd == -1)
11478     remote_hostio_error (remote_errno);
11479
11480   /* Send up to this many bytes at once.  They won't all fit in the
11481      remote packet limit, so we'll transfer slightly fewer.  */
11482   io_size = get_remote_packet_size ();
11483   buffer = (gdb_byte *) xmalloc (io_size);
11484   make_cleanup (xfree, buffer);
11485
11486   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11487
11488   bytes_in_buffer = 0;
11489   saw_eof = 0;
11490   offset = 0;
11491   while (bytes_in_buffer || !saw_eof)
11492     {
11493       if (!saw_eof)
11494         {
11495           bytes = fread (buffer + bytes_in_buffer, 1,
11496                          io_size - bytes_in_buffer,
11497                          file);
11498           if (bytes == 0)
11499             {
11500               if (ferror (file))
11501                 error (_("Error reading %s."), local_file);
11502               else
11503                 {
11504                   /* EOF.  Unless there is something still in the
11505                      buffer from the last iteration, we are done.  */
11506                   saw_eof = 1;
11507                   if (bytes_in_buffer == 0)
11508                     break;
11509                 }
11510             }
11511         }
11512       else
11513         bytes = 0;
11514
11515       bytes += bytes_in_buffer;
11516       bytes_in_buffer = 0;
11517
11518       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11519                                       fd, buffer, bytes,
11520                                       offset, &remote_errno);
11521
11522       if (retcode < 0)
11523         remote_hostio_error (remote_errno);
11524       else if (retcode == 0)
11525         error (_("Remote write of %d bytes returned 0!"), bytes);
11526       else if (retcode < bytes)
11527         {
11528           /* Short write.  Save the rest of the read data for the next
11529              write.  */
11530           bytes_in_buffer = bytes - retcode;
11531           memmove (buffer, buffer + retcode, bytes_in_buffer);
11532         }
11533
11534       offset += retcode;
11535     }
11536
11537   discard_cleanups (close_cleanup);
11538   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11539     remote_hostio_error (remote_errno);
11540
11541   if (from_tty)
11542     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11543   do_cleanups (back_to);
11544 }
11545
11546 void
11547 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11548 {
11549   struct cleanup *back_to, *close_cleanup;
11550   int fd, remote_errno, bytes, io_size;
11551   FILE *file;
11552   gdb_byte *buffer;
11553   ULONGEST offset;
11554   struct remote_state *rs = get_remote_state ();
11555
11556   if (!rs->remote_desc)
11557     error (_("command can only be used with remote target"));
11558
11559   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11560                            remote_file, FILEIO_O_RDONLY, 0, 0,
11561                            &remote_errno);
11562   if (fd == -1)
11563     remote_hostio_error (remote_errno);
11564
11565   file = gdb_fopen_cloexec (local_file, "wb");
11566   if (file == NULL)
11567     perror_with_name (local_file);
11568   back_to = make_cleanup_fclose (file);
11569
11570   /* Send up to this many bytes at once.  They won't all fit in the
11571      remote packet limit, so we'll transfer slightly fewer.  */
11572   io_size = get_remote_packet_size ();
11573   buffer = (gdb_byte *) xmalloc (io_size);
11574   make_cleanup (xfree, buffer);
11575
11576   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11577
11578   offset = 0;
11579   while (1)
11580     {
11581       bytes = remote_hostio_pread (find_target_at (process_stratum),
11582                                    fd, buffer, io_size, offset, &remote_errno);
11583       if (bytes == 0)
11584         /* Success, but no bytes, means end-of-file.  */
11585         break;
11586       if (bytes == -1)
11587         remote_hostio_error (remote_errno);
11588
11589       offset += bytes;
11590
11591       bytes = fwrite (buffer, 1, bytes, file);
11592       if (bytes == 0)
11593         perror_with_name (local_file);
11594     }
11595
11596   discard_cleanups (close_cleanup);
11597   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11598     remote_hostio_error (remote_errno);
11599
11600   if (from_tty)
11601     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11602   do_cleanups (back_to);
11603 }
11604
11605 void
11606 remote_file_delete (const char *remote_file, int from_tty)
11607 {
11608   int retcode, remote_errno;
11609   struct remote_state *rs = get_remote_state ();
11610
11611   if (!rs->remote_desc)
11612     error (_("command can only be used with remote target"));
11613
11614   retcode = remote_hostio_unlink (find_target_at (process_stratum),
11615                                   NULL, remote_file, &remote_errno);
11616   if (retcode == -1)
11617     remote_hostio_error (remote_errno);
11618
11619   if (from_tty)
11620     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11621 }
11622
11623 static void
11624 remote_put_command (char *args, int from_tty)
11625 {
11626   struct cleanup *back_to;
11627   char **argv;
11628
11629   if (args == NULL)
11630     error_no_arg (_("file to put"));
11631
11632   argv = gdb_buildargv (args);
11633   back_to = make_cleanup_freeargv (argv);
11634   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11635     error (_("Invalid parameters to remote put"));
11636
11637   remote_file_put (argv[0], argv[1], from_tty);
11638
11639   do_cleanups (back_to);
11640 }
11641
11642 static void
11643 remote_get_command (char *args, int from_tty)
11644 {
11645   struct cleanup *back_to;
11646   char **argv;
11647
11648   if (args == NULL)
11649     error_no_arg (_("file to get"));
11650
11651   argv = gdb_buildargv (args);
11652   back_to = make_cleanup_freeargv (argv);
11653   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11654     error (_("Invalid parameters to remote get"));
11655
11656   remote_file_get (argv[0], argv[1], from_tty);
11657
11658   do_cleanups (back_to);
11659 }
11660
11661 static void
11662 remote_delete_command (char *args, int from_tty)
11663 {
11664   struct cleanup *back_to;
11665   char **argv;
11666
11667   if (args == NULL)
11668     error_no_arg (_("file to delete"));
11669
11670   argv = gdb_buildargv (args);
11671   back_to = make_cleanup_freeargv (argv);
11672   if (argv[0] == NULL || argv[1] != NULL)
11673     error (_("Invalid parameters to remote delete"));
11674
11675   remote_file_delete (argv[0], from_tty);
11676
11677   do_cleanups (back_to);
11678 }
11679
11680 static void
11681 remote_command (char *args, int from_tty)
11682 {
11683   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11684 }
11685
11686 static int
11687 remote_can_execute_reverse (struct target_ops *self)
11688 {
11689   if (packet_support (PACKET_bs) == PACKET_ENABLE
11690       || packet_support (PACKET_bc) == PACKET_ENABLE)
11691     return 1;
11692   else
11693     return 0;
11694 }
11695
11696 static int
11697 remote_supports_non_stop (struct target_ops *self)
11698 {
11699   return 1;
11700 }
11701
11702 static int
11703 remote_supports_disable_randomization (struct target_ops *self)
11704 {
11705   /* Only supported in extended mode.  */
11706   return 0;
11707 }
11708
11709 static int
11710 remote_supports_multi_process (struct target_ops *self)
11711 {
11712   struct remote_state *rs = get_remote_state ();
11713
11714   return remote_multi_process_p (rs);
11715 }
11716
11717 static int
11718 remote_supports_cond_tracepoints (void)
11719 {
11720   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11721 }
11722
11723 static int
11724 remote_supports_cond_breakpoints (struct target_ops *self)
11725 {
11726   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11727 }
11728
11729 static int
11730 remote_supports_fast_tracepoints (void)
11731 {
11732   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11733 }
11734
11735 static int
11736 remote_supports_static_tracepoints (void)
11737 {
11738   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11739 }
11740
11741 static int
11742 remote_supports_install_in_trace (void)
11743 {
11744   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11745 }
11746
11747 static int
11748 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11749 {
11750   return (packet_support (PACKET_EnableDisableTracepoints_feature)
11751           == PACKET_ENABLE);
11752 }
11753
11754 static int
11755 remote_supports_string_tracing (struct target_ops *self)
11756 {
11757   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11758 }
11759
11760 static int
11761 remote_can_run_breakpoint_commands (struct target_ops *self)
11762 {
11763   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11764 }
11765
11766 static void
11767 remote_trace_init (struct target_ops *self)
11768 {
11769   putpkt ("QTinit");
11770   remote_get_noisy_reply (&target_buf, &target_buf_size);
11771   if (strcmp (target_buf, "OK") != 0)
11772     error (_("Target does not support this command."));
11773 }
11774
11775 static void free_actions_list (char **actions_list);
11776 static void free_actions_list_cleanup_wrapper (void *);
11777 static void
11778 free_actions_list_cleanup_wrapper (void *al)
11779 {
11780   free_actions_list ((char **) al);
11781 }
11782
11783 static void
11784 free_actions_list (char **actions_list)
11785 {
11786   int ndx;
11787
11788   if (actions_list == 0)
11789     return;
11790
11791   for (ndx = 0; actions_list[ndx]; ndx++)
11792     xfree (actions_list[ndx]);
11793
11794   xfree (actions_list);
11795 }
11796
11797 /* Recursive routine to walk through command list including loops, and
11798    download packets for each command.  */
11799
11800 static void
11801 remote_download_command_source (int num, ULONGEST addr,
11802                                 struct command_line *cmds)
11803 {
11804   struct remote_state *rs = get_remote_state ();
11805   struct command_line *cmd;
11806
11807   for (cmd = cmds; cmd; cmd = cmd->next)
11808     {
11809       QUIT;     /* Allow user to bail out with ^C.  */
11810       strcpy (rs->buf, "QTDPsrc:");
11811       encode_source_string (num, addr, "cmd", cmd->line,
11812                             rs->buf + strlen (rs->buf),
11813                             rs->buf_size - strlen (rs->buf));
11814       putpkt (rs->buf);
11815       remote_get_noisy_reply (&target_buf, &target_buf_size);
11816       if (strcmp (target_buf, "OK"))
11817         warning (_("Target does not support source download."));
11818
11819       if (cmd->control_type == while_control
11820           || cmd->control_type == while_stepping_control)
11821         {
11822           remote_download_command_source (num, addr, *cmd->body_list);
11823
11824           QUIT; /* Allow user to bail out with ^C.  */
11825           strcpy (rs->buf, "QTDPsrc:");
11826           encode_source_string (num, addr, "cmd", "end",
11827                                 rs->buf + strlen (rs->buf),
11828                                 rs->buf_size - strlen (rs->buf));
11829           putpkt (rs->buf);
11830           remote_get_noisy_reply (&target_buf, &target_buf_size);
11831           if (strcmp (target_buf, "OK"))
11832             warning (_("Target does not support source download."));
11833         }
11834     }
11835 }
11836
11837 static void
11838 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11839 {
11840 #define BUF_SIZE 2048
11841
11842   CORE_ADDR tpaddr;
11843   char addrbuf[40];
11844   char buf[BUF_SIZE];
11845   char **tdp_actions;
11846   char **stepping_actions;
11847   int ndx;
11848   struct cleanup *old_chain = NULL;
11849   struct agent_expr *aexpr;
11850   struct cleanup *aexpr_chain = NULL;
11851   char *pkt;
11852   struct breakpoint *b = loc->owner;
11853   struct tracepoint *t = (struct tracepoint *) b;
11854
11855   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11856   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11857                             tdp_actions);
11858   (void) make_cleanup (free_actions_list_cleanup_wrapper,
11859                        stepping_actions);
11860
11861   tpaddr = loc->address;
11862   sprintf_vma (addrbuf, tpaddr);
11863   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11864              addrbuf, /* address */
11865              (b->enable_state == bp_enabled ? 'E' : 'D'),
11866              t->step_count, t->pass_count);
11867   /* Fast tracepoints are mostly handled by the target, but we can
11868      tell the target how big of an instruction block should be moved
11869      around.  */
11870   if (b->type == bp_fast_tracepoint)
11871     {
11872       /* Only test for support at download time; we may not know
11873          target capabilities at definition time.  */
11874       if (remote_supports_fast_tracepoints ())
11875         {
11876           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11877                                                 NULL))
11878             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11879                        gdb_insn_length (loc->gdbarch, tpaddr));
11880           else
11881             /* If it passed validation at definition but fails now,
11882                something is very wrong.  */
11883             internal_error (__FILE__, __LINE__,
11884                             _("Fast tracepoint not "
11885                               "valid during download"));
11886         }
11887       else
11888         /* Fast tracepoints are functionally identical to regular
11889            tracepoints, so don't take lack of support as a reason to
11890            give up on the trace run.  */
11891         warning (_("Target does not support fast tracepoints, "
11892                    "downloading %d as regular tracepoint"), b->number);
11893     }
11894   else if (b->type == bp_static_tracepoint)
11895     {
11896       /* Only test for support at download time; we may not know
11897          target capabilities at definition time.  */
11898       if (remote_supports_static_tracepoints ())
11899         {
11900           struct static_tracepoint_marker marker;
11901
11902           if (target_static_tracepoint_marker_at (tpaddr, &marker))
11903             strcat (buf, ":S");
11904           else
11905             error (_("Static tracepoint not valid during download"));
11906         }
11907       else
11908         /* Fast tracepoints are functionally identical to regular
11909            tracepoints, so don't take lack of support as a reason
11910            to give up on the trace run.  */
11911         error (_("Target does not support static tracepoints"));
11912     }
11913   /* If the tracepoint has a conditional, make it into an agent
11914      expression and append to the definition.  */
11915   if (loc->cond)
11916     {
11917       /* Only test support at download time, we may not know target
11918          capabilities at definition time.  */
11919       if (remote_supports_cond_tracepoints ())
11920         {
11921           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11922           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11923           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11924                      aexpr->len);
11925           pkt = buf + strlen (buf);
11926           for (ndx = 0; ndx < aexpr->len; ++ndx)
11927             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11928           *pkt = '\0';
11929           do_cleanups (aexpr_chain);
11930         }
11931       else
11932         warning (_("Target does not support conditional tracepoints, "
11933                    "ignoring tp %d cond"), b->number);
11934     }
11935
11936   if (b->commands || *default_collect)
11937     strcat (buf, "-");
11938   putpkt (buf);
11939   remote_get_noisy_reply (&target_buf, &target_buf_size);
11940   if (strcmp (target_buf, "OK"))
11941     error (_("Target does not support tracepoints."));
11942
11943   /* do_single_steps (t); */
11944   if (tdp_actions)
11945     {
11946       for (ndx = 0; tdp_actions[ndx]; ndx++)
11947         {
11948           QUIT; /* Allow user to bail out with ^C.  */
11949           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11950                      b->number, addrbuf, /* address */
11951                      tdp_actions[ndx],
11952                      ((tdp_actions[ndx + 1] || stepping_actions)
11953                       ? '-' : 0));
11954           putpkt (buf);
11955           remote_get_noisy_reply (&target_buf,
11956                                   &target_buf_size);
11957           if (strcmp (target_buf, "OK"))
11958             error (_("Error on target while setting tracepoints."));
11959         }
11960     }
11961   if (stepping_actions)
11962     {
11963       for (ndx = 0; stepping_actions[ndx]; ndx++)
11964         {
11965           QUIT; /* Allow user to bail out with ^C.  */
11966           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11967                      b->number, addrbuf, /* address */
11968                      ((ndx == 0) ? "S" : ""),
11969                      stepping_actions[ndx],
11970                      (stepping_actions[ndx + 1] ? "-" : ""));
11971           putpkt (buf);
11972           remote_get_noisy_reply (&target_buf,
11973                                   &target_buf_size);
11974           if (strcmp (target_buf, "OK"))
11975             error (_("Error on target while setting tracepoints."));
11976         }
11977     }
11978
11979   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11980     {
11981       if (b->location != NULL)
11982         {
11983           strcpy (buf, "QTDPsrc:");
11984           encode_source_string (b->number, loc->address, "at",
11985                                 event_location_to_string (b->location),
11986                                 buf + strlen (buf), 2048 - strlen (buf));
11987           putpkt (buf);
11988           remote_get_noisy_reply (&target_buf, &target_buf_size);
11989           if (strcmp (target_buf, "OK"))
11990             warning (_("Target does not support source download."));
11991         }
11992       if (b->cond_string)
11993         {
11994           strcpy (buf, "QTDPsrc:");
11995           encode_source_string (b->number, loc->address,
11996                                 "cond", b->cond_string, buf + strlen (buf),
11997                                 2048 - strlen (buf));
11998           putpkt (buf);
11999           remote_get_noisy_reply (&target_buf, &target_buf_size);
12000           if (strcmp (target_buf, "OK"))
12001             warning (_("Target does not support source download."));
12002         }
12003       remote_download_command_source (b->number, loc->address,
12004                                       breakpoint_commands (b));
12005     }
12006
12007   do_cleanups (old_chain);
12008 }
12009
12010 static int
12011 remote_can_download_tracepoint (struct target_ops *self)
12012 {
12013   struct remote_state *rs = get_remote_state ();
12014   struct trace_status *ts;
12015   int status;
12016
12017   /* Don't try to install tracepoints until we've relocated our
12018      symbols, and fetched and merged the target's tracepoint list with
12019      ours.  */
12020   if (rs->starting_up)
12021     return 0;
12022
12023   ts = current_trace_status ();
12024   status = remote_get_trace_status (self, ts);
12025
12026   if (status == -1 || !ts->running_known || !ts->running)
12027     return 0;
12028
12029   /* If we are in a tracing experiment, but remote stub doesn't support
12030      installing tracepoint in trace, we have to return.  */
12031   if (!remote_supports_install_in_trace ())
12032     return 0;
12033
12034   return 1;
12035 }
12036
12037
12038 static void
12039 remote_download_trace_state_variable (struct target_ops *self,
12040                                       struct trace_state_variable *tsv)
12041 {
12042   struct remote_state *rs = get_remote_state ();
12043   char *p;
12044
12045   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12046              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12047              tsv->builtin);
12048   p = rs->buf + strlen (rs->buf);
12049   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12050     error (_("Trace state variable name too long for tsv definition packet"));
12051   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12052   *p++ = '\0';
12053   putpkt (rs->buf);
12054   remote_get_noisy_reply (&target_buf, &target_buf_size);
12055   if (*target_buf == '\0')
12056     error (_("Target does not support this command."));
12057   if (strcmp (target_buf, "OK") != 0)
12058     error (_("Error on target while downloading trace state variable."));
12059 }
12060
12061 static void
12062 remote_enable_tracepoint (struct target_ops *self,
12063                           struct bp_location *location)
12064 {
12065   struct remote_state *rs = get_remote_state ();
12066   char addr_buf[40];
12067
12068   sprintf_vma (addr_buf, location->address);
12069   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12070              location->owner->number, addr_buf);
12071   putpkt (rs->buf);
12072   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12073   if (*rs->buf == '\0')
12074     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12075   if (strcmp (rs->buf, "OK") != 0)
12076     error (_("Error on target while enabling tracepoint."));
12077 }
12078
12079 static void
12080 remote_disable_tracepoint (struct target_ops *self,
12081                            struct bp_location *location)
12082 {
12083   struct remote_state *rs = get_remote_state ();
12084   char addr_buf[40];
12085
12086   sprintf_vma (addr_buf, location->address);
12087   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12088              location->owner->number, addr_buf);
12089   putpkt (rs->buf);
12090   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12091   if (*rs->buf == '\0')
12092     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12093   if (strcmp (rs->buf, "OK") != 0)
12094     error (_("Error on target while disabling tracepoint."));
12095 }
12096
12097 static void
12098 remote_trace_set_readonly_regions (struct target_ops *self)
12099 {
12100   asection *s;
12101   bfd *abfd = NULL;
12102   bfd_size_type size;
12103   bfd_vma vma;
12104   int anysecs = 0;
12105   int offset = 0;
12106
12107   if (!exec_bfd)
12108     return;                     /* No information to give.  */
12109
12110   strcpy (target_buf, "QTro");
12111   offset = strlen (target_buf);
12112   for (s = exec_bfd->sections; s; s = s->next)
12113     {
12114       char tmp1[40], tmp2[40];
12115       int sec_length;
12116
12117       if ((s->flags & SEC_LOAD) == 0 ||
12118       /*  (s->flags & SEC_CODE) == 0 || */
12119           (s->flags & SEC_READONLY) == 0)
12120         continue;
12121
12122       anysecs = 1;
12123       vma = bfd_get_section_vma (abfd, s);
12124       size = bfd_get_section_size (s);
12125       sprintf_vma (tmp1, vma);
12126       sprintf_vma (tmp2, vma + size);
12127       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12128       if (offset + sec_length + 1 > target_buf_size)
12129         {
12130           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12131             warning (_("\
12132 Too many sections for read-only sections definition packet."));
12133           break;
12134         }
12135       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12136                  tmp1, tmp2);
12137       offset += sec_length;
12138     }
12139   if (anysecs)
12140     {
12141       putpkt (target_buf);
12142       getpkt (&target_buf, &target_buf_size, 0);
12143     }
12144 }
12145
12146 static void
12147 remote_trace_start (struct target_ops *self)
12148 {
12149   putpkt ("QTStart");
12150   remote_get_noisy_reply (&target_buf, &target_buf_size);
12151   if (*target_buf == '\0')
12152     error (_("Target does not support this command."));
12153   if (strcmp (target_buf, "OK") != 0)
12154     error (_("Bogus reply from target: %s"), target_buf);
12155 }
12156
12157 static int
12158 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12159 {
12160   /* Initialize it just to avoid a GCC false warning.  */
12161   char *p = NULL;
12162   /* FIXME we need to get register block size some other way.  */
12163   extern int trace_regblock_size;
12164   enum packet_result result;
12165
12166   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12167     return -1;
12168
12169   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12170
12171   putpkt ("qTStatus");
12172
12173   TRY
12174     {
12175       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12176     }
12177   CATCH (ex, RETURN_MASK_ERROR)
12178     {
12179       if (ex.error != TARGET_CLOSE_ERROR)
12180         {
12181           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12182           return -1;
12183         }
12184       throw_exception (ex);
12185     }
12186   END_CATCH
12187
12188   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12189
12190   /* If the remote target doesn't do tracing, flag it.  */
12191   if (result == PACKET_UNKNOWN)
12192     return -1;
12193
12194   /* We're working with a live target.  */
12195   ts->filename = NULL;
12196
12197   if (*p++ != 'T')
12198     error (_("Bogus trace status reply from target: %s"), target_buf);
12199
12200   /* Function 'parse_trace_status' sets default value of each field of
12201      'ts' at first, so we don't have to do it here.  */
12202   parse_trace_status (p, ts);
12203
12204   return ts->running;
12205 }
12206
12207 static void
12208 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12209                               struct uploaded_tp *utp)
12210 {
12211   struct remote_state *rs = get_remote_state ();
12212   char *reply;
12213   struct bp_location *loc;
12214   struct tracepoint *tp = (struct tracepoint *) bp;
12215   size_t size = get_remote_packet_size ();
12216
12217   if (tp)
12218     {
12219       tp->base.hit_count = 0;
12220       tp->traceframe_usage = 0;
12221       for (loc = tp->base.loc; loc; loc = loc->next)
12222         {
12223           /* If the tracepoint was never downloaded, don't go asking for
12224              any status.  */
12225           if (tp->number_on_target == 0)
12226             continue;
12227           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12228                      phex_nz (loc->address, 0));
12229           putpkt (rs->buf);
12230           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12231           if (reply && *reply)
12232             {
12233               if (*reply == 'V')
12234                 parse_tracepoint_status (reply + 1, bp, utp);
12235             }
12236         }
12237     }
12238   else if (utp)
12239     {
12240       utp->hit_count = 0;
12241       utp->traceframe_usage = 0;
12242       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12243                  phex_nz (utp->addr, 0));
12244       putpkt (rs->buf);
12245       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12246       if (reply && *reply)
12247         {
12248           if (*reply == 'V')
12249             parse_tracepoint_status (reply + 1, bp, utp);
12250         }
12251     }
12252 }
12253
12254 static void
12255 remote_trace_stop (struct target_ops *self)
12256 {
12257   putpkt ("QTStop");
12258   remote_get_noisy_reply (&target_buf, &target_buf_size);
12259   if (*target_buf == '\0')
12260     error (_("Target does not support this command."));
12261   if (strcmp (target_buf, "OK") != 0)
12262     error (_("Bogus reply from target: %s"), target_buf);
12263 }
12264
12265 static int
12266 remote_trace_find (struct target_ops *self,
12267                    enum trace_find_type type, int num,
12268                    CORE_ADDR addr1, CORE_ADDR addr2,
12269                    int *tpp)
12270 {
12271   struct remote_state *rs = get_remote_state ();
12272   char *endbuf = rs->buf + get_remote_packet_size ();
12273   char *p, *reply;
12274   int target_frameno = -1, target_tracept = -1;
12275
12276   /* Lookups other than by absolute frame number depend on the current
12277      trace selected, so make sure it is correct on the remote end
12278      first.  */
12279   if (type != tfind_number)
12280     set_remote_traceframe ();
12281
12282   p = rs->buf;
12283   strcpy (p, "QTFrame:");
12284   p = strchr (p, '\0');
12285   switch (type)
12286     {
12287     case tfind_number:
12288       xsnprintf (p, endbuf - p, "%x", num);
12289       break;
12290     case tfind_pc:
12291       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12292       break;
12293     case tfind_tp:
12294       xsnprintf (p, endbuf - p, "tdp:%x", num);
12295       break;
12296     case tfind_range:
12297       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12298                  phex_nz (addr2, 0));
12299       break;
12300     case tfind_outside:
12301       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12302                  phex_nz (addr2, 0));
12303       break;
12304     default:
12305       error (_("Unknown trace find type %d"), type);
12306     }
12307
12308   putpkt (rs->buf);
12309   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12310   if (*reply == '\0')
12311     error (_("Target does not support this command."));
12312
12313   while (reply && *reply)
12314     switch (*reply)
12315       {
12316       case 'F':
12317         p = ++reply;
12318         target_frameno = (int) strtol (p, &reply, 16);
12319         if (reply == p)
12320           error (_("Unable to parse trace frame number"));
12321         /* Don't update our remote traceframe number cache on failure
12322            to select a remote traceframe.  */
12323         if (target_frameno == -1)
12324           return -1;
12325         break;
12326       case 'T':
12327         p = ++reply;
12328         target_tracept = (int) strtol (p, &reply, 16);
12329         if (reply == p)
12330           error (_("Unable to parse tracepoint number"));
12331         break;
12332       case 'O':         /* "OK"? */
12333         if (reply[1] == 'K' && reply[2] == '\0')
12334           reply += 2;
12335         else
12336           error (_("Bogus reply from target: %s"), reply);
12337         break;
12338       default:
12339         error (_("Bogus reply from target: %s"), reply);
12340       }
12341   if (tpp)
12342     *tpp = target_tracept;
12343
12344   rs->remote_traceframe_number = target_frameno;
12345   return target_frameno;
12346 }
12347
12348 static int
12349 remote_get_trace_state_variable_value (struct target_ops *self,
12350                                        int tsvnum, LONGEST *val)
12351 {
12352   struct remote_state *rs = get_remote_state ();
12353   char *reply;
12354   ULONGEST uval;
12355
12356   set_remote_traceframe ();
12357
12358   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12359   putpkt (rs->buf);
12360   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12361   if (reply && *reply)
12362     {
12363       if (*reply == 'V')
12364         {
12365           unpack_varlen_hex (reply + 1, &uval);
12366           *val = (LONGEST) uval;
12367           return 1;
12368         }
12369     }
12370   return 0;
12371 }
12372
12373 static int
12374 remote_save_trace_data (struct target_ops *self, const char *filename)
12375 {
12376   struct remote_state *rs = get_remote_state ();
12377   char *p, *reply;
12378
12379   p = rs->buf;
12380   strcpy (p, "QTSave:");
12381   p += strlen (p);
12382   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12383     error (_("Remote file name too long for trace save packet"));
12384   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12385   *p++ = '\0';
12386   putpkt (rs->buf);
12387   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12388   if (*reply == '\0')
12389     error (_("Target does not support this command."));
12390   if (strcmp (reply, "OK") != 0)
12391     error (_("Bogus reply from target: %s"), reply);
12392   return 0;
12393 }
12394
12395 /* This is basically a memory transfer, but needs to be its own packet
12396    because we don't know how the target actually organizes its trace
12397    memory, plus we want to be able to ask for as much as possible, but
12398    not be unhappy if we don't get as much as we ask for.  */
12399
12400 static LONGEST
12401 remote_get_raw_trace_data (struct target_ops *self,
12402                            gdb_byte *buf, ULONGEST offset, LONGEST len)
12403 {
12404   struct remote_state *rs = get_remote_state ();
12405   char *reply;
12406   char *p;
12407   int rslt;
12408
12409   p = rs->buf;
12410   strcpy (p, "qTBuffer:");
12411   p += strlen (p);
12412   p += hexnumstr (p, offset);
12413   *p++ = ',';
12414   p += hexnumstr (p, len);
12415   *p++ = '\0';
12416
12417   putpkt (rs->buf);
12418   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12419   if (reply && *reply)
12420     {
12421       /* 'l' by itself means we're at the end of the buffer and
12422          there is nothing more to get.  */
12423       if (*reply == 'l')
12424         return 0;
12425
12426       /* Convert the reply into binary.  Limit the number of bytes to
12427          convert according to our passed-in buffer size, rather than
12428          what was returned in the packet; if the target is
12429          unexpectedly generous and gives us a bigger reply than we
12430          asked for, we don't want to crash.  */
12431       rslt = hex2bin (target_buf, buf, len);
12432       return rslt;
12433     }
12434
12435   /* Something went wrong, flag as an error.  */
12436   return -1;
12437 }
12438
12439 static void
12440 remote_set_disconnected_tracing (struct target_ops *self, int val)
12441 {
12442   struct remote_state *rs = get_remote_state ();
12443
12444   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12445     {
12446       char *reply;
12447
12448       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12449       putpkt (rs->buf);
12450       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12451       if (*reply == '\0')
12452         error (_("Target does not support this command."));
12453       if (strcmp (reply, "OK") != 0)
12454         error (_("Bogus reply from target: %s"), reply);
12455     }
12456   else if (val)
12457     warning (_("Target does not support disconnected tracing."));
12458 }
12459
12460 static int
12461 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12462 {
12463   struct thread_info *info = find_thread_ptid (ptid);
12464
12465   if (info && info->priv)
12466     return info->priv->core;
12467   return -1;
12468 }
12469
12470 static void
12471 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12472 {
12473   struct remote_state *rs = get_remote_state ();
12474   char *reply;
12475
12476   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12477   putpkt (rs->buf);
12478   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12479   if (*reply == '\0')
12480     error (_("Target does not support this command."));
12481   if (strcmp (reply, "OK") != 0)
12482     error (_("Bogus reply from target: %s"), reply);
12483 }
12484
12485 static struct traceframe_info *
12486 remote_traceframe_info (struct target_ops *self)
12487 {
12488   char *text;
12489
12490   text = target_read_stralloc (&current_target,
12491                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12492   if (text != NULL)
12493     {
12494       struct traceframe_info *info;
12495       struct cleanup *back_to = make_cleanup (xfree, text);
12496
12497       info = parse_traceframe_info (text);
12498       do_cleanups (back_to);
12499       return info;
12500     }
12501
12502   return NULL;
12503 }
12504
12505 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
12506    instruction on which a fast tracepoint may be placed.  Returns -1
12507    if the packet is not supported, and 0 if the minimum instruction
12508    length is unknown.  */
12509
12510 static int
12511 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12512 {
12513   struct remote_state *rs = get_remote_state ();
12514   char *reply;
12515
12516   /* If we're not debugging a process yet, the IPA can't be
12517      loaded.  */
12518   if (!target_has_execution)
12519     return 0;
12520
12521   /* Make sure the remote is pointing at the right process.  */
12522   set_general_process ();
12523
12524   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12525   putpkt (rs->buf);
12526   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12527   if (*reply == '\0')
12528     return -1;
12529   else
12530     {
12531       ULONGEST min_insn_len;
12532
12533       unpack_varlen_hex (reply, &min_insn_len);
12534
12535       return (int) min_insn_len;
12536     }
12537 }
12538
12539 static void
12540 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12541 {
12542   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12543     {
12544       struct remote_state *rs = get_remote_state ();
12545       char *buf = rs->buf;
12546       char *endbuf = rs->buf + get_remote_packet_size ();
12547       enum packet_result result;
12548
12549       gdb_assert (val >= 0 || val == -1);
12550       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12551       /* Send -1 as literal "-1" to avoid host size dependency.  */
12552       if (val < 0)
12553         {
12554           *buf++ = '-';
12555           buf += hexnumstr (buf, (ULONGEST) -val);
12556         }
12557       else
12558         buf += hexnumstr (buf, (ULONGEST) val);
12559
12560       putpkt (rs->buf);
12561       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12562       result = packet_ok (rs->buf,
12563                   &remote_protocol_packets[PACKET_QTBuffer_size]);
12564
12565       if (result != PACKET_OK)
12566         warning (_("Bogus reply from target: %s"), rs->buf);
12567     }
12568 }
12569
12570 static int
12571 remote_set_trace_notes (struct target_ops *self,
12572                         const char *user, const char *notes,
12573                         const char *stop_notes)
12574 {
12575   struct remote_state *rs = get_remote_state ();
12576   char *reply;
12577   char *buf = rs->buf;
12578   char *endbuf = rs->buf + get_remote_packet_size ();
12579   int nbytes;
12580
12581   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12582   if (user)
12583     {
12584       buf += xsnprintf (buf, endbuf - buf, "user:");
12585       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12586       buf += 2 * nbytes;
12587       *buf++ = ';';
12588     }
12589   if (notes)
12590     {
12591       buf += xsnprintf (buf, endbuf - buf, "notes:");
12592       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12593       buf += 2 * nbytes;
12594       *buf++ = ';';
12595     }
12596   if (stop_notes)
12597     {
12598       buf += xsnprintf (buf, endbuf - buf, "tstop:");
12599       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12600       buf += 2 * nbytes;
12601       *buf++ = ';';
12602     }
12603   /* Ensure the buffer is terminated.  */
12604   *buf = '\0';
12605
12606   putpkt (rs->buf);
12607   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12608   if (*reply == '\0')
12609     return 0;
12610
12611   if (strcmp (reply, "OK") != 0)
12612     error (_("Bogus reply from target: %s"), reply);
12613
12614   return 1;
12615 }
12616
12617 static int
12618 remote_use_agent (struct target_ops *self, int use)
12619 {
12620   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12621     {
12622       struct remote_state *rs = get_remote_state ();
12623
12624       /* If the stub supports QAgent.  */
12625       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12626       putpkt (rs->buf);
12627       getpkt (&rs->buf, &rs->buf_size, 0);
12628
12629       if (strcmp (rs->buf, "OK") == 0)
12630         {
12631           use_agent = use;
12632           return 1;
12633         }
12634     }
12635
12636   return 0;
12637 }
12638
12639 static int
12640 remote_can_use_agent (struct target_ops *self)
12641 {
12642   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12643 }
12644
12645 struct btrace_target_info
12646 {
12647   /* The ptid of the traced thread.  */
12648   ptid_t ptid;
12649
12650   /* The obtained branch trace configuration.  */
12651   struct btrace_config conf;
12652 };
12653
12654 /* Reset our idea of our target's btrace configuration.  */
12655
12656 static void
12657 remote_btrace_reset (void)
12658 {
12659   struct remote_state *rs = get_remote_state ();
12660
12661   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12662 }
12663
12664 /* Check whether the target supports branch tracing.  */
12665
12666 static int
12667 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12668 {
12669   if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12670     return 0;
12671   if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12672     return 0;
12673
12674   switch (format)
12675     {
12676       case BTRACE_FORMAT_NONE:
12677         return 0;
12678
12679       case BTRACE_FORMAT_BTS:
12680         return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12681
12682       case BTRACE_FORMAT_PT:
12683         /* The trace is decoded on the host.  Even if our target supports it,
12684            we still need to have libipt to decode the trace.  */
12685 #if defined (HAVE_LIBIPT)
12686         return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12687 #else /* !defined (HAVE_LIBIPT)  */
12688         return 0;
12689 #endif /* !defined (HAVE_LIBIPT)  */
12690     }
12691
12692   internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12693 }
12694
12695 /* Synchronize the configuration with the target.  */
12696
12697 static void
12698 btrace_sync_conf (const struct btrace_config *conf)
12699 {
12700   struct packet_config *packet;
12701   struct remote_state *rs;
12702   char *buf, *pos, *endbuf;
12703
12704   rs = get_remote_state ();
12705   buf = rs->buf;
12706   endbuf = buf + get_remote_packet_size ();
12707
12708   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12709   if (packet_config_support (packet) == PACKET_ENABLE
12710       && conf->bts.size != rs->btrace_config.bts.size)
12711     {
12712       pos = buf;
12713       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12714                         conf->bts.size);
12715
12716       putpkt (buf);
12717       getpkt (&buf, &rs->buf_size, 0);
12718
12719       if (packet_ok (buf, packet) == PACKET_ERROR)
12720         {
12721           if (buf[0] == 'E' && buf[1] == '.')
12722             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12723           else
12724             error (_("Failed to configure the BTS buffer size."));
12725         }
12726
12727       rs->btrace_config.bts.size = conf->bts.size;
12728     }
12729
12730   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12731   if (packet_config_support (packet) == PACKET_ENABLE
12732       && conf->pt.size != rs->btrace_config.pt.size)
12733     {
12734       pos = buf;
12735       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12736                         conf->pt.size);
12737
12738       putpkt (buf);
12739       getpkt (&buf, &rs->buf_size, 0);
12740
12741       if (packet_ok (buf, packet) == PACKET_ERROR)
12742         {
12743           if (buf[0] == 'E' && buf[1] == '.')
12744             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12745           else
12746             error (_("Failed to configure the trace buffer size."));
12747         }
12748
12749       rs->btrace_config.pt.size = conf->pt.size;
12750     }
12751 }
12752
12753 /* Read the current thread's btrace configuration from the target and
12754    store it into CONF.  */
12755
12756 static void
12757 btrace_read_config (struct btrace_config *conf)
12758 {
12759   char *xml;
12760
12761   xml = target_read_stralloc (&current_target,
12762                               TARGET_OBJECT_BTRACE_CONF, "");
12763   if (xml != NULL)
12764     {
12765       struct cleanup *cleanup;
12766
12767       cleanup = make_cleanup (xfree, xml);
12768       parse_xml_btrace_conf (conf, xml);
12769       do_cleanups (cleanup);
12770     }
12771 }
12772
12773 /* Enable branch tracing.  */
12774
12775 static struct btrace_target_info *
12776 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12777                       const struct btrace_config *conf)
12778 {
12779   struct btrace_target_info *tinfo = NULL;
12780   struct packet_config *packet = NULL;
12781   struct remote_state *rs = get_remote_state ();
12782   char *buf = rs->buf;
12783   char *endbuf = rs->buf + get_remote_packet_size ();
12784
12785   switch (conf->format)
12786     {
12787       case BTRACE_FORMAT_BTS:
12788         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12789         break;
12790
12791       case BTRACE_FORMAT_PT:
12792         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12793         break;
12794     }
12795
12796   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12797     error (_("Target does not support branch tracing."));
12798
12799   btrace_sync_conf (conf);
12800
12801   set_general_thread (ptid);
12802
12803   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12804   putpkt (rs->buf);
12805   getpkt (&rs->buf, &rs->buf_size, 0);
12806
12807   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12808     {
12809       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12810         error (_("Could not enable branch tracing for %s: %s"),
12811                target_pid_to_str (ptid), rs->buf + 2);
12812       else
12813         error (_("Could not enable branch tracing for %s."),
12814                target_pid_to_str (ptid));
12815     }
12816
12817   tinfo = XCNEW (struct btrace_target_info);
12818   tinfo->ptid = ptid;
12819
12820   /* If we fail to read the configuration, we lose some information, but the
12821      tracing itself is not impacted.  */
12822   TRY
12823     {
12824       btrace_read_config (&tinfo->conf);
12825     }
12826   CATCH (err, RETURN_MASK_ERROR)
12827     {
12828       if (err.message != NULL)
12829         warning ("%s", err.message);
12830     }
12831   END_CATCH
12832
12833   return tinfo;
12834 }
12835
12836 /* Disable branch tracing.  */
12837
12838 static void
12839 remote_disable_btrace (struct target_ops *self,
12840                        struct btrace_target_info *tinfo)
12841 {
12842   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12843   struct remote_state *rs = get_remote_state ();
12844   char *buf = rs->buf;
12845   char *endbuf = rs->buf + get_remote_packet_size ();
12846
12847   if (packet_config_support (packet) != PACKET_ENABLE)
12848     error (_("Target does not support branch tracing."));
12849
12850   set_general_thread (tinfo->ptid);
12851
12852   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12853   putpkt (rs->buf);
12854   getpkt (&rs->buf, &rs->buf_size, 0);
12855
12856   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12857     {
12858       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12859         error (_("Could not disable branch tracing for %s: %s"),
12860                target_pid_to_str (tinfo->ptid), rs->buf + 2);
12861       else
12862         error (_("Could not disable branch tracing for %s."),
12863                target_pid_to_str (tinfo->ptid));
12864     }
12865
12866   xfree (tinfo);
12867 }
12868
12869 /* Teardown branch tracing.  */
12870
12871 static void
12872 remote_teardown_btrace (struct target_ops *self,
12873                         struct btrace_target_info *tinfo)
12874 {
12875   /* We must not talk to the target during teardown.  */
12876   xfree (tinfo);
12877 }
12878
12879 /* Read the branch trace.  */
12880
12881 static enum btrace_error
12882 remote_read_btrace (struct target_ops *self,
12883                     struct btrace_data *btrace,
12884                     struct btrace_target_info *tinfo,
12885                     enum btrace_read_type type)
12886 {
12887   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12888   struct cleanup *cleanup;
12889   const char *annex;
12890   char *xml;
12891
12892   if (packet_config_support (packet) != PACKET_ENABLE)
12893     error (_("Target does not support branch tracing."));
12894
12895 #if !defined(HAVE_LIBEXPAT)
12896   error (_("Cannot process branch tracing result. XML parsing not supported."));
12897 #endif
12898
12899   switch (type)
12900     {
12901     case BTRACE_READ_ALL:
12902       annex = "all";
12903       break;
12904     case BTRACE_READ_NEW:
12905       annex = "new";
12906       break;
12907     case BTRACE_READ_DELTA:
12908       annex = "delta";
12909       break;
12910     default:
12911       internal_error (__FILE__, __LINE__,
12912                       _("Bad branch tracing read type: %u."),
12913                       (unsigned int) type);
12914     }
12915
12916   xml = target_read_stralloc (&current_target,
12917                               TARGET_OBJECT_BTRACE, annex);
12918   if (xml == NULL)
12919     return BTRACE_ERR_UNKNOWN;
12920
12921   cleanup = make_cleanup (xfree, xml);
12922   parse_xml_btrace (btrace, xml);
12923   do_cleanups (cleanup);
12924
12925   return BTRACE_ERR_NONE;
12926 }
12927
12928 static const struct btrace_config *
12929 remote_btrace_conf (struct target_ops *self,
12930                     const struct btrace_target_info *tinfo)
12931 {
12932   return &tinfo->conf;
12933 }
12934
12935 static int
12936 remote_augmented_libraries_svr4_read (struct target_ops *self)
12937 {
12938   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12939           == PACKET_ENABLE);
12940 }
12941
12942 /* Implementation of to_load.  */
12943
12944 static void
12945 remote_load (struct target_ops *self, const char *name, int from_tty)
12946 {
12947   generic_load (name, from_tty);
12948 }
12949
12950 /* Accepts an integer PID; returns a string representing a file that
12951    can be opened on the remote side to get the symbols for the child
12952    process.  Returns NULL if the operation is not supported.  */
12953
12954 static char *
12955 remote_pid_to_exec_file (struct target_ops *self, int pid)
12956 {
12957   static char *filename = NULL;
12958   struct inferior *inf;
12959   char *annex = NULL;
12960
12961   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12962     return NULL;
12963
12964   if (filename != NULL)
12965     xfree (filename);
12966
12967   inf = find_inferior_pid (pid);
12968   if (inf == NULL)
12969     internal_error (__FILE__, __LINE__,
12970                     _("not currently attached to process %d"), pid);
12971
12972   if (!inf->fake_pid_p)
12973     {
12974       const int annex_size = 9;
12975
12976       annex = (char *) alloca (annex_size);
12977       xsnprintf (annex, annex_size, "%x", pid);
12978     }
12979
12980   filename = target_read_stralloc (&current_target,
12981                                    TARGET_OBJECT_EXEC_FILE, annex);
12982
12983   return filename;
12984 }
12985
12986 /* Implement the to_can_do_single_step target_ops method.  */
12987
12988 static int
12989 remote_can_do_single_step (struct target_ops *ops)
12990 {
12991   /* We can only tell whether target supports single step or not by
12992      supported s and S vCont actions if the stub supports vContSupported
12993      feature.  If the stub doesn't support vContSupported feature,
12994      we have conservatively to think target doesn't supports single
12995      step.  */
12996   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12997     {
12998       struct remote_state *rs = get_remote_state ();
12999
13000       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13001         remote_vcont_probe (rs);
13002
13003       return rs->supports_vCont.s && rs->supports_vCont.S;
13004     }
13005   else
13006     return 0;
13007 }
13008
13009 static void
13010 init_remote_ops (void)
13011 {
13012   remote_ops.to_shortname = "remote";
13013   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13014   remote_ops.to_doc =
13015     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13016 Specify the serial device it is connected to\n\
13017 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13018   remote_ops.to_open = remote_open;
13019   remote_ops.to_close = remote_close;
13020   remote_ops.to_detach = remote_detach;
13021   remote_ops.to_disconnect = remote_disconnect;
13022   remote_ops.to_resume = remote_resume;
13023   remote_ops.to_wait = remote_wait;
13024   remote_ops.to_fetch_registers = remote_fetch_registers;
13025   remote_ops.to_store_registers = remote_store_registers;
13026   remote_ops.to_prepare_to_store = remote_prepare_to_store;
13027   remote_ops.to_files_info = remote_files_info;
13028   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13029   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13030   remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13031   remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13032   remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13033   remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13034   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13035   remote_ops.to_stopped_data_address = remote_stopped_data_address;
13036   remote_ops.to_watchpoint_addr_within_range =
13037     remote_watchpoint_addr_within_range;
13038   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13039   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13040   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13041   remote_ops.to_region_ok_for_hw_watchpoint
13042      = remote_region_ok_for_hw_watchpoint;
13043   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13044   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13045   remote_ops.to_kill = remote_kill;
13046   remote_ops.to_load = remote_load;
13047   remote_ops.to_mourn_inferior = remote_mourn;
13048   remote_ops.to_pass_signals = remote_pass_signals;
13049   remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13050   remote_ops.to_program_signals = remote_program_signals;
13051   remote_ops.to_thread_alive = remote_thread_alive;
13052   remote_ops.to_thread_name = remote_thread_name;
13053   remote_ops.to_update_thread_list = remote_update_thread_list;
13054   remote_ops.to_pid_to_str = remote_pid_to_str;
13055   remote_ops.to_extra_thread_info = remote_threads_extra_info;
13056   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13057   remote_ops.to_stop = remote_stop;
13058   remote_ops.to_interrupt = remote_interrupt;
13059   remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
13060   remote_ops.to_xfer_partial = remote_xfer_partial;
13061   remote_ops.to_rcmd = remote_rcmd;
13062   remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13063   remote_ops.to_log_command = serial_log_command;
13064   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13065   remote_ops.to_stratum = process_stratum;
13066   remote_ops.to_has_all_memory = default_child_has_all_memory;
13067   remote_ops.to_has_memory = default_child_has_memory;
13068   remote_ops.to_has_stack = default_child_has_stack;
13069   remote_ops.to_has_registers = default_child_has_registers;
13070   remote_ops.to_has_execution = default_child_has_execution;
13071   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
13072   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13073   remote_ops.to_magic = OPS_MAGIC;
13074   remote_ops.to_memory_map = remote_memory_map;
13075   remote_ops.to_flash_erase = remote_flash_erase;
13076   remote_ops.to_flash_done = remote_flash_done;
13077   remote_ops.to_read_description = remote_read_description;
13078   remote_ops.to_search_memory = remote_search_memory;
13079   remote_ops.to_can_async_p = remote_can_async_p;
13080   remote_ops.to_is_async_p = remote_is_async_p;
13081   remote_ops.to_async = remote_async;
13082   remote_ops.to_thread_events = remote_thread_events;
13083   remote_ops.to_can_do_single_step = remote_can_do_single_step;
13084   remote_ops.to_terminal_inferior = remote_terminal_inferior;
13085   remote_ops.to_terminal_ours = remote_terminal_ours;
13086   remote_ops.to_supports_non_stop = remote_supports_non_stop;
13087   remote_ops.to_supports_multi_process = remote_supports_multi_process;
13088   remote_ops.to_supports_disable_randomization
13089     = remote_supports_disable_randomization;
13090   remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13091   remote_ops.to_fileio_open = remote_hostio_open;
13092   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13093   remote_ops.to_fileio_pread = remote_hostio_pread;
13094   remote_ops.to_fileio_fstat = remote_hostio_fstat;
13095   remote_ops.to_fileio_close = remote_hostio_close;
13096   remote_ops.to_fileio_unlink = remote_hostio_unlink;
13097   remote_ops.to_fileio_readlink = remote_hostio_readlink;
13098   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13099   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13100   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13101   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13102   remote_ops.to_trace_init = remote_trace_init;
13103   remote_ops.to_download_tracepoint = remote_download_tracepoint;
13104   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13105   remote_ops.to_download_trace_state_variable
13106     = remote_download_trace_state_variable;
13107   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13108   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13109   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13110   remote_ops.to_trace_start = remote_trace_start;
13111   remote_ops.to_get_trace_status = remote_get_trace_status;
13112   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13113   remote_ops.to_trace_stop = remote_trace_stop;
13114   remote_ops.to_trace_find = remote_trace_find;
13115   remote_ops.to_get_trace_state_variable_value
13116     = remote_get_trace_state_variable_value;
13117   remote_ops.to_save_trace_data = remote_save_trace_data;
13118   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13119   remote_ops.to_upload_trace_state_variables
13120     = remote_upload_trace_state_variables;
13121   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13122   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13123   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13124   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13125   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13126   remote_ops.to_set_trace_notes = remote_set_trace_notes;
13127   remote_ops.to_core_of_thread = remote_core_of_thread;
13128   remote_ops.to_verify_memory = remote_verify_memory;
13129   remote_ops.to_get_tib_address = remote_get_tib_address;
13130   remote_ops.to_set_permissions = remote_set_permissions;
13131   remote_ops.to_static_tracepoint_marker_at
13132     = remote_static_tracepoint_marker_at;
13133   remote_ops.to_static_tracepoint_markers_by_strid
13134     = remote_static_tracepoint_markers_by_strid;
13135   remote_ops.to_traceframe_info = remote_traceframe_info;
13136   remote_ops.to_use_agent = remote_use_agent;
13137   remote_ops.to_can_use_agent = remote_can_use_agent;
13138   remote_ops.to_supports_btrace = remote_supports_btrace;
13139   remote_ops.to_enable_btrace = remote_enable_btrace;
13140   remote_ops.to_disable_btrace = remote_disable_btrace;
13141   remote_ops.to_teardown_btrace = remote_teardown_btrace;
13142   remote_ops.to_read_btrace = remote_read_btrace;
13143   remote_ops.to_btrace_conf = remote_btrace_conf;
13144   remote_ops.to_augmented_libraries_svr4_read =
13145     remote_augmented_libraries_svr4_read;
13146   remote_ops.to_follow_fork = remote_follow_fork;
13147   remote_ops.to_follow_exec = remote_follow_exec;
13148   remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13149   remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13150   remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13151   remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13152   remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13153   remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13154 }
13155
13156 /* Set up the extended remote vector by making a copy of the standard
13157    remote vector and adding to it.  */
13158
13159 static void
13160 init_extended_remote_ops (void)
13161 {
13162   extended_remote_ops = remote_ops;
13163
13164   extended_remote_ops.to_shortname = "extended-remote";
13165   extended_remote_ops.to_longname =
13166     "Extended remote serial target in gdb-specific protocol";
13167   extended_remote_ops.to_doc =
13168     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13169 Specify the serial device it is connected to (e.g. /dev/ttya).";
13170   extended_remote_ops.to_open = extended_remote_open;
13171   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13172   extended_remote_ops.to_detach = extended_remote_detach;
13173   extended_remote_ops.to_attach = extended_remote_attach;
13174   extended_remote_ops.to_post_attach = extended_remote_post_attach;
13175   extended_remote_ops.to_supports_disable_randomization
13176     = extended_remote_supports_disable_randomization;
13177 }
13178
13179 static int
13180 remote_can_async_p (struct target_ops *ops)
13181 {
13182   struct remote_state *rs = get_remote_state ();
13183
13184   if (!target_async_permitted)
13185     /* We only enable async when the user specifically asks for it.  */
13186     return 0;
13187
13188   /* We're async whenever the serial device is.  */
13189   return serial_can_async_p (rs->remote_desc);
13190 }
13191
13192 static int
13193 remote_is_async_p (struct target_ops *ops)
13194 {
13195   struct remote_state *rs = get_remote_state ();
13196
13197   if (!target_async_permitted)
13198     /* We only enable async when the user specifically asks for it.  */
13199     return 0;
13200
13201   /* We're async whenever the serial device is.  */
13202   return serial_is_async_p (rs->remote_desc);
13203 }
13204
13205 /* Pass the SERIAL event on and up to the client.  One day this code
13206    will be able to delay notifying the client of an event until the
13207    point where an entire packet has been received.  */
13208
13209 static serial_event_ftype remote_async_serial_handler;
13210
13211 static void
13212 remote_async_serial_handler (struct serial *scb, void *context)
13213 {
13214   /* Don't propogate error information up to the client.  Instead let
13215      the client find out about the error by querying the target.  */
13216   inferior_event_handler (INF_REG_EVENT, NULL);
13217 }
13218
13219 static void
13220 remote_async_inferior_event_handler (gdb_client_data data)
13221 {
13222   inferior_event_handler (INF_REG_EVENT, NULL);
13223 }
13224
13225 static void
13226 remote_async (struct target_ops *ops, int enable)
13227 {
13228   struct remote_state *rs = get_remote_state ();
13229
13230   if (enable)
13231     {
13232       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13233
13234       /* If there are pending events in the stop reply queue tell the
13235          event loop to process them.  */
13236       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13237         mark_async_event_handler (remote_async_inferior_event_token);
13238       /* For simplicity, below we clear the pending events token
13239          without remembering whether it is marked, so here we always
13240          mark it.  If there's actually no pending notification to
13241          process, this ends up being a no-op (other than a spurious
13242          event-loop wakeup).  */
13243       if (target_is_non_stop_p ())
13244         mark_async_event_handler (rs->notif_state->get_pending_events_token);
13245     }
13246   else
13247     {
13248       serial_async (rs->remote_desc, NULL, NULL);
13249       /* If the core is disabling async, it doesn't want to be
13250          disturbed with target events.  Clear all async event sources
13251          too.  */
13252       clear_async_event_handler (remote_async_inferior_event_token);
13253       if (target_is_non_stop_p ())
13254         clear_async_event_handler (rs->notif_state->get_pending_events_token);
13255     }
13256 }
13257
13258 /* Implementation of the to_thread_events method.  */
13259
13260 static void
13261 remote_thread_events (struct target_ops *ops, int enable)
13262 {
13263   struct remote_state *rs = get_remote_state ();
13264   size_t size = get_remote_packet_size ();
13265
13266   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13267     return;
13268
13269   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13270   putpkt (rs->buf);
13271   getpkt (&rs->buf, &rs->buf_size, 0);
13272
13273   switch (packet_ok (rs->buf,
13274                      &remote_protocol_packets[PACKET_QThreadEvents]))
13275     {
13276     case PACKET_OK:
13277       if (strcmp (rs->buf, "OK") != 0)
13278         error (_("Remote refused setting thread events: %s"), rs->buf);
13279       break;
13280     case PACKET_ERROR:
13281       warning (_("Remote failure reply: %s"), rs->buf);
13282       break;
13283     case PACKET_UNKNOWN:
13284       break;
13285     }
13286 }
13287
13288 static void
13289 set_remote_cmd (char *args, int from_tty)
13290 {
13291   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13292 }
13293
13294 static void
13295 show_remote_cmd (char *args, int from_tty)
13296 {
13297   /* We can't just use cmd_show_list here, because we want to skip
13298      the redundant "show remote Z-packet" and the legacy aliases.  */
13299   struct cleanup *showlist_chain;
13300   struct cmd_list_element *list = remote_show_cmdlist;
13301   struct ui_out *uiout = current_uiout;
13302
13303   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13304   for (; list != NULL; list = list->next)
13305     if (strcmp (list->name, "Z-packet") == 0)
13306       continue;
13307     else if (list->type == not_set_cmd)
13308       /* Alias commands are exactly like the original, except they
13309          don't have the normal type.  */
13310       continue;
13311     else
13312       {
13313         struct cleanup *option_chain
13314           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13315
13316         ui_out_field_string (uiout, "name", list->name);
13317         ui_out_text (uiout, ":  ");
13318         if (list->type == show_cmd)
13319           do_show_command ((char *) NULL, from_tty, list);
13320         else
13321           cmd_func (list, NULL, from_tty);
13322         /* Close the tuple.  */
13323         do_cleanups (option_chain);
13324       }
13325
13326   /* Close the tuple.  */
13327   do_cleanups (showlist_chain);
13328 }
13329
13330
13331 /* Function to be called whenever a new objfile (shlib) is detected.  */
13332 static void
13333 remote_new_objfile (struct objfile *objfile)
13334 {
13335   struct remote_state *rs = get_remote_state ();
13336
13337   if (rs->remote_desc != 0)             /* Have a remote connection.  */
13338     remote_check_symbols ();
13339 }
13340
13341 /* Pull all the tracepoints defined on the target and create local
13342    data structures representing them.  We don't want to create real
13343    tracepoints yet, we don't want to mess up the user's existing
13344    collection.  */
13345   
13346 static int
13347 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13348 {
13349   struct remote_state *rs = get_remote_state ();
13350   char *p;
13351
13352   /* Ask for a first packet of tracepoint definition.  */
13353   putpkt ("qTfP");
13354   getpkt (&rs->buf, &rs->buf_size, 0);
13355   p = rs->buf;
13356   while (*p && *p != 'l')
13357     {
13358       parse_tracepoint_definition (p, utpp);
13359       /* Ask for another packet of tracepoint definition.  */
13360       putpkt ("qTsP");
13361       getpkt (&rs->buf, &rs->buf_size, 0);
13362       p = rs->buf;
13363     }
13364   return 0;
13365 }
13366
13367 static int
13368 remote_upload_trace_state_variables (struct target_ops *self,
13369                                      struct uploaded_tsv **utsvp)
13370 {
13371   struct remote_state *rs = get_remote_state ();
13372   char *p;
13373
13374   /* Ask for a first packet of variable definition.  */
13375   putpkt ("qTfV");
13376   getpkt (&rs->buf, &rs->buf_size, 0);
13377   p = rs->buf;
13378   while (*p && *p != 'l')
13379     {
13380       parse_tsv_definition (p, utsvp);
13381       /* Ask for another packet of variable definition.  */
13382       putpkt ("qTsV");
13383       getpkt (&rs->buf, &rs->buf_size, 0);
13384       p = rs->buf;
13385     }
13386   return 0;
13387 }
13388
13389 /* The "set/show range-stepping" show hook.  */
13390
13391 static void
13392 show_range_stepping (struct ui_file *file, int from_tty,
13393                      struct cmd_list_element *c,
13394                      const char *value)
13395 {
13396   fprintf_filtered (file,
13397                     _("Debugger's willingness to use range stepping "
13398                       "is %s.\n"), value);
13399 }
13400
13401 /* The "set/show range-stepping" set hook.  */
13402
13403 static void
13404 set_range_stepping (char *ignore_args, int from_tty,
13405                     struct cmd_list_element *c)
13406 {
13407   struct remote_state *rs = get_remote_state ();
13408
13409   /* Whene enabling, check whether range stepping is actually
13410      supported by the target, and warn if not.  */
13411   if (use_range_stepping)
13412     {
13413       if (rs->remote_desc != NULL)
13414         {
13415           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13416             remote_vcont_probe (rs);
13417
13418           if (packet_support (PACKET_vCont) == PACKET_ENABLE
13419               && rs->supports_vCont.r)
13420             return;
13421         }
13422
13423       warning (_("Range stepping is not supported by the current target"));
13424     }
13425 }
13426
13427 void
13428 _initialize_remote (void)
13429 {
13430   struct cmd_list_element *cmd;
13431   const char *cmd_name;
13432
13433   /* architecture specific data */
13434   remote_gdbarch_data_handle =
13435     gdbarch_data_register_post_init (init_remote_state);
13436   remote_g_packet_data_handle =
13437     gdbarch_data_register_pre_init (remote_g_packet_data_init);
13438
13439   remote_pspace_data
13440     = register_program_space_data_with_cleanup (NULL,
13441                                                 remote_pspace_data_cleanup);
13442
13443   /* Initialize the per-target state.  At the moment there is only one
13444      of these, not one per target.  Only one target is active at a
13445      time.  */
13446   remote_state = new_remote_state ();
13447
13448   init_remote_ops ();
13449   add_target (&remote_ops);
13450
13451   init_extended_remote_ops ();
13452   add_target (&extended_remote_ops);
13453
13454   /* Hook into new objfile notification.  */
13455   observer_attach_new_objfile (remote_new_objfile);
13456   /* We're no longer interested in notification events of an inferior
13457      when it exits.  */
13458   observer_attach_inferior_exit (discard_pending_stop_replies);
13459
13460   /* Set up signal handlers.  */
13461   async_sigint_remote_token =
13462     create_async_signal_handler (async_remote_interrupt, NULL);
13463   async_sigint_remote_twice_token =
13464     create_async_signal_handler (async_remote_interrupt_twice, NULL);
13465
13466 #if 0
13467   init_remote_threadtests ();
13468 #endif
13469
13470   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13471   /* set/show remote ...  */
13472
13473   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13474 Remote protocol specific variables\n\
13475 Configure various remote-protocol specific variables such as\n\
13476 the packets being used"),
13477                   &remote_set_cmdlist, "set remote ",
13478                   0 /* allow-unknown */, &setlist);
13479   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13480 Remote protocol specific variables\n\
13481 Configure various remote-protocol specific variables such as\n\
13482 the packets being used"),
13483                   &remote_show_cmdlist, "show remote ",
13484                   0 /* allow-unknown */, &showlist);
13485
13486   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13487 Compare section data on target to the exec file.\n\
13488 Argument is a single section name (default: all loaded sections).\n\
13489 To compare only read-only loaded sections, specify the -r option."),
13490            &cmdlist);
13491
13492   add_cmd ("packet", class_maintenance, packet_command, _("\
13493 Send an arbitrary packet to a remote target.\n\
13494    maintenance packet TEXT\n\
13495 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13496 this command sends the string TEXT to the inferior, and displays the\n\
13497 response packet.  GDB supplies the initial `$' character, and the\n\
13498 terminating `#' character and checksum."),
13499            &maintenancelist);
13500
13501   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13502 Set whether to send break if interrupted."), _("\
13503 Show whether to send break if interrupted."), _("\
13504 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13505                            set_remotebreak, show_remotebreak,
13506                            &setlist, &showlist);
13507   cmd_name = "remotebreak";
13508   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13509   deprecate_cmd (cmd, "set remote interrupt-sequence");
13510   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13511   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13512   deprecate_cmd (cmd, "show remote interrupt-sequence");
13513
13514   add_setshow_enum_cmd ("interrupt-sequence", class_support,
13515                         interrupt_sequence_modes, &interrupt_sequence_mode,
13516                         _("\
13517 Set interrupt sequence to remote target."), _("\
13518 Show interrupt sequence to remote target."), _("\
13519 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13520                         NULL, show_interrupt_sequence,
13521                         &remote_set_cmdlist,
13522                         &remote_show_cmdlist);
13523
13524   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13525                            &interrupt_on_connect, _("\
13526 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
13527 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
13528 If set, interrupt sequence is sent to remote target."),
13529                            NULL, NULL,
13530                            &remote_set_cmdlist, &remote_show_cmdlist);
13531
13532   /* Install commands for configuring memory read/write packets.  */
13533
13534   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13535 Set the maximum number of bytes per memory write packet (deprecated)."),
13536            &setlist);
13537   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13538 Show the maximum number of bytes per memory write packet (deprecated)."),
13539            &showlist);
13540   add_cmd ("memory-write-packet-size", no_class,
13541            set_memory_write_packet_size, _("\
13542 Set the maximum number of bytes per memory-write packet.\n\
13543 Specify the number of bytes in a packet or 0 (zero) for the\n\
13544 default packet size.  The actual limit is further reduced\n\
13545 dependent on the target.  Specify ``fixed'' to disable the\n\
13546 further restriction and ``limit'' to enable that restriction."),
13547            &remote_set_cmdlist);
13548   add_cmd ("memory-read-packet-size", no_class,
13549            set_memory_read_packet_size, _("\
13550 Set the maximum number of bytes per memory-read packet.\n\
13551 Specify the number of bytes in a packet or 0 (zero) for the\n\
13552 default packet size.  The actual limit is further reduced\n\
13553 dependent on the target.  Specify ``fixed'' to disable the\n\
13554 further restriction and ``limit'' to enable that restriction."),
13555            &remote_set_cmdlist);
13556   add_cmd ("memory-write-packet-size", no_class,
13557            show_memory_write_packet_size,
13558            _("Show the maximum number of bytes per memory-write packet."),
13559            &remote_show_cmdlist);
13560   add_cmd ("memory-read-packet-size", no_class,
13561            show_memory_read_packet_size,
13562            _("Show the maximum number of bytes per memory-read packet."),
13563            &remote_show_cmdlist);
13564
13565   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13566                             &remote_hw_watchpoint_limit, _("\
13567 Set the maximum number of target hardware watchpoints."), _("\
13568 Show the maximum number of target hardware watchpoints."), _("\
13569 Specify a negative limit for unlimited."),
13570                             NULL, NULL, /* FIXME: i18n: The maximum
13571                                            number of target hardware
13572                                            watchpoints is %s.  */
13573                             &remote_set_cmdlist, &remote_show_cmdlist);
13574   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13575                             &remote_hw_watchpoint_length_limit, _("\
13576 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13577 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13578 Specify a negative limit for unlimited."),
13579                             NULL, NULL, /* FIXME: i18n: The maximum
13580                                            length (in bytes) of a target
13581                                            hardware watchpoint is %s.  */
13582                             &remote_set_cmdlist, &remote_show_cmdlist);
13583   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13584                             &remote_hw_breakpoint_limit, _("\
13585 Set the maximum number of target hardware breakpoints."), _("\
13586 Show the maximum number of target hardware breakpoints."), _("\
13587 Specify a negative limit for unlimited."),
13588                             NULL, NULL, /* FIXME: i18n: The maximum
13589                                            number of target hardware
13590                                            breakpoints is %s.  */
13591                             &remote_set_cmdlist, &remote_show_cmdlist);
13592
13593   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13594                              &remote_address_size, _("\
13595 Set the maximum size of the address (in bits) in a memory packet."), _("\
13596 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13597                              NULL,
13598                              NULL, /* FIXME: i18n: */
13599                              &setlist, &showlist);
13600
13601   init_all_packet_configs ();
13602
13603   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13604                          "X", "binary-download", 1);
13605
13606   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13607                          "vCont", "verbose-resume", 0);
13608
13609   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13610                          "QPassSignals", "pass-signals", 0);
13611
13612   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13613                          "QCatchSyscalls", "catch-syscalls", 0);
13614
13615   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13616                          "QProgramSignals", "program-signals", 0);
13617
13618   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13619                          "qSymbol", "symbol-lookup", 0);
13620
13621   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13622                          "P", "set-register", 1);
13623
13624   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13625                          "p", "fetch-register", 1);
13626
13627   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13628                          "Z0", "software-breakpoint", 0);
13629
13630   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13631                          "Z1", "hardware-breakpoint", 0);
13632
13633   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13634                          "Z2", "write-watchpoint", 0);
13635
13636   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13637                          "Z3", "read-watchpoint", 0);
13638
13639   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13640                          "Z4", "access-watchpoint", 0);
13641
13642   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13643                          "qXfer:auxv:read", "read-aux-vector", 0);
13644
13645   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13646                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
13647
13648   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13649                          "qXfer:features:read", "target-features", 0);
13650
13651   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13652                          "qXfer:libraries:read", "library-info", 0);
13653
13654   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13655                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13656
13657   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13658                          "qXfer:memory-map:read", "memory-map", 0);
13659
13660   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13661                          "qXfer:spu:read", "read-spu-object", 0);
13662
13663   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13664                          "qXfer:spu:write", "write-spu-object", 0);
13665
13666   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13667                         "qXfer:osdata:read", "osdata", 0);
13668
13669   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13670                          "qXfer:threads:read", "threads", 0);
13671
13672   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13673                          "qXfer:siginfo:read", "read-siginfo-object", 0);
13674
13675   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13676                          "qXfer:siginfo:write", "write-siginfo-object", 0);
13677
13678   add_packet_config_cmd
13679     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13680      "qXfer:traceframe-info:read", "traceframe-info", 0);
13681
13682   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13683                          "qXfer:uib:read", "unwind-info-block", 0);
13684
13685   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13686                          "qGetTLSAddr", "get-thread-local-storage-address",
13687                          0);
13688
13689   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13690                          "qGetTIBAddr", "get-thread-information-block-address",
13691                          0);
13692
13693   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13694                          "bc", "reverse-continue", 0);
13695
13696   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13697                          "bs", "reverse-step", 0);
13698
13699   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13700                          "qSupported", "supported-packets", 0);
13701
13702   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13703                          "qSearch:memory", "search-memory", 0);
13704
13705   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13706                          "qTStatus", "trace-status", 0);
13707
13708   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13709                          "vFile:setfs", "hostio-setfs", 0);
13710
13711   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13712                          "vFile:open", "hostio-open", 0);
13713
13714   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13715                          "vFile:pread", "hostio-pread", 0);
13716
13717   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13718                          "vFile:pwrite", "hostio-pwrite", 0);
13719
13720   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13721                          "vFile:close", "hostio-close", 0);
13722
13723   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13724                          "vFile:unlink", "hostio-unlink", 0);
13725
13726   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13727                          "vFile:readlink", "hostio-readlink", 0);
13728
13729   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13730                          "vFile:fstat", "hostio-fstat", 0);
13731
13732   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13733                          "vAttach", "attach", 0);
13734
13735   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13736                          "vRun", "run", 0);
13737
13738   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13739                          "QStartNoAckMode", "noack", 0);
13740
13741   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13742                          "vKill", "kill", 0);
13743
13744   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13745                          "qAttached", "query-attached", 0);
13746
13747   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13748                          "ConditionalTracepoints",
13749                          "conditional-tracepoints", 0);
13750
13751   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13752                          "ConditionalBreakpoints",
13753                          "conditional-breakpoints", 0);
13754
13755   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13756                          "BreakpointCommands",
13757                          "breakpoint-commands", 0);
13758
13759   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13760                          "FastTracepoints", "fast-tracepoints", 0);
13761
13762   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13763                          "TracepointSource", "TracepointSource", 0);
13764
13765   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13766                          "QAllow", "allow", 0);
13767
13768   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13769                          "StaticTracepoints", "static-tracepoints", 0);
13770
13771   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13772                          "InstallInTrace", "install-in-trace", 0);
13773
13774   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13775                          "qXfer:statictrace:read", "read-sdata-object", 0);
13776
13777   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13778                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13779
13780   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13781                          "QDisableRandomization", "disable-randomization", 0);
13782
13783   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13784                          "QAgent", "agent", 0);
13785
13786   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13787                          "QTBuffer:size", "trace-buffer-size", 0);
13788
13789   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13790        "Qbtrace:off", "disable-btrace", 0);
13791
13792   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13793        "Qbtrace:bts", "enable-btrace-bts", 0);
13794
13795   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13796        "Qbtrace:pt", "enable-btrace-pt", 0);
13797
13798   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13799        "qXfer:btrace", "read-btrace", 0);
13800
13801   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13802        "qXfer:btrace-conf", "read-btrace-conf", 0);
13803
13804   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13805        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13806
13807   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13808        "multiprocess-feature", "multiprocess-feature", 0);
13809
13810   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13811                          "swbreak-feature", "swbreak-feature", 0);
13812
13813   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13814                          "hwbreak-feature", "hwbreak-feature", 0);
13815
13816   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13817                          "fork-event-feature", "fork-event-feature", 0);
13818
13819   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13820                          "vfork-event-feature", "vfork-event-feature", 0);
13821
13822   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13823        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13824
13825   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13826                          "vContSupported", "verbose-resume-supported", 0);
13827
13828   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13829                          "exec-event-feature", "exec-event-feature", 0);
13830
13831   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13832                          "vCtrlC", "ctrl-c", 0);
13833
13834   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13835                          "QThreadEvents", "thread-events", 0);
13836
13837   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13838                          "N stop reply", "no-resumed-stop-reply", 0);
13839
13840   /* Assert that we've registered "set remote foo-packet" commands
13841      for all packet configs.  */
13842   {
13843     int i;
13844
13845     for (i = 0; i < PACKET_MAX; i++)
13846       {
13847         /* Ideally all configs would have a command associated.  Some
13848            still don't though.  */
13849         int excepted;
13850
13851         switch (i)
13852           {
13853           case PACKET_QNonStop:
13854           case PACKET_EnableDisableTracepoints_feature:
13855           case PACKET_tracenz_feature:
13856           case PACKET_DisconnectedTracing_feature:
13857           case PACKET_augmented_libraries_svr4_read_feature:
13858           case PACKET_qCRC:
13859             /* Additions to this list need to be well justified:
13860                pre-existing packets are OK; new packets are not.  */
13861             excepted = 1;
13862             break;
13863           default:
13864             excepted = 0;
13865             break;
13866           }
13867
13868         /* This catches both forgetting to add a config command, and
13869            forgetting to remove a packet from the exception list.  */
13870         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13871       }
13872   }
13873
13874   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
13875      Z sub-packet has its own set and show commands, but users may
13876      have sets to this variable in their .gdbinit files (or in their
13877      documentation).  */
13878   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13879                                 &remote_Z_packet_detect, _("\
13880 Set use of remote protocol `Z' packets"), _("\
13881 Show use of remote protocol `Z' packets "), _("\
13882 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13883 packets."),
13884                                 set_remote_protocol_Z_packet_cmd,
13885                                 show_remote_protocol_Z_packet_cmd,
13886                                 /* FIXME: i18n: Use of remote protocol
13887                                    `Z' packets is %s.  */
13888                                 &remote_set_cmdlist, &remote_show_cmdlist);
13889
13890   add_prefix_cmd ("remote", class_files, remote_command, _("\
13891 Manipulate files on the remote system\n\
13892 Transfer files to and from the remote target system."),
13893                   &remote_cmdlist, "remote ",
13894                   0 /* allow-unknown */, &cmdlist);
13895
13896   add_cmd ("put", class_files, remote_put_command,
13897            _("Copy a local file to the remote system."),
13898            &remote_cmdlist);
13899
13900   add_cmd ("get", class_files, remote_get_command,
13901            _("Copy a remote file to the local system."),
13902            &remote_cmdlist);
13903
13904   add_cmd ("delete", class_files, remote_delete_command,
13905            _("Delete a remote file."),
13906            &remote_cmdlist);
13907
13908   add_setshow_string_noescape_cmd ("exec-file", class_files,
13909                                    &remote_exec_file_var, _("\
13910 Set the remote pathname for \"run\""), _("\
13911 Show the remote pathname for \"run\""), NULL,
13912                                    set_remote_exec_file,
13913                                    show_remote_exec_file,
13914                                    &remote_set_cmdlist,
13915                                    &remote_show_cmdlist);
13916
13917   add_setshow_boolean_cmd ("range-stepping", class_run,
13918                            &use_range_stepping, _("\
13919 Enable or disable range stepping."), _("\
13920 Show whether target-assisted range stepping is enabled."), _("\
13921 If on, and the target supports it, when stepping a source line, GDB\n\
13922 tells the target to step the corresponding range of addresses itself instead\n\
13923 of issuing multiple single-steps.  This speeds up source level\n\
13924 stepping.  If off, GDB always issues single-steps, even if range\n\
13925 stepping is supported by the target.  The default is on."),
13926                            set_range_stepping,
13927                            show_range_stepping,
13928                            &setlist,
13929                            &showlist);
13930
13931   /* Eventually initialize fileio.  See fileio.c */
13932   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13933
13934   /* Take advantage of the fact that the TID field is not used, to tag
13935      special ptids with it set to != 0.  */
13936   magic_null_ptid = ptid_build (42000, -1, 1);
13937   not_sent_ptid = ptid_build (42000, -2, 1);
13938   any_thread_ptid = ptid_build (42000, 0, 1);
13939
13940   target_buf_size = 2048;
13941   target_buf = (char *) xmalloc (target_buf_size);
13942 }
13943