Remove some unneeded casts from remote.c
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2016 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* See the GDB User Guide for details of the GDB remote protocol.  */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 /*#include "terminal.h" */
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observer.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "filestuff.h"
46 #include "rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdb_sys_time.h"
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74
75 /* Temp hacks for tracepoint encoding migration.  */
76 static char *target_buf;
77 static long target_buf_size;
78
79 /* Per-program-space data key.  */
80 static const struct program_space_data *remote_pspace_data;
81
82 /* The variable registered as the control variable used by the
83    remote exec-file commands.  While the remote exec-file setting is
84    per-program-space, the set/show machinery uses this as the 
85    location of the remote exec-file value.  */
86 static char *remote_exec_file_var;
87
88 /* The size to align memory write packets, when practical.  The protocol
89    does not guarantee any alignment, and gdb will generate short
90    writes and unaligned writes, but even as a best-effort attempt this
91    can improve bulk transfers.  For instance, if a write is misaligned
92    relative to the target's data bus, the stub may need to make an extra
93    round trip fetching data from the target.  This doesn't make a
94    huge difference, but it's easy to do, so we try to be helpful.
95
96    The alignment chosen is arbitrary; usually data bus width is
97    important here, not the possibly larger cache line size.  */
98 enum { REMOTE_ALIGN_WRITES = 16 };
99
100 /* Prototypes for local functions.  */
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 remote_files_info (struct target_ops *ignore);
106
107 static void remote_prepare_to_store (struct target_ops *self,
108                                      struct regcache *regcache);
109
110 static void remote_open_1 (const char *, int, struct target_ops *,
111                            int extended_p);
112
113 static void remote_close (struct target_ops *self);
114
115 struct remote_state;
116
117 static int remote_vkill (int pid, struct remote_state *rs);
118
119 static void remote_kill_k (void);
120
121 static void remote_mourn (struct target_ops *ops);
122
123 static void extended_remote_restart (void);
124
125 static void remote_send (char **buf, long *sizeof_buf_p);
126
127 static int readchar (int timeout);
128
129 static void remote_serial_write (const char *str, int len);
130
131 static void remote_kill (struct target_ops *ops);
132
133 static int remote_can_async_p (struct target_ops *);
134
135 static int remote_is_async_p (struct target_ops *);
136
137 static void remote_async (struct target_ops *ops, int enable);
138
139 static void remote_thread_events (struct target_ops *ops, int enable);
140
141 static void interrupt_query (void);
142
143 static void set_general_thread (struct ptid ptid);
144 static void set_continue_thread (struct ptid ptid);
145
146 static void get_offsets (void);
147
148 static void skip_frame (void);
149
150 static long read_frame (char **buf_p, long *sizeof_buf);
151
152 static int hexnumlen (ULONGEST num);
153
154 static void init_remote_ops (void);
155
156 static void init_extended_remote_ops (void);
157
158 static void remote_stop (struct target_ops *self, ptid_t);
159
160 static int stubhex (int ch);
161
162 static int hexnumstr (char *, ULONGEST);
163
164 static int hexnumnstr (char *, ULONGEST, int);
165
166 static CORE_ADDR remote_address_masked (CORE_ADDR);
167
168 static void print_packet (const char *);
169
170 static void compare_sections_command (char *, int);
171
172 static void packet_command (char *, int);
173
174 static int stub_unpack_int (char *buff, int fieldlength);
175
176 static ptid_t remote_current_thread (ptid_t oldptid);
177
178 static int putpkt_binary (const char *buf, int cnt);
179
180 static void check_binary_download (CORE_ADDR addr);
181
182 struct packet_config;
183
184 static void show_packet_config_cmd (struct packet_config *config);
185
186 static void show_remote_protocol_packet_cmd (struct ui_file *file,
187                                              int from_tty,
188                                              struct cmd_list_element *c,
189                                              const char *value);
190
191 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
192 static ptid_t read_ptid (char *buf, char **obuf);
193
194 static void remote_set_permissions (struct target_ops *self);
195
196 static int remote_get_trace_status (struct target_ops *self,
197                                     struct trace_status *ts);
198
199 static int remote_upload_tracepoints (struct target_ops *self,
200                                       struct uploaded_tp **utpp);
201
202 static int remote_upload_trace_state_variables (struct target_ops *self,
203                                                 struct uploaded_tsv **utsvp);
204   
205 static void remote_query_supported (void);
206
207 static void remote_check_symbols (void);
208
209 void _initialize_remote (void);
210
211 struct stop_reply;
212 static void stop_reply_xfree (struct stop_reply *);
213 static void remote_parse_stop_reply (char *, struct stop_reply *);
214 static void push_stop_reply (struct stop_reply *);
215 static void discard_pending_stop_replies_in_queue (struct remote_state *);
216 static int peek_stop_reply (ptid_t ptid);
217
218 struct threads_listing_context;
219 static void remove_new_fork_children (struct threads_listing_context *);
220
221 static void remote_async_inferior_event_handler (gdb_client_data);
222
223 static void remote_terminal_ours (struct target_ops *self);
224
225 static int remote_read_description_p (struct target_ops *target);
226
227 static void remote_console_output (char *msg);
228
229 static int remote_supports_cond_breakpoints (struct target_ops *self);
230
231 static int remote_can_run_breakpoint_commands (struct target_ops *self);
232
233 static void remote_btrace_reset (void);
234
235 static void remote_btrace_maybe_reopen (void);
236
237 static int stop_reply_queue_length (void);
238
239 static void readahead_cache_invalidate (void);
240
241 static void remote_unpush_and_throw (void);
242
243 /* For "remote".  */
244
245 static struct cmd_list_element *remote_cmdlist;
246
247 /* For "set remote" and "show remote".  */
248
249 static struct cmd_list_element *remote_set_cmdlist;
250 static struct cmd_list_element *remote_show_cmdlist;
251
252 /* Stub vCont actions support.
253
254    Each field is a boolean flag indicating whether the stub reports
255    support for the corresponding action.  */
256
257 struct vCont_action_support
258 {
259   /* vCont;t */
260   int t;
261
262   /* vCont;r */
263   int r;
264
265   /* vCont;s */
266   int s;
267
268   /* vCont;S */
269   int S;
270 };
271
272 /* Controls whether GDB is willing to use range stepping.  */
273
274 static int use_range_stepping = 1;
275
276 #define OPAQUETHREADBYTES 8
277
278 /* a 64 bit opaque identifier */
279 typedef unsigned char threadref[OPAQUETHREADBYTES];
280
281 /* About this many threadisds fit in a packet.  */
282
283 #define MAXTHREADLISTRESULTS 32
284
285 /* Data for the vFile:pread readahead cache.  */
286
287 struct readahead_cache
288 {
289   /* The file descriptor for the file that is being cached.  -1 if the
290      cache is invalid.  */
291   int fd;
292
293   /* The offset into the file that the cache buffer corresponds
294      to.  */
295   ULONGEST offset;
296
297   /* The buffer holding the cache contents.  */
298   gdb_byte *buf;
299   /* The buffer's size.  We try to read as much as fits into a packet
300      at a time.  */
301   size_t bufsize;
302
303   /* Cache hit and miss counters.  */
304   ULONGEST hit_count;
305   ULONGEST miss_count;
306 };
307
308 /* Description of the remote protocol state for the currently
309    connected target.  This is per-target state, and independent of the
310    selected architecture.  */
311
312 struct remote_state
313 {
314   /* A buffer to use for incoming packets, and its current size.  The
315      buffer is grown dynamically for larger incoming packets.
316      Outgoing packets may also be constructed in this buffer.
317      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
318      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
319      packets.  */
320   char *buf;
321   long buf_size;
322
323   /* True if we're going through initial connection setup (finding out
324      about the remote side's threads, relocating symbols, etc.).  */
325   int starting_up;
326
327   /* If we negotiated packet size explicitly (and thus can bypass
328      heuristics for the largest packet size that will not overflow
329      a buffer in the stub), this will be set to that packet size.
330      Otherwise zero, meaning to use the guessed size.  */
331   long explicit_packet_size;
332
333   /* remote_wait is normally called when the target is running and
334      waits for a stop reply packet.  But sometimes we need to call it
335      when the target is already stopped.  We can send a "?" packet
336      and have remote_wait read the response.  Or, if we already have
337      the response, we can stash it in BUF and tell remote_wait to
338      skip calling getpkt.  This flag is set when BUF contains a
339      stop reply packet and the target is not waiting.  */
340   int cached_wait_status;
341
342   /* True, if in no ack mode.  That is, neither GDB nor the stub will
343      expect acks from each other.  The connection is assumed to be
344      reliable.  */
345   int noack_mode;
346
347   /* True if we're connected in extended remote mode.  */
348   int extended;
349
350   /* True if we resumed the target and we're waiting for the target to
351      stop.  In the mean time, we can't start another command/query.
352      The remote server wouldn't be ready to process it, so we'd
353      timeout waiting for a reply that would never come and eventually
354      we'd close the connection.  This can happen in asynchronous mode
355      because we allow GDB commands while the target is running.  */
356   int waiting_for_stop_reply;
357
358   /* The status of the stub support for the various vCont actions.  */
359   struct vCont_action_support supports_vCont;
360
361   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
362      responded to that.  */
363   int ctrlc_pending_p;
364
365   /* True if we saw a Ctrl-C while reading or writing from/to the
366      remote descriptor.  At that point it is not safe to send a remote
367      interrupt packet, so we instead remember we saw the Ctrl-C and
368      process it once we're done with sending/receiving the current
369      packet, which should be shortly.  If however that takes too long,
370      and the user presses Ctrl-C again, we offer to disconnect.  */
371   int got_ctrlc_during_io;
372
373   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
374      remote_open knows that we don't have a file open when the program
375      starts.  */
376   struct serial *remote_desc;
377
378   /* These are the threads which we last sent to the remote system.  The
379      TID member will be -1 for all or -2 for not sent yet.  */
380   ptid_t general_thread;
381   ptid_t continue_thread;
382
383   /* This is the traceframe which we last selected on the remote system.
384      It will be -1 if no traceframe is selected.  */
385   int remote_traceframe_number;
386
387   char *last_pass_packet;
388
389   /* The last QProgramSignals packet sent to the target.  We bypass
390      sending a new program signals list down to the target if the new
391      packet is exactly the same as the last we sent.  IOW, we only let
392      the target know about program signals list changes.  */
393   char *last_program_signals_packet;
394
395   enum gdb_signal last_sent_signal;
396
397   int last_sent_step;
398
399   /* The execution direction of the last resume we got.  */
400   enum exec_direction_kind last_resume_exec_dir;
401
402   char *finished_object;
403   char *finished_annex;
404   ULONGEST finished_offset;
405
406   /* Should we try the 'ThreadInfo' query packet?
407
408      This variable (NOT available to the user: auto-detect only!)
409      determines whether GDB will use the new, simpler "ThreadInfo"
410      query or the older, more complex syntax for thread queries.
411      This is an auto-detect variable (set to true at each connect,
412      and set to false when the target fails to recognize it).  */
413   int use_threadinfo_query;
414   int use_threadextra_query;
415
416   threadref echo_nextthread;
417   threadref nextthread;
418   threadref resultthreadlist[MAXTHREADLISTRESULTS];
419
420   /* The state of remote notification.  */
421   struct remote_notif_state *notif_state;
422
423   /* The branch trace configuration.  */
424   struct btrace_config btrace_config;
425
426   /* The argument to the last "vFile:setfs:" packet we sent, used
427      to avoid sending repeated unnecessary "vFile:setfs:" packets.
428      Initialized to -1 to indicate that no "vFile:setfs:" packet
429      has yet been sent.  */
430   int fs_pid;
431
432   /* A readahead cache for vFile:pread.  Often, reading a binary
433      involves a sequence of small reads.  E.g., when parsing an ELF
434      file.  A readahead cache helps mostly the case of remote
435      debugging on a connection with higher latency, due to the
436      request/reply nature of the RSP.  We only cache data for a single
437      file descriptor at a time.  */
438   struct readahead_cache readahead_cache;
439 };
440
441 /* Private data that we'll store in (struct thread_info)->private.  */
442 struct private_thread_info
443 {
444   char *extra;
445   char *name;
446   int core;
447
448   /* Whether the target stopped for a breakpoint/watchpoint.  */
449   enum target_stop_reason stop_reason;
450
451   /* This is set to the data address of the access causing the target
452      to stop for a watchpoint.  */
453   CORE_ADDR watch_data_address;
454 };
455
456 static void
457 free_private_thread_info (struct private_thread_info *info)
458 {
459   xfree (info->extra);
460   xfree (info->name);
461   xfree (info);
462 }
463
464 /* This data could be associated with a target, but we do not always
465    have access to the current target when we need it, so for now it is
466    static.  This will be fine for as long as only one target is in use
467    at a time.  */
468 static struct remote_state *remote_state;
469
470 static struct remote_state *
471 get_remote_state_raw (void)
472 {
473   return remote_state;
474 }
475
476 /* Allocate a new struct remote_state with xmalloc, initialize it, and
477    return it.  */
478
479 static struct remote_state *
480 new_remote_state (void)
481 {
482   struct remote_state *result = XCNEW (struct remote_state);
483
484   /* The default buffer size is unimportant; it will be expanded
485      whenever a larger buffer is needed. */
486   result->buf_size = 400;
487   result->buf = (char *) xmalloc (result->buf_size);
488   result->remote_traceframe_number = -1;
489   result->last_sent_signal = GDB_SIGNAL_0;
490   result->last_resume_exec_dir = EXEC_FORWARD;
491   result->fs_pid = -1;
492
493   return result;
494 }
495
496 /* Description of the remote protocol for a given architecture.  */
497
498 struct packet_reg
499 {
500   long offset; /* Offset into G packet.  */
501   long regnum; /* GDB's internal register number.  */
502   LONGEST pnum; /* Remote protocol register number.  */
503   int in_g_packet; /* Always part of G packet.  */
504   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
505      at present.  */
506   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
507      at present.  */
508 };
509
510 struct remote_arch_state
511 {
512   /* Description of the remote protocol registers.  */
513   long sizeof_g_packet;
514
515   /* Description of the remote protocol registers indexed by REGNUM
516      (making an array gdbarch_num_regs in size).  */
517   struct packet_reg *regs;
518
519   /* This is the size (in chars) of the first response to the ``g''
520      packet.  It is used as a heuristic when determining the maximum
521      size of memory-read and memory-write packets.  A target will
522      typically only reserve a buffer large enough to hold the ``g''
523      packet.  The size does not include packet overhead (headers and
524      trailers).  */
525   long actual_register_packet_size;
526
527   /* This is the maximum size (in chars) of a non read/write packet.
528      It is also used as a cap on the size of read/write packets.  */
529   long remote_packet_size;
530 };
531
532 /* Utility: generate error from an incoming stub packet.  */
533 static void
534 trace_error (char *buf)
535 {
536   if (*buf++ != 'E')
537     return;                     /* not an error msg */
538   switch (*buf)
539     {
540     case '1':                   /* malformed packet error */
541       if (*++buf == '0')        /*   general case: */
542         error (_("remote.c: error in outgoing packet."));
543       else
544         error (_("remote.c: error in outgoing packet at field #%ld."),
545                strtol (buf, NULL, 16));
546     default:
547       error (_("Target returns error code '%s'."), buf);
548     }
549 }
550
551 /* Utility: wait for reply from stub, while accepting "O" packets.  */
552 static char *
553 remote_get_noisy_reply (char **buf_p,
554                         long *sizeof_buf)
555 {
556   do                            /* Loop on reply from remote stub.  */
557     {
558       char *buf;
559
560       QUIT;                     /* Allow user to bail out with ^C.  */
561       getpkt (buf_p, sizeof_buf, 0);
562       buf = *buf_p;
563       if (buf[0] == 'E')
564         trace_error (buf);
565       else if (startswith (buf, "qRelocInsn:"))
566         {
567           ULONGEST ul;
568           CORE_ADDR from, to, org_to;
569           char *p, *pp;
570           int adjusted_size = 0;
571           int relocated = 0;
572
573           p = buf + strlen ("qRelocInsn:");
574           pp = unpack_varlen_hex (p, &ul);
575           if (*pp != ';')
576             error (_("invalid qRelocInsn packet: %s"), buf);
577           from = ul;
578
579           p = pp + 1;
580           unpack_varlen_hex (p, &ul);
581           to = ul;
582
583           org_to = to;
584
585           TRY
586             {
587               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
588               relocated = 1;
589             }
590           CATCH (ex, RETURN_MASK_ALL)
591             {
592               if (ex.error == MEMORY_ERROR)
593                 {
594                   /* Propagate memory errors silently back to the
595                      target.  The stub may have limited the range of
596                      addresses we can write to, for example.  */
597                 }
598               else
599                 {
600                   /* Something unexpectedly bad happened.  Be verbose
601                      so we can tell what, and propagate the error back
602                      to the stub, so it doesn't get stuck waiting for
603                      a response.  */
604                   exception_fprintf (gdb_stderr, ex,
605                                      _("warning: relocating instruction: "));
606                 }
607               putpkt ("E01");
608             }
609           END_CATCH
610
611           if (relocated)
612             {
613               adjusted_size = to - org_to;
614
615               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
616               putpkt (buf);
617             }
618         }
619       else if (buf[0] == 'O' && buf[1] != 'K')
620         remote_console_output (buf + 1);        /* 'O' message from stub */
621       else
622         return buf;             /* Here's the actual reply.  */
623     }
624   while (1);
625 }
626
627 /* Handle for retreving the remote protocol data from gdbarch.  */
628 static struct gdbarch_data *remote_gdbarch_data_handle;
629
630 static struct remote_arch_state *
631 get_remote_arch_state (void)
632 {
633   gdb_assert (target_gdbarch () != NULL);
634   return ((struct remote_arch_state *)
635           gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
636 }
637
638 /* Fetch the global remote target state.  */
639
640 static struct remote_state *
641 get_remote_state (void)
642 {
643   /* Make sure that the remote architecture state has been
644      initialized, because doing so might reallocate rs->buf.  Any
645      function which calls getpkt also needs to be mindful of changes
646      to rs->buf, but this call limits the number of places which run
647      into trouble.  */
648   get_remote_arch_state ();
649
650   return get_remote_state_raw ();
651 }
652
653 /* Cleanup routine for the remote module's pspace data.  */
654
655 static void
656 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
657 {
658   char *remote_exec_file = (char *) arg;
659
660   xfree (remote_exec_file);
661 }
662
663 /* Fetch the remote exec-file from the current program space.  */
664
665 static const char *
666 get_remote_exec_file (void)
667 {
668   char *remote_exec_file;
669
670   remote_exec_file
671     = (char *) program_space_data (current_program_space,
672                                    remote_pspace_data);
673   if (remote_exec_file == NULL)
674     return "";
675
676   return remote_exec_file;
677 }
678
679 /* Set the remote exec file for PSPACE.  */
680
681 static void
682 set_pspace_remote_exec_file (struct program_space *pspace,
683                         char *remote_exec_file)
684 {
685   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
686
687   xfree (old_file);
688   set_program_space_data (pspace, remote_pspace_data,
689                           xstrdup (remote_exec_file));
690 }
691
692 /* The "set/show remote exec-file" set command hook.  */
693
694 static void
695 set_remote_exec_file (char *ignored, int from_tty,
696                       struct cmd_list_element *c)
697 {
698   gdb_assert (remote_exec_file_var != NULL);
699   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
700 }
701
702 /* The "set/show remote exec-file" show command hook.  */
703
704 static void
705 show_remote_exec_file (struct ui_file *file, int from_tty,
706                        struct cmd_list_element *cmd, const char *value)
707 {
708   fprintf_filtered (file, "%s\n", remote_exec_file_var);
709 }
710
711 static int
712 compare_pnums (const void *lhs_, const void *rhs_)
713 {
714   const struct packet_reg * const *lhs
715     = (const struct packet_reg * const *) lhs_;
716   const struct packet_reg * const *rhs
717     = (const struct packet_reg * const *) rhs_;
718
719   if ((*lhs)->pnum < (*rhs)->pnum)
720     return -1;
721   else if ((*lhs)->pnum == (*rhs)->pnum)
722     return 0;
723   else
724     return 1;
725 }
726
727 static int
728 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
729 {
730   int regnum, num_remote_regs, offset;
731   struct packet_reg **remote_regs;
732
733   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
734     {
735       struct packet_reg *r = &regs[regnum];
736
737       if (register_size (gdbarch, regnum) == 0)
738         /* Do not try to fetch zero-sized (placeholder) registers.  */
739         r->pnum = -1;
740       else
741         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
742
743       r->regnum = regnum;
744     }
745
746   /* Define the g/G packet format as the contents of each register
747      with a remote protocol number, in order of ascending protocol
748      number.  */
749
750   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
751   for (num_remote_regs = 0, regnum = 0;
752        regnum < gdbarch_num_regs (gdbarch);
753        regnum++)
754     if (regs[regnum].pnum != -1)
755       remote_regs[num_remote_regs++] = &regs[regnum];
756
757   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
758          compare_pnums);
759
760   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
761     {
762       remote_regs[regnum]->in_g_packet = 1;
763       remote_regs[regnum]->offset = offset;
764       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
765     }
766
767   return offset;
768 }
769
770 /* Given the architecture described by GDBARCH, return the remote
771    protocol register's number and the register's offset in the g/G
772    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
773    If the target does not have a mapping for REGNUM, return false,
774    otherwise, return true.  */
775
776 int
777 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
778                                    int *pnum, int *poffset)
779 {
780   struct packet_reg *regs;
781   struct cleanup *old_chain;
782
783   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
784
785   regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
786   old_chain = make_cleanup (xfree, regs);
787
788   map_regcache_remote_table (gdbarch, regs);
789
790   *pnum = regs[regnum].pnum;
791   *poffset = regs[regnum].offset;
792
793   do_cleanups (old_chain);
794
795   return *pnum != -1;
796 }
797
798 static void *
799 init_remote_state (struct gdbarch *gdbarch)
800 {
801   struct remote_state *rs = get_remote_state_raw ();
802   struct remote_arch_state *rsa;
803
804   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
805
806   /* Use the architecture to build a regnum<->pnum table, which will be
807      1:1 unless a feature set specifies otherwise.  */
808   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
809                                       gdbarch_num_regs (gdbarch),
810                                       struct packet_reg);
811
812   /* Record the maximum possible size of the g packet - it may turn out
813      to be smaller.  */
814   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
815
816   /* Default maximum number of characters in a packet body.  Many
817      remote stubs have a hardwired buffer size of 400 bytes
818      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
819      as the maximum packet-size to ensure that the packet and an extra
820      NUL character can always fit in the buffer.  This stops GDB
821      trashing stubs that try to squeeze an extra NUL into what is
822      already a full buffer (As of 1999-12-04 that was most stubs).  */
823   rsa->remote_packet_size = 400 - 1;
824
825   /* This one is filled in when a ``g'' packet is received.  */
826   rsa->actual_register_packet_size = 0;
827
828   /* Should rsa->sizeof_g_packet needs more space than the
829      default, adjust the size accordingly.  Remember that each byte is
830      encoded as two characters.  32 is the overhead for the packet
831      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
832      (``$NN:G...#NN'') is a better guess, the below has been padded a
833      little.  */
834   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
835     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
836
837   /* Make sure that the packet buffer is plenty big enough for
838      this architecture.  */
839   if (rs->buf_size < rsa->remote_packet_size)
840     {
841       rs->buf_size = 2 * rsa->remote_packet_size;
842       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
843     }
844
845   return rsa;
846 }
847
848 /* Return the current allowed size of a remote packet.  This is
849    inferred from the current architecture, and should be used to
850    limit the length of outgoing packets.  */
851 static long
852 get_remote_packet_size (void)
853 {
854   struct remote_state *rs = get_remote_state ();
855   struct remote_arch_state *rsa = get_remote_arch_state ();
856
857   if (rs->explicit_packet_size)
858     return rs->explicit_packet_size;
859
860   return rsa->remote_packet_size;
861 }
862
863 static struct packet_reg *
864 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
865 {
866   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
867     return NULL;
868   else
869     {
870       struct packet_reg *r = &rsa->regs[regnum];
871
872       gdb_assert (r->regnum == regnum);
873       return r;
874     }
875 }
876
877 static struct packet_reg *
878 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
879 {
880   int i;
881
882   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
883     {
884       struct packet_reg *r = &rsa->regs[i];
885
886       if (r->pnum == pnum)
887         return r;
888     }
889   return NULL;
890 }
891
892 static struct target_ops remote_ops;
893
894 static struct target_ops extended_remote_ops;
895
896 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
897    ``forever'' still use the normal timeout mechanism.  This is
898    currently used by the ASYNC code to guarentee that target reads
899    during the initial connect always time-out.  Once getpkt has been
900    modified to return a timeout indication and, in turn
901    remote_wait()/wait_for_inferior() have gained a timeout parameter
902    this can go away.  */
903 static int wait_forever_enabled_p = 1;
904
905 /* Allow the user to specify what sequence to send to the remote
906    when he requests a program interruption: Although ^C is usually
907    what remote systems expect (this is the default, here), it is
908    sometimes preferable to send a break.  On other systems such
909    as the Linux kernel, a break followed by g, which is Magic SysRq g
910    is required in order to interrupt the execution.  */
911 const char interrupt_sequence_control_c[] = "Ctrl-C";
912 const char interrupt_sequence_break[] = "BREAK";
913 const char interrupt_sequence_break_g[] = "BREAK-g";
914 static const char *const interrupt_sequence_modes[] =
915   {
916     interrupt_sequence_control_c,
917     interrupt_sequence_break,
918     interrupt_sequence_break_g,
919     NULL
920   };
921 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
922
923 static void
924 show_interrupt_sequence (struct ui_file *file, int from_tty,
925                          struct cmd_list_element *c,
926                          const char *value)
927 {
928   if (interrupt_sequence_mode == interrupt_sequence_control_c)
929     fprintf_filtered (file,
930                       _("Send the ASCII ETX character (Ctrl-c) "
931                         "to the remote target to interrupt the "
932                         "execution of the program.\n"));
933   else if (interrupt_sequence_mode == interrupt_sequence_break)
934     fprintf_filtered (file,
935                       _("send a break signal to the remote target "
936                         "to interrupt the execution of the program.\n"));
937   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
938     fprintf_filtered (file,
939                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
940                         "the remote target to interrupt the execution "
941                         "of Linux kernel.\n"));
942   else
943     internal_error (__FILE__, __LINE__,
944                     _("Invalid value for interrupt_sequence_mode: %s."),
945                     interrupt_sequence_mode);
946 }
947
948 /* This boolean variable specifies whether interrupt_sequence is sent
949    to the remote target when gdb connects to it.
950    This is mostly needed when you debug the Linux kernel: The Linux kernel
951    expects BREAK g which is Magic SysRq g for connecting gdb.  */
952 static int interrupt_on_connect = 0;
953
954 /* This variable is used to implement the "set/show remotebreak" commands.
955    Since these commands are now deprecated in favor of "set/show remote
956    interrupt-sequence", it no longer has any effect on the code.  */
957 static int remote_break;
958
959 static void
960 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
961 {
962   if (remote_break)
963     interrupt_sequence_mode = interrupt_sequence_break;
964   else
965     interrupt_sequence_mode = interrupt_sequence_control_c;
966 }
967
968 static void
969 show_remotebreak (struct ui_file *file, int from_tty,
970                   struct cmd_list_element *c,
971                   const char *value)
972 {
973 }
974
975 /* This variable sets the number of bits in an address that are to be
976    sent in a memory ("M" or "m") packet.  Normally, after stripping
977    leading zeros, the entire address would be sent.  This variable
978    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
979    initial implementation of remote.c restricted the address sent in
980    memory packets to ``host::sizeof long'' bytes - (typically 32
981    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
982    address was never sent.  Since fixing this bug may cause a break in
983    some remote targets this variable is principly provided to
984    facilitate backward compatibility.  */
985
986 static unsigned int remote_address_size;
987
988 /* Temporary to track who currently owns the terminal.  See
989    remote_terminal_* for more details.  */
990
991 static int remote_async_terminal_ours_p;
992
993 \f
994 /* User configurable variables for the number of characters in a
995    memory read/write packet.  MIN (rsa->remote_packet_size,
996    rsa->sizeof_g_packet) is the default.  Some targets need smaller
997    values (fifo overruns, et.al.) and some users need larger values
998    (speed up transfers).  The variables ``preferred_*'' (the user
999    request), ``current_*'' (what was actually set) and ``forced_*''
1000    (Positive - a soft limit, negative - a hard limit).  */
1001
1002 struct memory_packet_config
1003 {
1004   char *name;
1005   long size;
1006   int fixed_p;
1007 };
1008
1009 /* The default max memory-write-packet-size.  The 16k is historical.
1010    (It came from older GDB's using alloca for buffers and the
1011    knowledge (folklore?) that some hosts don't cope very well with
1012    large alloca calls.)  */
1013 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1014
1015 /* The minimum remote packet size for memory transfers.  Ensures we
1016    can write at least one byte.  */
1017 #define MIN_MEMORY_PACKET_SIZE 20
1018
1019 /* Compute the current size of a read/write packet.  Since this makes
1020    use of ``actual_register_packet_size'' the computation is dynamic.  */
1021
1022 static long
1023 get_memory_packet_size (struct memory_packet_config *config)
1024 {
1025   struct remote_state *rs = get_remote_state ();
1026   struct remote_arch_state *rsa = get_remote_arch_state ();
1027
1028   long what_they_get;
1029   if (config->fixed_p)
1030     {
1031       if (config->size <= 0)
1032         what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1033       else
1034         what_they_get = config->size;
1035     }
1036   else
1037     {
1038       what_they_get = get_remote_packet_size ();
1039       /* Limit the packet to the size specified by the user.  */
1040       if (config->size > 0
1041           && what_they_get > config->size)
1042         what_they_get = config->size;
1043
1044       /* Limit it to the size of the targets ``g'' response unless we have
1045          permission from the stub to use a larger packet size.  */
1046       if (rs->explicit_packet_size == 0
1047           && rsa->actual_register_packet_size > 0
1048           && what_they_get > rsa->actual_register_packet_size)
1049         what_they_get = rsa->actual_register_packet_size;
1050     }
1051   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1052     what_they_get = MIN_MEMORY_PACKET_SIZE;
1053
1054   /* Make sure there is room in the global buffer for this packet
1055      (including its trailing NUL byte).  */
1056   if (rs->buf_size < what_they_get + 1)
1057     {
1058       rs->buf_size = 2 * what_they_get;
1059       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1060     }
1061
1062   return what_they_get;
1063 }
1064
1065 /* Update the size of a read/write packet.  If they user wants
1066    something really big then do a sanity check.  */
1067
1068 static void
1069 set_memory_packet_size (char *args, struct memory_packet_config *config)
1070 {
1071   int fixed_p = config->fixed_p;
1072   long size = config->size;
1073
1074   if (args == NULL)
1075     error (_("Argument required (integer, `fixed' or `limited')."));
1076   else if (strcmp (args, "hard") == 0
1077       || strcmp (args, "fixed") == 0)
1078     fixed_p = 1;
1079   else if (strcmp (args, "soft") == 0
1080            || strcmp (args, "limit") == 0)
1081     fixed_p = 0;
1082   else
1083     {
1084       char *end;
1085
1086       size = strtoul (args, &end, 0);
1087       if (args == end)
1088         error (_("Invalid %s (bad syntax)."), config->name);
1089
1090       /* Instead of explicitly capping the size of a packet to or
1091          disallowing it, the user is allowed to set the size to
1092          something arbitrarily large.  */
1093     }
1094
1095   /* So that the query shows the correct value.  */
1096   if (size <= 0)
1097     size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1098
1099   /* Extra checks?  */
1100   if (fixed_p && !config->fixed_p)
1101     {
1102       if (! query (_("The target may not be able to correctly handle a %s\n"
1103                    "of %ld bytes. Change the packet size? "),
1104                    config->name, size))
1105         error (_("Packet size not changed."));
1106     }
1107   /* Update the config.  */
1108   config->fixed_p = fixed_p;
1109   config->size = size;
1110 }
1111
1112 static void
1113 show_memory_packet_size (struct memory_packet_config *config)
1114 {
1115   printf_filtered (_("The %s is %ld. "), config->name, config->size);
1116   if (config->fixed_p)
1117     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1118                      get_memory_packet_size (config));
1119   else
1120     printf_filtered (_("Packets are limited to %ld bytes.\n"),
1121                      get_memory_packet_size (config));
1122 }
1123
1124 static struct memory_packet_config memory_write_packet_config =
1125 {
1126   "memory-write-packet-size",
1127 };
1128
1129 static void
1130 set_memory_write_packet_size (char *args, int from_tty)
1131 {
1132   set_memory_packet_size (args, &memory_write_packet_config);
1133 }
1134
1135 static void
1136 show_memory_write_packet_size (char *args, int from_tty)
1137 {
1138   show_memory_packet_size (&memory_write_packet_config);
1139 }
1140
1141 static long
1142 get_memory_write_packet_size (void)
1143 {
1144   return get_memory_packet_size (&memory_write_packet_config);
1145 }
1146
1147 static struct memory_packet_config memory_read_packet_config =
1148 {
1149   "memory-read-packet-size",
1150 };
1151
1152 static void
1153 set_memory_read_packet_size (char *args, int from_tty)
1154 {
1155   set_memory_packet_size (args, &memory_read_packet_config);
1156 }
1157
1158 static void
1159 show_memory_read_packet_size (char *args, int from_tty)
1160 {
1161   show_memory_packet_size (&memory_read_packet_config);
1162 }
1163
1164 static long
1165 get_memory_read_packet_size (void)
1166 {
1167   long size = get_memory_packet_size (&memory_read_packet_config);
1168
1169   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1170      extra buffer size argument before the memory read size can be
1171      increased beyond this.  */
1172   if (size > get_remote_packet_size ())
1173     size = get_remote_packet_size ();
1174   return size;
1175 }
1176
1177 \f
1178 /* Generic configuration support for packets the stub optionally
1179    supports.  Allows the user to specify the use of the packet as well
1180    as allowing GDB to auto-detect support in the remote stub.  */
1181
1182 enum packet_support
1183   {
1184     PACKET_SUPPORT_UNKNOWN = 0,
1185     PACKET_ENABLE,
1186     PACKET_DISABLE
1187   };
1188
1189 struct packet_config
1190   {
1191     const char *name;
1192     const char *title;
1193
1194     /* If auto, GDB auto-detects support for this packet or feature,
1195        either through qSupported, or by trying the packet and looking
1196        at the response.  If true, GDB assumes the target supports this
1197        packet.  If false, the packet is disabled.  Configs that don't
1198        have an associated command always have this set to auto.  */
1199     enum auto_boolean detect;
1200
1201     /* Does the target support this packet?  */
1202     enum packet_support support;
1203   };
1204
1205 /* Analyze a packet's return value and update the packet config
1206    accordingly.  */
1207
1208 enum packet_result
1209 {
1210   PACKET_ERROR,
1211   PACKET_OK,
1212   PACKET_UNKNOWN
1213 };
1214
1215 static enum packet_support packet_config_support (struct packet_config *config);
1216 static enum packet_support packet_support (int packet);
1217
1218 static void
1219 show_packet_config_cmd (struct packet_config *config)
1220 {
1221   char *support = "internal-error";
1222
1223   switch (packet_config_support (config))
1224     {
1225     case PACKET_ENABLE:
1226       support = "enabled";
1227       break;
1228     case PACKET_DISABLE:
1229       support = "disabled";
1230       break;
1231     case PACKET_SUPPORT_UNKNOWN:
1232       support = "unknown";
1233       break;
1234     }
1235   switch (config->detect)
1236     {
1237     case AUTO_BOOLEAN_AUTO:
1238       printf_filtered (_("Support for the `%s' packet "
1239                          "is auto-detected, currently %s.\n"),
1240                        config->name, support);
1241       break;
1242     case AUTO_BOOLEAN_TRUE:
1243     case AUTO_BOOLEAN_FALSE:
1244       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1245                        config->name, support);
1246       break;
1247     }
1248 }
1249
1250 static void
1251 add_packet_config_cmd (struct packet_config *config, const char *name,
1252                        const char *title, int legacy)
1253 {
1254   char *set_doc;
1255   char *show_doc;
1256   char *cmd_name;
1257
1258   config->name = name;
1259   config->title = title;
1260   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1261                         name, title);
1262   show_doc = xstrprintf ("Show current use of remote "
1263                          "protocol `%s' (%s) packet",
1264                          name, title);
1265   /* set/show TITLE-packet {auto,on,off} */
1266   cmd_name = xstrprintf ("%s-packet", title);
1267   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1268                                 &config->detect, set_doc,
1269                                 show_doc, NULL, /* help_doc */
1270                                 NULL,
1271                                 show_remote_protocol_packet_cmd,
1272                                 &remote_set_cmdlist, &remote_show_cmdlist);
1273   /* The command code copies the documentation strings.  */
1274   xfree (set_doc);
1275   xfree (show_doc);
1276   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1277   if (legacy)
1278     {
1279       char *legacy_name;
1280
1281       legacy_name = xstrprintf ("%s-packet", name);
1282       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1283                      &remote_set_cmdlist);
1284       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1285                      &remote_show_cmdlist);
1286     }
1287 }
1288
1289 static enum packet_result
1290 packet_check_result (const char *buf)
1291 {
1292   if (buf[0] != '\0')
1293     {
1294       /* The stub recognized the packet request.  Check that the
1295          operation succeeded.  */
1296       if (buf[0] == 'E'
1297           && isxdigit (buf[1]) && isxdigit (buf[2])
1298           && buf[3] == '\0')
1299         /* "Enn"  - definitly an error.  */
1300         return PACKET_ERROR;
1301
1302       /* Always treat "E." as an error.  This will be used for
1303          more verbose error messages, such as E.memtypes.  */
1304       if (buf[0] == 'E' && buf[1] == '.')
1305         return PACKET_ERROR;
1306
1307       /* The packet may or may not be OK.  Just assume it is.  */
1308       return PACKET_OK;
1309     }
1310   else
1311     /* The stub does not support the packet.  */
1312     return PACKET_UNKNOWN;
1313 }
1314
1315 static enum packet_result
1316 packet_ok (const char *buf, struct packet_config *config)
1317 {
1318   enum packet_result result;
1319
1320   if (config->detect != AUTO_BOOLEAN_TRUE
1321       && config->support == PACKET_DISABLE)
1322     internal_error (__FILE__, __LINE__,
1323                     _("packet_ok: attempt to use a disabled packet"));
1324
1325   result = packet_check_result (buf);
1326   switch (result)
1327     {
1328     case PACKET_OK:
1329     case PACKET_ERROR:
1330       /* The stub recognized the packet request.  */
1331       if (config->support == PACKET_SUPPORT_UNKNOWN)
1332         {
1333           if (remote_debug)
1334             fprintf_unfiltered (gdb_stdlog,
1335                                 "Packet %s (%s) is supported\n",
1336                                 config->name, config->title);
1337           config->support = PACKET_ENABLE;
1338         }
1339       break;
1340     case PACKET_UNKNOWN:
1341       /* The stub does not support the packet.  */
1342       if (config->detect == AUTO_BOOLEAN_AUTO
1343           && config->support == PACKET_ENABLE)
1344         {
1345           /* If the stub previously indicated that the packet was
1346              supported then there is a protocol error.  */
1347           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1348                  config->name, config->title);
1349         }
1350       else if (config->detect == AUTO_BOOLEAN_TRUE)
1351         {
1352           /* The user set it wrong.  */
1353           error (_("Enabled packet %s (%s) not recognized by stub"),
1354                  config->name, config->title);
1355         }
1356
1357       if (remote_debug)
1358         fprintf_unfiltered (gdb_stdlog,
1359                             "Packet %s (%s) is NOT supported\n",
1360                             config->name, config->title);
1361       config->support = PACKET_DISABLE;
1362       break;
1363     }
1364
1365   return result;
1366 }
1367
1368 enum {
1369   PACKET_vCont = 0,
1370   PACKET_X,
1371   PACKET_qSymbol,
1372   PACKET_P,
1373   PACKET_p,
1374   PACKET_Z0,
1375   PACKET_Z1,
1376   PACKET_Z2,
1377   PACKET_Z3,
1378   PACKET_Z4,
1379   PACKET_vFile_setfs,
1380   PACKET_vFile_open,
1381   PACKET_vFile_pread,
1382   PACKET_vFile_pwrite,
1383   PACKET_vFile_close,
1384   PACKET_vFile_unlink,
1385   PACKET_vFile_readlink,
1386   PACKET_vFile_fstat,
1387   PACKET_qXfer_auxv,
1388   PACKET_qXfer_features,
1389   PACKET_qXfer_exec_file,
1390   PACKET_qXfer_libraries,
1391   PACKET_qXfer_libraries_svr4,
1392   PACKET_qXfer_memory_map,
1393   PACKET_qXfer_spu_read,
1394   PACKET_qXfer_spu_write,
1395   PACKET_qXfer_osdata,
1396   PACKET_qXfer_threads,
1397   PACKET_qXfer_statictrace_read,
1398   PACKET_qXfer_traceframe_info,
1399   PACKET_qXfer_uib,
1400   PACKET_qGetTIBAddr,
1401   PACKET_qGetTLSAddr,
1402   PACKET_qSupported,
1403   PACKET_qTStatus,
1404   PACKET_QPassSignals,
1405   PACKET_QCatchSyscalls,
1406   PACKET_QProgramSignals,
1407   PACKET_qCRC,
1408   PACKET_qSearch_memory,
1409   PACKET_vAttach,
1410   PACKET_vRun,
1411   PACKET_QStartNoAckMode,
1412   PACKET_vKill,
1413   PACKET_qXfer_siginfo_read,
1414   PACKET_qXfer_siginfo_write,
1415   PACKET_qAttached,
1416
1417   /* Support for conditional tracepoints.  */
1418   PACKET_ConditionalTracepoints,
1419
1420   /* Support for target-side breakpoint conditions.  */
1421   PACKET_ConditionalBreakpoints,
1422
1423   /* Support for target-side breakpoint commands.  */
1424   PACKET_BreakpointCommands,
1425
1426   /* Support for fast tracepoints.  */
1427   PACKET_FastTracepoints,
1428
1429   /* Support for static tracepoints.  */
1430   PACKET_StaticTracepoints,
1431
1432   /* Support for installing tracepoints while a trace experiment is
1433      running.  */
1434   PACKET_InstallInTrace,
1435
1436   PACKET_bc,
1437   PACKET_bs,
1438   PACKET_TracepointSource,
1439   PACKET_QAllow,
1440   PACKET_qXfer_fdpic,
1441   PACKET_QDisableRandomization,
1442   PACKET_QAgent,
1443   PACKET_QTBuffer_size,
1444   PACKET_Qbtrace_off,
1445   PACKET_Qbtrace_bts,
1446   PACKET_Qbtrace_pt,
1447   PACKET_qXfer_btrace,
1448
1449   /* Support for the QNonStop packet.  */
1450   PACKET_QNonStop,
1451
1452   /* Support for the QThreadEvents packet.  */
1453   PACKET_QThreadEvents,
1454
1455   /* Support for multi-process extensions.  */
1456   PACKET_multiprocess_feature,
1457
1458   /* Support for enabling and disabling tracepoints while a trace
1459      experiment is running.  */
1460   PACKET_EnableDisableTracepoints_feature,
1461
1462   /* Support for collecting strings using the tracenz bytecode.  */
1463   PACKET_tracenz_feature,
1464
1465   /* Support for continuing to run a trace experiment while GDB is
1466      disconnected.  */
1467   PACKET_DisconnectedTracing_feature,
1468
1469   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1470   PACKET_augmented_libraries_svr4_read_feature,
1471
1472   /* Support for the qXfer:btrace-conf:read packet.  */
1473   PACKET_qXfer_btrace_conf,
1474
1475   /* Support for the Qbtrace-conf:bts:size packet.  */
1476   PACKET_Qbtrace_conf_bts_size,
1477
1478   /* Support for swbreak+ feature.  */
1479   PACKET_swbreak_feature,
1480
1481   /* Support for hwbreak+ feature.  */
1482   PACKET_hwbreak_feature,
1483
1484   /* Support for fork events.  */
1485   PACKET_fork_event_feature,
1486
1487   /* Support for vfork events.  */
1488   PACKET_vfork_event_feature,
1489
1490   /* Support for the Qbtrace-conf:pt:size packet.  */
1491   PACKET_Qbtrace_conf_pt_size,
1492
1493   /* Support for exec events.  */
1494   PACKET_exec_event_feature,
1495
1496   /* Support for query supported vCont actions.  */
1497   PACKET_vContSupported,
1498
1499   /* Support remote CTRL-C.  */
1500   PACKET_vCtrlC,
1501
1502   /* Support TARGET_WAITKIND_NO_RESUMED.  */
1503   PACKET_no_resumed,
1504
1505   PACKET_MAX
1506 };
1507
1508 static struct packet_config remote_protocol_packets[PACKET_MAX];
1509
1510 /* Returns the packet's corresponding "set remote foo-packet" command
1511    state.  See struct packet_config for more details.  */
1512
1513 static enum auto_boolean
1514 packet_set_cmd_state (int packet)
1515 {
1516   return remote_protocol_packets[packet].detect;
1517 }
1518
1519 /* Returns whether a given packet or feature is supported.  This takes
1520    into account the state of the corresponding "set remote foo-packet"
1521    command, which may be used to bypass auto-detection.  */
1522
1523 static enum packet_support
1524 packet_config_support (struct packet_config *config)
1525 {
1526   switch (config->detect)
1527     {
1528     case AUTO_BOOLEAN_TRUE:
1529       return PACKET_ENABLE;
1530     case AUTO_BOOLEAN_FALSE:
1531       return PACKET_DISABLE;
1532     case AUTO_BOOLEAN_AUTO:
1533       return config->support;
1534     default:
1535       gdb_assert_not_reached (_("bad switch"));
1536     }
1537 }
1538
1539 /* Same as packet_config_support, but takes the packet's enum value as
1540    argument.  */
1541
1542 static enum packet_support
1543 packet_support (int packet)
1544 {
1545   struct packet_config *config = &remote_protocol_packets[packet];
1546
1547   return packet_config_support (config);
1548 }
1549
1550 static void
1551 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1552                                  struct cmd_list_element *c,
1553                                  const char *value)
1554 {
1555   struct packet_config *packet;
1556
1557   for (packet = remote_protocol_packets;
1558        packet < &remote_protocol_packets[PACKET_MAX];
1559        packet++)
1560     {
1561       if (&packet->detect == c->var)
1562         {
1563           show_packet_config_cmd (packet);
1564           return;
1565         }
1566     }
1567   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1568                   c->name);
1569 }
1570
1571 /* Should we try one of the 'Z' requests?  */
1572
1573 enum Z_packet_type
1574 {
1575   Z_PACKET_SOFTWARE_BP,
1576   Z_PACKET_HARDWARE_BP,
1577   Z_PACKET_WRITE_WP,
1578   Z_PACKET_READ_WP,
1579   Z_PACKET_ACCESS_WP,
1580   NR_Z_PACKET_TYPES
1581 };
1582
1583 /* For compatibility with older distributions.  Provide a ``set remote
1584    Z-packet ...'' command that updates all the Z packet types.  */
1585
1586 static enum auto_boolean remote_Z_packet_detect;
1587
1588 static void
1589 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1590                                   struct cmd_list_element *c)
1591 {
1592   int i;
1593
1594   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1595     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1596 }
1597
1598 static void
1599 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1600                                    struct cmd_list_element *c,
1601                                    const char *value)
1602 {
1603   int i;
1604
1605   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1606     {
1607       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1608     }
1609 }
1610
1611 /* Returns true if the multi-process extensions are in effect.  */
1612
1613 static int
1614 remote_multi_process_p (struct remote_state *rs)
1615 {
1616   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1617 }
1618
1619 /* Returns true if fork events are supported.  */
1620
1621 static int
1622 remote_fork_event_p (struct remote_state *rs)
1623 {
1624   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1625 }
1626
1627 /* Returns true if vfork events are supported.  */
1628
1629 static int
1630 remote_vfork_event_p (struct remote_state *rs)
1631 {
1632   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1633 }
1634
1635 /* Returns true if exec events are supported.  */
1636
1637 static int
1638 remote_exec_event_p (struct remote_state *rs)
1639 {
1640   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1641 }
1642
1643 /* Insert fork catchpoint target routine.  If fork events are enabled
1644    then return success, nothing more to do.  */
1645
1646 static int
1647 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1648 {
1649   struct remote_state *rs = get_remote_state ();
1650
1651   return !remote_fork_event_p (rs);
1652 }
1653
1654 /* Remove fork catchpoint target routine.  Nothing to do, just
1655    return success.  */
1656
1657 static int
1658 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1659 {
1660   return 0;
1661 }
1662
1663 /* Insert vfork catchpoint target routine.  If vfork events are enabled
1664    then return success, nothing more to do.  */
1665
1666 static int
1667 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1668 {
1669   struct remote_state *rs = get_remote_state ();
1670
1671   return !remote_vfork_event_p (rs);
1672 }
1673
1674 /* Remove vfork catchpoint target routine.  Nothing to do, just
1675    return success.  */
1676
1677 static int
1678 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1679 {
1680   return 0;
1681 }
1682
1683 /* Insert exec catchpoint target routine.  If exec events are
1684    enabled, just return success.  */
1685
1686 static int
1687 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1688 {
1689   struct remote_state *rs = get_remote_state ();
1690
1691   return !remote_exec_event_p (rs);
1692 }
1693
1694 /* Remove exec catchpoint target routine.  Nothing to do, just
1695    return success.  */
1696
1697 static int
1698 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1699 {
1700   return 0;
1701 }
1702
1703 \f
1704 /* Asynchronous signal handle registered as event loop source for
1705    when we have pending events ready to be passed to the core.  */
1706
1707 static struct async_event_handler *remote_async_inferior_event_token;
1708
1709 \f
1710
1711 static ptid_t magic_null_ptid;
1712 static ptid_t not_sent_ptid;
1713 static ptid_t any_thread_ptid;
1714
1715 /* Find out if the stub attached to PID (and hence GDB should offer to
1716    detach instead of killing it when bailing out).  */
1717
1718 static int
1719 remote_query_attached (int pid)
1720 {
1721   struct remote_state *rs = get_remote_state ();
1722   size_t size = get_remote_packet_size ();
1723
1724   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1725     return 0;
1726
1727   if (remote_multi_process_p (rs))
1728     xsnprintf (rs->buf, size, "qAttached:%x", pid);
1729   else
1730     xsnprintf (rs->buf, size, "qAttached");
1731
1732   putpkt (rs->buf);
1733   getpkt (&rs->buf, &rs->buf_size, 0);
1734
1735   switch (packet_ok (rs->buf,
1736                      &remote_protocol_packets[PACKET_qAttached]))
1737     {
1738     case PACKET_OK:
1739       if (strcmp (rs->buf, "1") == 0)
1740         return 1;
1741       break;
1742     case PACKET_ERROR:
1743       warning (_("Remote failure reply: %s"), rs->buf);
1744       break;
1745     case PACKET_UNKNOWN:
1746       break;
1747     }
1748
1749   return 0;
1750 }
1751
1752 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
1753    has been invented by GDB, instead of reported by the target.  Since
1754    we can be connected to a remote system before before knowing about
1755    any inferior, mark the target with execution when we find the first
1756    inferior.  If ATTACHED is 1, then we had just attached to this
1757    inferior.  If it is 0, then we just created this inferior.  If it
1758    is -1, then try querying the remote stub to find out if it had
1759    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
1760    attempt to open this inferior's executable as the main executable
1761    if no main executable is open already.  */
1762
1763 static struct inferior *
1764 remote_add_inferior (int fake_pid_p, int pid, int attached,
1765                      int try_open_exec)
1766 {
1767   struct inferior *inf;
1768
1769   /* Check whether this process we're learning about is to be
1770      considered attached, or if is to be considered to have been
1771      spawned by the stub.  */
1772   if (attached == -1)
1773     attached = remote_query_attached (pid);
1774
1775   if (gdbarch_has_global_solist (target_gdbarch ()))
1776     {
1777       /* If the target shares code across all inferiors, then every
1778          attach adds a new inferior.  */
1779       inf = add_inferior (pid);
1780
1781       /* ... and every inferior is bound to the same program space.
1782          However, each inferior may still have its own address
1783          space.  */
1784       inf->aspace = maybe_new_address_space ();
1785       inf->pspace = current_program_space;
1786     }
1787   else
1788     {
1789       /* In the traditional debugging scenario, there's a 1-1 match
1790          between program/address spaces.  We simply bind the inferior
1791          to the program space's address space.  */
1792       inf = current_inferior ();
1793       inferior_appeared (inf, pid);
1794     }
1795
1796   inf->attach_flag = attached;
1797   inf->fake_pid_p = fake_pid_p;
1798
1799   /* If no main executable is currently open then attempt to
1800      open the file that was executed to create this inferior.  */
1801   if (try_open_exec && get_exec_file (0) == NULL)
1802     exec_file_locate_attach (pid, 1);
1803
1804   return inf;
1805 }
1806
1807 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1808    according to RUNNING.  */
1809
1810 static void
1811 remote_add_thread (ptid_t ptid, int running, int executing)
1812 {
1813   struct remote_state *rs = get_remote_state ();
1814
1815   /* GDB historically didn't pull threads in the initial connection
1816      setup.  If the remote target doesn't even have a concept of
1817      threads (e.g., a bare-metal target), even if internally we
1818      consider that a single-threaded target, mentioning a new thread
1819      might be confusing to the user.  Be silent then, preserving the
1820      age old behavior.  */
1821   if (rs->starting_up)
1822     add_thread_silent (ptid);
1823   else
1824     add_thread (ptid);
1825
1826   set_executing (ptid, executing);
1827   set_running (ptid, running);
1828 }
1829
1830 /* Come here when we learn about a thread id from the remote target.
1831    It may be the first time we hear about such thread, so take the
1832    opportunity to add it to GDB's thread list.  In case this is the
1833    first time we're noticing its corresponding inferior, add it to
1834    GDB's inferior list as well.  EXECUTING indicates whether the
1835    thread is (internally) executing or stopped.  */
1836
1837 static void
1838 remote_notice_new_inferior (ptid_t currthread, int executing)
1839 {
1840   /* In non-stop mode, we assume new found threads are (externally)
1841      running until proven otherwise with a stop reply.  In all-stop,
1842      we can only get here if all threads are stopped.  */
1843   int running = target_is_non_stop_p () ? 1 : 0;
1844
1845   /* If this is a new thread, add it to GDB's thread list.
1846      If we leave it up to WFI to do this, bad things will happen.  */
1847
1848   if (in_thread_list (currthread) && is_exited (currthread))
1849     {
1850       /* We're seeing an event on a thread id we knew had exited.
1851          This has to be a new thread reusing the old id.  Add it.  */
1852       remote_add_thread (currthread, running, executing);
1853       return;
1854     }
1855
1856   if (!in_thread_list (currthread))
1857     {
1858       struct inferior *inf = NULL;
1859       int pid = ptid_get_pid (currthread);
1860
1861       if (ptid_is_pid (inferior_ptid)
1862           && pid == ptid_get_pid (inferior_ptid))
1863         {
1864           /* inferior_ptid has no thread member yet.  This can happen
1865              with the vAttach -> remote_wait,"TAAthread:" path if the
1866              stub doesn't support qC.  This is the first stop reported
1867              after an attach, so this is the main thread.  Update the
1868              ptid in the thread list.  */
1869           if (in_thread_list (pid_to_ptid (pid)))
1870             thread_change_ptid (inferior_ptid, currthread);
1871           else
1872             {
1873               remote_add_thread (currthread, running, executing);
1874               inferior_ptid = currthread;
1875             }
1876           return;
1877         }
1878
1879       if (ptid_equal (magic_null_ptid, inferior_ptid))
1880         {
1881           /* inferior_ptid is not set yet.  This can happen with the
1882              vRun -> remote_wait,"TAAthread:" path if the stub
1883              doesn't support qC.  This is the first stop reported
1884              after an attach, so this is the main thread.  Update the
1885              ptid in the thread list.  */
1886           thread_change_ptid (inferior_ptid, currthread);
1887           return;
1888         }
1889
1890       /* When connecting to a target remote, or to a target
1891          extended-remote which already was debugging an inferior, we
1892          may not know about it yet.  Add it before adding its child
1893          thread, so notifications are emitted in a sensible order.  */
1894       if (!in_inferior_list (ptid_get_pid (currthread)))
1895         {
1896           struct remote_state *rs = get_remote_state ();
1897           int fake_pid_p = !remote_multi_process_p (rs);
1898
1899           inf = remote_add_inferior (fake_pid_p,
1900                                      ptid_get_pid (currthread), -1, 1);
1901         }
1902
1903       /* This is really a new thread.  Add it.  */
1904       remote_add_thread (currthread, running, executing);
1905
1906       /* If we found a new inferior, let the common code do whatever
1907          it needs to with it (e.g., read shared libraries, insert
1908          breakpoints), unless we're just setting up an all-stop
1909          connection.  */
1910       if (inf != NULL)
1911         {
1912           struct remote_state *rs = get_remote_state ();
1913
1914           if (!rs->starting_up)
1915             notice_new_inferior (currthread, executing, 0);
1916         }
1917     }
1918 }
1919
1920 /* Return the private thread data, creating it if necessary.  */
1921
1922 static struct private_thread_info *
1923 demand_private_info (ptid_t ptid)
1924 {
1925   struct thread_info *info = find_thread_ptid (ptid);
1926
1927   gdb_assert (info);
1928
1929   if (!info->priv)
1930     {
1931       info->priv = XNEW (struct private_thread_info);
1932       info->private_dtor = free_private_thread_info;
1933       info->priv->core = -1;
1934       info->priv->extra = NULL;
1935       info->priv->name = NULL;
1936     }
1937
1938   return info->priv;
1939 }
1940
1941 /* Call this function as a result of
1942    1) A halt indication (T packet) containing a thread id
1943    2) A direct query of currthread
1944    3) Successful execution of set thread */
1945
1946 static void
1947 record_currthread (struct remote_state *rs, ptid_t currthread)
1948 {
1949   rs->general_thread = currthread;
1950 }
1951
1952 /* If 'QPassSignals' is supported, tell the remote stub what signals
1953    it can simply pass through to the inferior without reporting.  */
1954
1955 static void
1956 remote_pass_signals (struct target_ops *self,
1957                      int numsigs, unsigned char *pass_signals)
1958 {
1959   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1960     {
1961       char *pass_packet, *p;
1962       int count = 0, i;
1963       struct remote_state *rs = get_remote_state ();
1964
1965       gdb_assert (numsigs < 256);
1966       for (i = 0; i < numsigs; i++)
1967         {
1968           if (pass_signals[i])
1969             count++;
1970         }
1971       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1972       strcpy (pass_packet, "QPassSignals:");
1973       p = pass_packet + strlen (pass_packet);
1974       for (i = 0; i < numsigs; i++)
1975         {
1976           if (pass_signals[i])
1977             {
1978               if (i >= 16)
1979                 *p++ = tohex (i >> 4);
1980               *p++ = tohex (i & 15);
1981               if (count)
1982                 *p++ = ';';
1983               else
1984                 break;
1985               count--;
1986             }
1987         }
1988       *p = 0;
1989       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1990         {
1991           putpkt (pass_packet);
1992           getpkt (&rs->buf, &rs->buf_size, 0);
1993           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1994           if (rs->last_pass_packet)
1995             xfree (rs->last_pass_packet);
1996           rs->last_pass_packet = pass_packet;
1997         }
1998       else
1999         xfree (pass_packet);
2000     }
2001 }
2002
2003 /* If 'QCatchSyscalls' is supported, tell the remote stub
2004    to report syscalls to GDB.  */
2005
2006 static int
2007 remote_set_syscall_catchpoint (struct target_ops *self,
2008                                int pid, int needed, int any_count,
2009                                int table_size, int *table)
2010 {
2011   char *catch_packet;
2012   enum packet_result result;
2013   int n_sysno = 0;
2014
2015   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2016     {
2017       /* Not supported.  */
2018       return 1;
2019     }
2020
2021   if (needed && !any_count)
2022     {
2023       int i;
2024
2025       /* Count how many syscalls are to be caught (table[sysno] != 0).  */
2026       for (i = 0; i < table_size; i++)
2027         {
2028           if (table[i] != 0)
2029             n_sysno++;
2030         }
2031     }
2032
2033   if (remote_debug)
2034     {
2035       fprintf_unfiltered (gdb_stdlog,
2036                           "remote_set_syscall_catchpoint "
2037                           "pid %d needed %d any_count %d n_sysno %d\n",
2038                           pid, needed, any_count, n_sysno);
2039     }
2040
2041   if (needed)
2042     {
2043       /* Prepare a packet with the sysno list, assuming max 8+1
2044          characters for a sysno.  If the resulting packet size is too
2045          big, fallback on the non-selective packet.  */
2046       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2047
2048       catch_packet = (char *) xmalloc (maxpktsz);
2049       strcpy (catch_packet, "QCatchSyscalls:1");
2050       if (!any_count)
2051         {
2052           int i;
2053           char *p;
2054
2055           p = catch_packet;
2056           p += strlen (p);
2057
2058           /* Add in catch_packet each syscall to be caught (table[i] != 0).  */
2059           for (i = 0; i < table_size; i++)
2060             {
2061               if (table[i] != 0)
2062                 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2063             }
2064         }
2065       if (strlen (catch_packet) > get_remote_packet_size ())
2066         {
2067           /* catch_packet too big.  Fallback to less efficient
2068              non selective mode, with GDB doing the filtering.  */
2069           catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2070         }
2071     }
2072   else
2073     catch_packet = xstrdup ("QCatchSyscalls:0");
2074
2075   {
2076     struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2077     struct remote_state *rs = get_remote_state ();
2078
2079     putpkt (catch_packet);
2080     getpkt (&rs->buf, &rs->buf_size, 0);
2081     result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2082     do_cleanups (old_chain);
2083     if (result == PACKET_OK)
2084       return 0;
2085     else
2086       return -1;
2087   }
2088 }
2089
2090 /* If 'QProgramSignals' is supported, tell the remote stub what
2091    signals it should pass through to the inferior when detaching.  */
2092
2093 static void
2094 remote_program_signals (struct target_ops *self,
2095                         int numsigs, unsigned char *signals)
2096 {
2097   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2098     {
2099       char *packet, *p;
2100       int count = 0, i;
2101       struct remote_state *rs = get_remote_state ();
2102
2103       gdb_assert (numsigs < 256);
2104       for (i = 0; i < numsigs; i++)
2105         {
2106           if (signals[i])
2107             count++;
2108         }
2109       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2110       strcpy (packet, "QProgramSignals:");
2111       p = packet + strlen (packet);
2112       for (i = 0; i < numsigs; i++)
2113         {
2114           if (signal_pass_state (i))
2115             {
2116               if (i >= 16)
2117                 *p++ = tohex (i >> 4);
2118               *p++ = tohex (i & 15);
2119               if (count)
2120                 *p++ = ';';
2121               else
2122                 break;
2123               count--;
2124             }
2125         }
2126       *p = 0;
2127       if (!rs->last_program_signals_packet
2128           || strcmp (rs->last_program_signals_packet, packet) != 0)
2129         {
2130           putpkt (packet);
2131           getpkt (&rs->buf, &rs->buf_size, 0);
2132           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2133           xfree (rs->last_program_signals_packet);
2134           rs->last_program_signals_packet = packet;
2135         }
2136       else
2137         xfree (packet);
2138     }
2139 }
2140
2141 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2142    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2143    thread.  If GEN is set, set the general thread, if not, then set
2144    the step/continue thread.  */
2145 static void
2146 set_thread (struct ptid ptid, int gen)
2147 {
2148   struct remote_state *rs = get_remote_state ();
2149   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2150   char *buf = rs->buf;
2151   char *endbuf = rs->buf + get_remote_packet_size ();
2152
2153   if (ptid_equal (state, ptid))
2154     return;
2155
2156   *buf++ = 'H';
2157   *buf++ = gen ? 'g' : 'c';
2158   if (ptid_equal (ptid, magic_null_ptid))
2159     xsnprintf (buf, endbuf - buf, "0");
2160   else if (ptid_equal (ptid, any_thread_ptid))
2161     xsnprintf (buf, endbuf - buf, "0");
2162   else if (ptid_equal (ptid, minus_one_ptid))
2163     xsnprintf (buf, endbuf - buf, "-1");
2164   else
2165     write_ptid (buf, endbuf, ptid);
2166   putpkt (rs->buf);
2167   getpkt (&rs->buf, &rs->buf_size, 0);
2168   if (gen)
2169     rs->general_thread = ptid;
2170   else
2171     rs->continue_thread = ptid;
2172 }
2173
2174 static void
2175 set_general_thread (struct ptid ptid)
2176 {
2177   set_thread (ptid, 1);
2178 }
2179
2180 static void
2181 set_continue_thread (struct ptid ptid)
2182 {
2183   set_thread (ptid, 0);
2184 }
2185
2186 /* Change the remote current process.  Which thread within the process
2187    ends up selected isn't important, as long as it is the same process
2188    as what INFERIOR_PTID points to.
2189
2190    This comes from that fact that there is no explicit notion of
2191    "selected process" in the protocol.  The selected process for
2192    general operations is the process the selected general thread
2193    belongs to.  */
2194
2195 static void
2196 set_general_process (void)
2197 {
2198   struct remote_state *rs = get_remote_state ();
2199
2200   /* If the remote can't handle multiple processes, don't bother.  */
2201   if (!remote_multi_process_p (rs))
2202     return;
2203
2204   /* We only need to change the remote current thread if it's pointing
2205      at some other process.  */
2206   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2207     set_general_thread (inferior_ptid);
2208 }
2209
2210 \f
2211 /* Return nonzero if this is the main thread that we made up ourselves
2212    to model non-threaded targets as single-threaded.  */
2213
2214 static int
2215 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2216 {
2217   if (ptid_equal (ptid, magic_null_ptid))
2218     /* The main thread is always alive.  */
2219     return 1;
2220
2221   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2222     /* The main thread is always alive.  This can happen after a
2223        vAttach, if the remote side doesn't support
2224        multi-threading.  */
2225     return 1;
2226
2227   return 0;
2228 }
2229
2230 /* Return nonzero if the thread PTID is still alive on the remote
2231    system.  */
2232
2233 static int
2234 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2235 {
2236   struct remote_state *rs = get_remote_state ();
2237   char *p, *endp;
2238
2239   /* Check if this is a thread that we made up ourselves to model
2240      non-threaded targets as single-threaded.  */
2241   if (remote_thread_always_alive (ops, ptid))
2242     return 1;
2243
2244   p = rs->buf;
2245   endp = rs->buf + get_remote_packet_size ();
2246
2247   *p++ = 'T';
2248   write_ptid (p, endp, ptid);
2249
2250   putpkt (rs->buf);
2251   getpkt (&rs->buf, &rs->buf_size, 0);
2252   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2253 }
2254
2255 /* Return a pointer to a thread name if we know it and NULL otherwise.
2256    The thread_info object owns the memory for the name.  */
2257
2258 static const char *
2259 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2260 {
2261   if (info->priv != NULL)
2262     return info->priv->name;
2263
2264   return NULL;
2265 }
2266
2267 /* About these extended threadlist and threadinfo packets.  They are
2268    variable length packets but, the fields within them are often fixed
2269    length.  They are redundent enough to send over UDP as is the
2270    remote protocol in general.  There is a matching unit test module
2271    in libstub.  */
2272
2273 /* WARNING: This threadref data structure comes from the remote O.S.,
2274    libstub protocol encoding, and remote.c.  It is not particularly
2275    changable.  */
2276
2277 /* Right now, the internal structure is int. We want it to be bigger.
2278    Plan to fix this.  */
2279
2280 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2281
2282 /* gdb_ext_thread_info is an internal GDB data structure which is
2283    equivalent to the reply of the remote threadinfo packet.  */
2284
2285 struct gdb_ext_thread_info
2286   {
2287     threadref threadid;         /* External form of thread reference.  */
2288     int active;                 /* Has state interesting to GDB?
2289                                    regs, stack.  */
2290     char display[256];          /* Brief state display, name,
2291                                    blocked/suspended.  */
2292     char shortname[32];         /* To be used to name threads.  */
2293     char more_display[256];     /* Long info, statistics, queue depth,
2294                                    whatever.  */
2295   };
2296
2297 /* The volume of remote transfers can be limited by submitting
2298    a mask containing bits specifying the desired information.
2299    Use a union of these values as the 'selection' parameter to
2300    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2301
2302 #define TAG_THREADID 1
2303 #define TAG_EXISTS 2
2304 #define TAG_DISPLAY 4
2305 #define TAG_THREADNAME 8
2306 #define TAG_MOREDISPLAY 16
2307
2308 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2309
2310 static char *unpack_nibble (char *buf, int *val);
2311
2312 static char *unpack_byte (char *buf, int *value);
2313
2314 static char *pack_int (char *buf, int value);
2315
2316 static char *unpack_int (char *buf, int *value);
2317
2318 static char *unpack_string (char *src, char *dest, int length);
2319
2320 static char *pack_threadid (char *pkt, threadref *id);
2321
2322 static char *unpack_threadid (char *inbuf, threadref *id);
2323
2324 void int_to_threadref (threadref *id, int value);
2325
2326 static int threadref_to_int (threadref *ref);
2327
2328 static void copy_threadref (threadref *dest, threadref *src);
2329
2330 static int threadmatch (threadref *dest, threadref *src);
2331
2332 static char *pack_threadinfo_request (char *pkt, int mode,
2333                                       threadref *id);
2334
2335 static int remote_unpack_thread_info_response (char *pkt,
2336                                                threadref *expectedref,
2337                                                struct gdb_ext_thread_info
2338                                                *info);
2339
2340
2341 static int remote_get_threadinfo (threadref *threadid,
2342                                   int fieldset, /*TAG mask */
2343                                   struct gdb_ext_thread_info *info);
2344
2345 static char *pack_threadlist_request (char *pkt, int startflag,
2346                                       int threadcount,
2347                                       threadref *nextthread);
2348
2349 static int parse_threadlist_response (char *pkt,
2350                                       int result_limit,
2351                                       threadref *original_echo,
2352                                       threadref *resultlist,
2353                                       int *doneflag);
2354
2355 static int remote_get_threadlist (int startflag,
2356                                   threadref *nextthread,
2357                                   int result_limit,
2358                                   int *done,
2359                                   int *result_count,
2360                                   threadref *threadlist);
2361
2362 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2363
2364 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2365                                        void *context, int looplimit);
2366
2367 static int remote_newthread_step (threadref *ref, void *context);
2368
2369
2370 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2371    buffer we're allowed to write to.  Returns
2372    BUF+CHARACTERS_WRITTEN.  */
2373
2374 static char *
2375 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2376 {
2377   int pid, tid;
2378   struct remote_state *rs = get_remote_state ();
2379
2380   if (remote_multi_process_p (rs))
2381     {
2382       pid = ptid_get_pid (ptid);
2383       if (pid < 0)
2384         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2385       else
2386         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2387     }
2388   tid = ptid_get_lwp (ptid);
2389   if (tid < 0)
2390     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2391   else
2392     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2393
2394   return buf;
2395 }
2396
2397 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
2398    passed the last parsed char.  Returns null_ptid on error.  */
2399
2400 static ptid_t
2401 read_ptid (char *buf, char **obuf)
2402 {
2403   char *p = buf;
2404   char *pp;
2405   ULONGEST pid = 0, tid = 0;
2406
2407   if (*p == 'p')
2408     {
2409       /* Multi-process ptid.  */
2410       pp = unpack_varlen_hex (p + 1, &pid);
2411       if (*pp != '.')
2412         error (_("invalid remote ptid: %s"), p);
2413
2414       p = pp;
2415       pp = unpack_varlen_hex (p + 1, &tid);
2416       if (obuf)
2417         *obuf = pp;
2418       return ptid_build (pid, tid, 0);
2419     }
2420
2421   /* No multi-process.  Just a tid.  */
2422   pp = unpack_varlen_hex (p, &tid);
2423
2424   /* Return null_ptid when no thread id is found.  */
2425   if (p == pp)
2426     {
2427       if (obuf)
2428         *obuf = pp;
2429       return null_ptid;
2430     }
2431
2432   /* Since the stub is not sending a process id, then default to
2433      what's in inferior_ptid, unless it's null at this point.  If so,
2434      then since there's no way to know the pid of the reported
2435      threads, use the magic number.  */
2436   if (ptid_equal (inferior_ptid, null_ptid))
2437     pid = ptid_get_pid (magic_null_ptid);
2438   else
2439     pid = ptid_get_pid (inferior_ptid);
2440
2441   if (obuf)
2442     *obuf = pp;
2443   return ptid_build (pid, tid, 0);
2444 }
2445
2446 static int
2447 stubhex (int ch)
2448 {
2449   if (ch >= 'a' && ch <= 'f')
2450     return ch - 'a' + 10;
2451   if (ch >= '0' && ch <= '9')
2452     return ch - '0';
2453   if (ch >= 'A' && ch <= 'F')
2454     return ch - 'A' + 10;
2455   return -1;
2456 }
2457
2458 static int
2459 stub_unpack_int (char *buff, int fieldlength)
2460 {
2461   int nibble;
2462   int retval = 0;
2463
2464   while (fieldlength)
2465     {
2466       nibble = stubhex (*buff++);
2467       retval |= nibble;
2468       fieldlength--;
2469       if (fieldlength)
2470         retval = retval << 4;
2471     }
2472   return retval;
2473 }
2474
2475 static char *
2476 unpack_nibble (char *buf, int *val)
2477 {
2478   *val = fromhex (*buf++);
2479   return buf;
2480 }
2481
2482 static char *
2483 unpack_byte (char *buf, int *value)
2484 {
2485   *value = stub_unpack_int (buf, 2);
2486   return buf + 2;
2487 }
2488
2489 static char *
2490 pack_int (char *buf, int value)
2491 {
2492   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2493   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2494   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2495   buf = pack_hex_byte (buf, (value & 0xff));
2496   return buf;
2497 }
2498
2499 static char *
2500 unpack_int (char *buf, int *value)
2501 {
2502   *value = stub_unpack_int (buf, 8);
2503   return buf + 8;
2504 }
2505
2506 #if 0                   /* Currently unused, uncomment when needed.  */
2507 static char *pack_string (char *pkt, char *string);
2508
2509 static char *
2510 pack_string (char *pkt, char *string)
2511 {
2512   char ch;
2513   int len;
2514
2515   len = strlen (string);
2516   if (len > 200)
2517     len = 200;          /* Bigger than most GDB packets, junk???  */
2518   pkt = pack_hex_byte (pkt, len);
2519   while (len-- > 0)
2520     {
2521       ch = *string++;
2522       if ((ch == '\0') || (ch == '#'))
2523         ch = '*';               /* Protect encapsulation.  */
2524       *pkt++ = ch;
2525     }
2526   return pkt;
2527 }
2528 #endif /* 0 (unused) */
2529
2530 static char *
2531 unpack_string (char *src, char *dest, int length)
2532 {
2533   while (length--)
2534     *dest++ = *src++;
2535   *dest = '\0';
2536   return src;
2537 }
2538
2539 static char *
2540 pack_threadid (char *pkt, threadref *id)
2541 {
2542   char *limit;
2543   unsigned char *altid;
2544
2545   altid = (unsigned char *) id;
2546   limit = pkt + BUF_THREAD_ID_SIZE;
2547   while (pkt < limit)
2548     pkt = pack_hex_byte (pkt, *altid++);
2549   return pkt;
2550 }
2551
2552
2553 static char *
2554 unpack_threadid (char *inbuf, threadref *id)
2555 {
2556   char *altref;
2557   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2558   int x, y;
2559
2560   altref = (char *) id;
2561
2562   while (inbuf < limit)
2563     {
2564       x = stubhex (*inbuf++);
2565       y = stubhex (*inbuf++);
2566       *altref++ = (x << 4) | y;
2567     }
2568   return inbuf;
2569 }
2570
2571 /* Externally, threadrefs are 64 bits but internally, they are still
2572    ints.  This is due to a mismatch of specifications.  We would like
2573    to use 64bit thread references internally.  This is an adapter
2574    function.  */
2575
2576 void
2577 int_to_threadref (threadref *id, int value)
2578 {
2579   unsigned char *scan;
2580
2581   scan = (unsigned char *) id;
2582   {
2583     int i = 4;
2584     while (i--)
2585       *scan++ = 0;
2586   }
2587   *scan++ = (value >> 24) & 0xff;
2588   *scan++ = (value >> 16) & 0xff;
2589   *scan++ = (value >> 8) & 0xff;
2590   *scan++ = (value & 0xff);
2591 }
2592
2593 static int
2594 threadref_to_int (threadref *ref)
2595 {
2596   int i, value = 0;
2597   unsigned char *scan;
2598
2599   scan = *ref;
2600   scan += 4;
2601   i = 4;
2602   while (i-- > 0)
2603     value = (value << 8) | ((*scan++) & 0xff);
2604   return value;
2605 }
2606
2607 static void
2608 copy_threadref (threadref *dest, threadref *src)
2609 {
2610   int i;
2611   unsigned char *csrc, *cdest;
2612
2613   csrc = (unsigned char *) src;
2614   cdest = (unsigned char *) dest;
2615   i = 8;
2616   while (i--)
2617     *cdest++ = *csrc++;
2618 }
2619
2620 static int
2621 threadmatch (threadref *dest, threadref *src)
2622 {
2623   /* Things are broken right now, so just assume we got a match.  */
2624 #if 0
2625   unsigned char *srcp, *destp;
2626   int i, result;
2627   srcp = (char *) src;
2628   destp = (char *) dest;
2629
2630   result = 1;
2631   while (i-- > 0)
2632     result &= (*srcp++ == *destp++) ? 1 : 0;
2633   return result;
2634 #endif
2635   return 1;
2636 }
2637
2638 /*
2639    threadid:1,        # always request threadid
2640    context_exists:2,
2641    display:4,
2642    unique_name:8,
2643    more_display:16
2644  */
2645
2646 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2647
2648 static char *
2649 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2650 {
2651   *pkt++ = 'q';                         /* Info Query */
2652   *pkt++ = 'P';                         /* process or thread info */
2653   pkt = pack_int (pkt, mode);           /* mode */
2654   pkt = pack_threadid (pkt, id);        /* threadid */
2655   *pkt = '\0';                          /* terminate */
2656   return pkt;
2657 }
2658
2659 /* These values tag the fields in a thread info response packet.  */
2660 /* Tagging the fields allows us to request specific fields and to
2661    add more fields as time goes by.  */
2662
2663 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2664 #define TAG_EXISTS 2            /* Is this process defined enough to
2665                                    fetch registers and its stack?  */
2666 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2667 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2668 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2669                                    the process.  */
2670
2671 static int
2672 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2673                                     struct gdb_ext_thread_info *info)
2674 {
2675   struct remote_state *rs = get_remote_state ();
2676   int mask, length;
2677   int tag;
2678   threadref ref;
2679   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2680   int retval = 1;
2681
2682   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2683   info->active = 0;
2684   info->display[0] = '\0';
2685   info->shortname[0] = '\0';
2686   info->more_display[0] = '\0';
2687
2688   /* Assume the characters indicating the packet type have been
2689      stripped.  */
2690   pkt = unpack_int (pkt, &mask);        /* arg mask */
2691   pkt = unpack_threadid (pkt, &ref);
2692
2693   if (mask == 0)
2694     warning (_("Incomplete response to threadinfo request."));
2695   if (!threadmatch (&ref, expectedref))
2696     {                   /* This is an answer to a different request.  */
2697       warning (_("ERROR RMT Thread info mismatch."));
2698       return 0;
2699     }
2700   copy_threadref (&info->threadid, &ref);
2701
2702   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
2703
2704   /* Packets are terminated with nulls.  */
2705   while ((pkt < limit) && mask && *pkt)
2706     {
2707       pkt = unpack_int (pkt, &tag);     /* tag */
2708       pkt = unpack_byte (pkt, &length); /* length */
2709       if (!(tag & mask))                /* Tags out of synch with mask.  */
2710         {
2711           warning (_("ERROR RMT: threadinfo tag mismatch."));
2712           retval = 0;
2713           break;
2714         }
2715       if (tag == TAG_THREADID)
2716         {
2717           if (length != 16)
2718             {
2719               warning (_("ERROR RMT: length of threadid is not 16."));
2720               retval = 0;
2721               break;
2722             }
2723           pkt = unpack_threadid (pkt, &ref);
2724           mask = mask & ~TAG_THREADID;
2725           continue;
2726         }
2727       if (tag == TAG_EXISTS)
2728         {
2729           info->active = stub_unpack_int (pkt, length);
2730           pkt += length;
2731           mask = mask & ~(TAG_EXISTS);
2732           if (length > 8)
2733             {
2734               warning (_("ERROR RMT: 'exists' length too long."));
2735               retval = 0;
2736               break;
2737             }
2738           continue;
2739         }
2740       if (tag == TAG_THREADNAME)
2741         {
2742           pkt = unpack_string (pkt, &info->shortname[0], length);
2743           mask = mask & ~TAG_THREADNAME;
2744           continue;
2745         }
2746       if (tag == TAG_DISPLAY)
2747         {
2748           pkt = unpack_string (pkt, &info->display[0], length);
2749           mask = mask & ~TAG_DISPLAY;
2750           continue;
2751         }
2752       if (tag == TAG_MOREDISPLAY)
2753         {
2754           pkt = unpack_string (pkt, &info->more_display[0], length);
2755           mask = mask & ~TAG_MOREDISPLAY;
2756           continue;
2757         }
2758       warning (_("ERROR RMT: unknown thread info tag."));
2759       break;                    /* Not a tag we know about.  */
2760     }
2761   return retval;
2762 }
2763
2764 static int
2765 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2766                        struct gdb_ext_thread_info *info)
2767 {
2768   struct remote_state *rs = get_remote_state ();
2769   int result;
2770
2771   pack_threadinfo_request (rs->buf, fieldset, threadid);
2772   putpkt (rs->buf);
2773   getpkt (&rs->buf, &rs->buf_size, 0);
2774
2775   if (rs->buf[0] == '\0')
2776     return 0;
2777
2778   result = remote_unpack_thread_info_response (rs->buf + 2,
2779                                                threadid, info);
2780   return result;
2781 }
2782
2783 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2784
2785 static char *
2786 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2787                          threadref *nextthread)
2788 {
2789   *pkt++ = 'q';                 /* info query packet */
2790   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2791   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2792   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2793   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2794   *pkt = '\0';
2795   return pkt;
2796 }
2797
2798 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2799
2800 static int
2801 parse_threadlist_response (char *pkt, int result_limit,
2802                            threadref *original_echo, threadref *resultlist,
2803                            int *doneflag)
2804 {
2805   struct remote_state *rs = get_remote_state ();
2806   char *limit;
2807   int count, resultcount, done;
2808
2809   resultcount = 0;
2810   /* Assume the 'q' and 'M chars have been stripped.  */
2811   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2812   /* done parse past here */
2813   pkt = unpack_byte (pkt, &count);      /* count field */
2814   pkt = unpack_nibble (pkt, &done);
2815   /* The first threadid is the argument threadid.  */
2816   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2817   while ((count-- > 0) && (pkt < limit))
2818     {
2819       pkt = unpack_threadid (pkt, resultlist++);
2820       if (resultcount++ >= result_limit)
2821         break;
2822     }
2823   if (doneflag)
2824     *doneflag = done;
2825   return resultcount;
2826 }
2827
2828 /* Fetch the next batch of threads from the remote.  Returns -1 if the
2829    qL packet is not supported, 0 on error and 1 on success.  */
2830
2831 static int
2832 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2833                        int *done, int *result_count, threadref *threadlist)
2834 {
2835   struct remote_state *rs = get_remote_state ();
2836   int result = 1;
2837
2838   /* Trancate result limit to be smaller than the packet size.  */
2839   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2840       >= get_remote_packet_size ())
2841     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2842
2843   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2844   putpkt (rs->buf);
2845   getpkt (&rs->buf, &rs->buf_size, 0);
2846   if (*rs->buf == '\0')
2847     {
2848       /* Packet not supported.  */
2849       return -1;
2850     }
2851
2852   *result_count =
2853     parse_threadlist_response (rs->buf + 2, result_limit,
2854                                &rs->echo_nextthread, threadlist, done);
2855
2856   if (!threadmatch (&rs->echo_nextthread, nextthread))
2857     {
2858       /* FIXME: This is a good reason to drop the packet.  */
2859       /* Possably, there is a duplicate response.  */
2860       /* Possabilities :
2861          retransmit immediatly - race conditions
2862          retransmit after timeout - yes
2863          exit
2864          wait for packet, then exit
2865        */
2866       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2867       return 0;                 /* I choose simply exiting.  */
2868     }
2869   if (*result_count <= 0)
2870     {
2871       if (*done != 1)
2872         {
2873           warning (_("RMT ERROR : failed to get remote thread list."));
2874           result = 0;
2875         }
2876       return result;            /* break; */
2877     }
2878   if (*result_count > result_limit)
2879     {
2880       *result_count = 0;
2881       warning (_("RMT ERROR: threadlist response longer than requested."));
2882       return 0;
2883     }
2884   return result;
2885 }
2886
2887 /* Fetch the list of remote threads, with the qL packet, and call
2888    STEPFUNCTION for each thread found.  Stops iterating and returns 1
2889    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
2890    STEPFUNCTION returns false.  If the packet is not supported,
2891    returns -1.  */
2892
2893 static int
2894 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2895                             int looplimit)
2896 {
2897   struct remote_state *rs = get_remote_state ();
2898   int done, i, result_count;
2899   int startflag = 1;
2900   int result = 1;
2901   int loopcount = 0;
2902
2903   done = 0;
2904   while (!done)
2905     {
2906       if (loopcount++ > looplimit)
2907         {
2908           result = 0;
2909           warning (_("Remote fetch threadlist -infinite loop-."));
2910           break;
2911         }
2912       result = remote_get_threadlist (startflag, &rs->nextthread,
2913                                       MAXTHREADLISTRESULTS,
2914                                       &done, &result_count,
2915                                       rs->resultthreadlist);
2916       if (result <= 0)
2917         break;
2918       /* Clear for later iterations.  */
2919       startflag = 0;
2920       /* Setup to resume next batch of thread references, set nextthread.  */
2921       if (result_count >= 1)
2922         copy_threadref (&rs->nextthread,
2923                         &rs->resultthreadlist[result_count - 1]);
2924       i = 0;
2925       while (result_count--)
2926         {
2927           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2928             {
2929               result = 0;
2930               break;
2931             }
2932         }
2933     }
2934   return result;
2935 }
2936
2937 /* A thread found on the remote target.  */
2938
2939 typedef struct thread_item
2940 {
2941   /* The thread's PTID.  */
2942   ptid_t ptid;
2943
2944   /* The thread's extra info.  May be NULL.  */
2945   char *extra;
2946
2947   /* The thread's name.  May be NULL.  */
2948   char *name;
2949
2950   /* The core the thread was running on.  -1 if not known.  */
2951   int core;
2952 } thread_item_t;
2953 DEF_VEC_O(thread_item_t);
2954
2955 /* Context passed around to the various methods listing remote
2956    threads.  As new threads are found, they're added to the ITEMS
2957    vector.  */
2958
2959 struct threads_listing_context
2960 {
2961   /* The threads found on the remote target.  */
2962   VEC (thread_item_t) *items;
2963 };
2964
2965 /* Discard the contents of the constructed thread listing context.  */
2966
2967 static void
2968 clear_threads_listing_context (void *p)
2969 {
2970   struct threads_listing_context *context
2971     = (struct threads_listing_context *) p;
2972   int i;
2973   struct thread_item *item;
2974
2975   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2976     {
2977       xfree (item->extra);
2978       xfree (item->name);
2979     }
2980
2981   VEC_free (thread_item_t, context->items);
2982 }
2983
2984 /* Remove the thread specified as the related_pid field of WS
2985    from the CONTEXT list.  */
2986
2987 static void
2988 threads_listing_context_remove (struct target_waitstatus *ws,
2989                                 struct threads_listing_context *context)
2990 {
2991   struct thread_item *item;
2992   int i;
2993   ptid_t child_ptid = ws->value.related_pid;
2994
2995   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2996     {
2997       if (ptid_equal (item->ptid, child_ptid))
2998         {
2999           VEC_ordered_remove (thread_item_t, context->items, i);
3000           break;
3001         }
3002     }
3003 }
3004
3005 static int
3006 remote_newthread_step (threadref *ref, void *data)
3007 {
3008   struct threads_listing_context *context
3009     = (struct threads_listing_context *) data;
3010   struct thread_item item;
3011   int pid = ptid_get_pid (inferior_ptid);
3012
3013   item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3014   item.core = -1;
3015   item.name = NULL;
3016   item.extra = NULL;
3017
3018   VEC_safe_push (thread_item_t, context->items, &item);
3019
3020   return 1;                     /* continue iterator */
3021 }
3022
3023 #define CRAZY_MAX_THREADS 1000
3024
3025 static ptid_t
3026 remote_current_thread (ptid_t oldpid)
3027 {
3028   struct remote_state *rs = get_remote_state ();
3029
3030   putpkt ("qC");
3031   getpkt (&rs->buf, &rs->buf_size, 0);
3032   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3033     {
3034       char *obuf;
3035       ptid_t result;
3036
3037       result = read_ptid (&rs->buf[2], &obuf);
3038       if (*obuf != '\0' && remote_debug)
3039         fprintf_unfiltered (gdb_stdlog,
3040                             "warning: garbage in qC reply\n");
3041
3042       return result;
3043     }
3044   else
3045     return oldpid;
3046 }
3047
3048 /* List remote threads using the deprecated qL packet.  */
3049
3050 static int
3051 remote_get_threads_with_ql (struct target_ops *ops,
3052                             struct threads_listing_context *context)
3053 {
3054   if (remote_threadlist_iterator (remote_newthread_step, context,
3055                                   CRAZY_MAX_THREADS) >= 0)
3056     return 1;
3057
3058   return 0;
3059 }
3060
3061 #if defined(HAVE_LIBEXPAT)
3062
3063 static void
3064 start_thread (struct gdb_xml_parser *parser,
3065               const struct gdb_xml_element *element,
3066               void *user_data, VEC(gdb_xml_value_s) *attributes)
3067 {
3068   struct threads_listing_context *data
3069     = (struct threads_listing_context *) user_data;
3070
3071   struct thread_item item;
3072   char *id;
3073   struct gdb_xml_value *attr;
3074
3075   id = (char *) xml_find_attribute (attributes, "id")->value;
3076   item.ptid = read_ptid (id, NULL);
3077
3078   attr = xml_find_attribute (attributes, "core");
3079   if (attr != NULL)
3080     item.core = *(ULONGEST *) attr->value;
3081   else
3082     item.core = -1;
3083
3084   attr = xml_find_attribute (attributes, "name");
3085   item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3086
3087   item.extra = 0;
3088
3089   VEC_safe_push (thread_item_t, data->items, &item);
3090 }
3091
3092 static void
3093 end_thread (struct gdb_xml_parser *parser,
3094             const struct gdb_xml_element *element,
3095             void *user_data, const char *body_text)
3096 {
3097   struct threads_listing_context *data
3098     = (struct threads_listing_context *) user_data;
3099
3100   if (body_text && *body_text)
3101     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3102 }
3103
3104 const struct gdb_xml_attribute thread_attributes[] = {
3105   { "id", GDB_XML_AF_NONE, NULL, NULL },
3106   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3107   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3108   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3109 };
3110
3111 const struct gdb_xml_element thread_children[] = {
3112   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3113 };
3114
3115 const struct gdb_xml_element threads_children[] = {
3116   { "thread", thread_attributes, thread_children,
3117     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3118     start_thread, end_thread },
3119   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3120 };
3121
3122 const struct gdb_xml_element threads_elements[] = {
3123   { "threads", NULL, threads_children,
3124     GDB_XML_EF_NONE, NULL, NULL },
3125   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3126 };
3127
3128 #endif
3129
3130 /* List remote threads using qXfer:threads:read.  */
3131
3132 static int
3133 remote_get_threads_with_qxfer (struct target_ops *ops,
3134                                struct threads_listing_context *context)
3135 {
3136 #if defined(HAVE_LIBEXPAT)
3137   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3138     {
3139       char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3140       struct cleanup *back_to = make_cleanup (xfree, xml);
3141
3142       if (xml != NULL && *xml != '\0')
3143         {
3144           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3145                                threads_elements, xml, context);
3146         }
3147
3148       do_cleanups (back_to);
3149       return 1;
3150     }
3151 #endif
3152
3153   return 0;
3154 }
3155
3156 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3157
3158 static int
3159 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3160                                      struct threads_listing_context *context)
3161 {
3162   struct remote_state *rs = get_remote_state ();
3163
3164   if (rs->use_threadinfo_query)
3165     {
3166       char *bufp;
3167
3168       putpkt ("qfThreadInfo");
3169       getpkt (&rs->buf, &rs->buf_size, 0);
3170       bufp = rs->buf;
3171       if (bufp[0] != '\0')              /* q packet recognized */
3172         {
3173           while (*bufp++ == 'm')        /* reply contains one or more TID */
3174             {
3175               do
3176                 {
3177                   struct thread_item item;
3178
3179                   item.ptid = read_ptid (bufp, &bufp);
3180                   item.core = -1;
3181                   item.name = NULL;
3182                   item.extra = NULL;
3183
3184                   VEC_safe_push (thread_item_t, context->items, &item);
3185                 }
3186               while (*bufp++ == ',');   /* comma-separated list */
3187               putpkt ("qsThreadInfo");
3188               getpkt (&rs->buf, &rs->buf_size, 0);
3189               bufp = rs->buf;
3190             }
3191           return 1;
3192         }
3193       else
3194         {
3195           /* Packet not recognized.  */
3196           rs->use_threadinfo_query = 0;
3197         }
3198     }
3199
3200   return 0;
3201 }
3202
3203 /* Implement the to_update_thread_list function for the remote
3204    targets.  */
3205
3206 static void
3207 remote_update_thread_list (struct target_ops *ops)
3208 {
3209   struct threads_listing_context context;
3210   struct cleanup *old_chain;
3211   int got_list = 0;
3212
3213   context.items = NULL;
3214   old_chain = make_cleanup (clear_threads_listing_context, &context);
3215
3216   /* We have a few different mechanisms to fetch the thread list.  Try
3217      them all, starting with the most preferred one first, falling
3218      back to older methods.  */
3219   if (remote_get_threads_with_qxfer (ops, &context)
3220       || remote_get_threads_with_qthreadinfo (ops, &context)
3221       || remote_get_threads_with_ql (ops, &context))
3222     {
3223       int i;
3224       struct thread_item *item;
3225       struct thread_info *tp, *tmp;
3226
3227       got_list = 1;
3228
3229       if (VEC_empty (thread_item_t, context.items)
3230           && remote_thread_always_alive (ops, inferior_ptid))
3231         {
3232           /* Some targets don't really support threads, but still
3233              reply an (empty) thread list in response to the thread
3234              listing packets, instead of replying "packet not
3235              supported".  Exit early so we don't delete the main
3236              thread.  */
3237           do_cleanups (old_chain);
3238           return;
3239         }
3240
3241       /* CONTEXT now holds the current thread list on the remote
3242          target end.  Delete GDB-side threads no longer found on the
3243          target.  */
3244       ALL_THREADS_SAFE (tp, tmp)
3245         {
3246           for (i = 0;
3247                VEC_iterate (thread_item_t, context.items, i, item);
3248                ++i)
3249             {
3250               if (ptid_equal (item->ptid, tp->ptid))
3251                 break;
3252             }
3253
3254           if (i == VEC_length (thread_item_t, context.items))
3255             {
3256               /* Not found.  */
3257               delete_thread (tp->ptid);
3258             }
3259         }
3260
3261       /* Remove any unreported fork child threads from CONTEXT so
3262          that we don't interfere with follow fork, which is where
3263          creation of such threads is handled.  */
3264       remove_new_fork_children (&context);
3265
3266       /* And now add threads we don't know about yet to our list.  */
3267       for (i = 0;
3268            VEC_iterate (thread_item_t, context.items, i, item);
3269            ++i)
3270         {
3271           if (!ptid_equal (item->ptid, null_ptid))
3272             {
3273               struct private_thread_info *info;
3274               /* In non-stop mode, we assume new found threads are
3275                  executing until proven otherwise with a stop reply.
3276                  In all-stop, we can only get here if all threads are
3277                  stopped.  */
3278               int executing = target_is_non_stop_p () ? 1 : 0;
3279
3280               remote_notice_new_inferior (item->ptid, executing);
3281
3282               info = demand_private_info (item->ptid);
3283               info->core = item->core;
3284               info->extra = item->extra;
3285               item->extra = NULL;
3286               info->name = item->name;
3287               item->name = NULL;
3288             }
3289         }
3290     }
3291
3292   if (!got_list)
3293     {
3294       /* If no thread listing method is supported, then query whether
3295          each known thread is alive, one by one, with the T packet.
3296          If the target doesn't support threads at all, then this is a
3297          no-op.  See remote_thread_alive.  */
3298       prune_threads ();
3299     }
3300
3301   do_cleanups (old_chain);
3302 }
3303
3304 /*
3305  * Collect a descriptive string about the given thread.
3306  * The target may say anything it wants to about the thread
3307  * (typically info about its blocked / runnable state, name, etc.).
3308  * This string will appear in the info threads display.
3309  *
3310  * Optional: targets are not required to implement this function.
3311  */
3312
3313 static char *
3314 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3315 {
3316   struct remote_state *rs = get_remote_state ();
3317   int result;
3318   int set;
3319   threadref id;
3320   struct gdb_ext_thread_info threadinfo;
3321   static char display_buf[100]; /* arbitrary...  */
3322   int n = 0;                    /* position in display_buf */
3323
3324   if (rs->remote_desc == 0)             /* paranoia */
3325     internal_error (__FILE__, __LINE__,
3326                     _("remote_threads_extra_info"));
3327
3328   if (ptid_equal (tp->ptid, magic_null_ptid)
3329       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3330     /* This is the main thread which was added by GDB.  The remote
3331        server doesn't know about it.  */
3332     return NULL;
3333
3334   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3335     {
3336       struct thread_info *info = find_thread_ptid (tp->ptid);
3337
3338       if (info && info->priv)
3339         return info->priv->extra;
3340       else
3341         return NULL;
3342     }
3343
3344   if (rs->use_threadextra_query)
3345     {
3346       char *b = rs->buf;
3347       char *endb = rs->buf + get_remote_packet_size ();
3348
3349       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3350       b += strlen (b);
3351       write_ptid (b, endb, tp->ptid);
3352
3353       putpkt (rs->buf);
3354       getpkt (&rs->buf, &rs->buf_size, 0);
3355       if (rs->buf[0] != 0)
3356         {
3357           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3358           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3359           display_buf [result] = '\0';
3360           return display_buf;
3361         }
3362     }
3363
3364   /* If the above query fails, fall back to the old method.  */
3365   rs->use_threadextra_query = 0;
3366   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3367     | TAG_MOREDISPLAY | TAG_DISPLAY;
3368   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3369   if (remote_get_threadinfo (&id, set, &threadinfo))
3370     if (threadinfo.active)
3371       {
3372         if (*threadinfo.shortname)
3373           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3374                           " Name: %s,", threadinfo.shortname);
3375         if (*threadinfo.display)
3376           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3377                           " State: %s,", threadinfo.display);
3378         if (*threadinfo.more_display)
3379           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3380                           " Priority: %s", threadinfo.more_display);
3381
3382         if (n > 0)
3383           {
3384             /* For purely cosmetic reasons, clear up trailing commas.  */
3385             if (',' == display_buf[n-1])
3386               display_buf[n-1] = ' ';
3387             return display_buf;
3388           }
3389       }
3390   return NULL;
3391 }
3392 \f
3393
3394 static int
3395 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3396                                     struct static_tracepoint_marker *marker)
3397 {
3398   struct remote_state *rs = get_remote_state ();
3399   char *p = rs->buf;
3400
3401   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3402   p += strlen (p);
3403   p += hexnumstr (p, addr);
3404   putpkt (rs->buf);
3405   getpkt (&rs->buf, &rs->buf_size, 0);
3406   p = rs->buf;
3407
3408   if (*p == 'E')
3409     error (_("Remote failure reply: %s"), p);
3410
3411   if (*p++ == 'm')
3412     {
3413       parse_static_tracepoint_marker_definition (p, &p, marker);
3414       return 1;
3415     }
3416
3417   return 0;
3418 }
3419
3420 static VEC(static_tracepoint_marker_p) *
3421 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3422                                            const char *strid)
3423 {
3424   struct remote_state *rs = get_remote_state ();
3425   VEC(static_tracepoint_marker_p) *markers = NULL;
3426   struct static_tracepoint_marker *marker = NULL;
3427   struct cleanup *old_chain;
3428   char *p;
3429
3430   /* Ask for a first packet of static tracepoint marker
3431      definition.  */
3432   putpkt ("qTfSTM");
3433   getpkt (&rs->buf, &rs->buf_size, 0);
3434   p = rs->buf;
3435   if (*p == 'E')
3436     error (_("Remote failure reply: %s"), p);
3437
3438   old_chain = make_cleanup (free_current_marker, &marker);
3439
3440   while (*p++ == 'm')
3441     {
3442       if (marker == NULL)
3443         marker = XCNEW (struct static_tracepoint_marker);
3444
3445       do
3446         {
3447           parse_static_tracepoint_marker_definition (p, &p, marker);
3448
3449           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3450             {
3451               VEC_safe_push (static_tracepoint_marker_p,
3452                              markers, marker);
3453               marker = NULL;
3454             }
3455           else
3456             {
3457               release_static_tracepoint_marker (marker);
3458               memset (marker, 0, sizeof (*marker));
3459             }
3460         }
3461       while (*p++ == ',');      /* comma-separated list */
3462       /* Ask for another packet of static tracepoint definition.  */
3463       putpkt ("qTsSTM");
3464       getpkt (&rs->buf, &rs->buf_size, 0);
3465       p = rs->buf;
3466     }
3467
3468   do_cleanups (old_chain);
3469   return markers;
3470 }
3471
3472 \f
3473 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3474
3475 static ptid_t
3476 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3477 {
3478   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3479 }
3480 \f
3481
3482 /* Restart the remote side; this is an extended protocol operation.  */
3483
3484 static void
3485 extended_remote_restart (void)
3486 {
3487   struct remote_state *rs = get_remote_state ();
3488
3489   /* Send the restart command; for reasons I don't understand the
3490      remote side really expects a number after the "R".  */
3491   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3492   putpkt (rs->buf);
3493
3494   remote_fileio_reset ();
3495 }
3496 \f
3497 /* Clean up connection to a remote debugger.  */
3498
3499 static void
3500 remote_close (struct target_ops *self)
3501 {
3502   struct remote_state *rs = get_remote_state ();
3503
3504   if (rs->remote_desc == NULL)
3505     return; /* already closed */
3506
3507   /* Make sure we leave stdin registered in the event loop.  */
3508   remote_terminal_ours (self);
3509
3510   serial_close (rs->remote_desc);
3511   rs->remote_desc = NULL;
3512
3513   /* We don't have a connection to the remote stub anymore.  Get rid
3514      of all the inferiors and their threads we were controlling.
3515      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3516      will be unable to find the thread corresponding to (pid, 0, 0).  */
3517   inferior_ptid = null_ptid;
3518   discard_all_inferiors ();
3519
3520   /* We are closing the remote target, so we should discard
3521      everything of this target.  */
3522   discard_pending_stop_replies_in_queue (rs);
3523
3524   if (remote_async_inferior_event_token)
3525     delete_async_event_handler (&remote_async_inferior_event_token);
3526
3527   remote_notif_state_xfree (rs->notif_state);
3528
3529   trace_reset_local_state ();
3530 }
3531
3532 /* Query the remote side for the text, data and bss offsets.  */
3533
3534 static void
3535 get_offsets (void)
3536 {
3537   struct remote_state *rs = get_remote_state ();
3538   char *buf;
3539   char *ptr;
3540   int lose, num_segments = 0, do_sections, do_segments;
3541   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3542   struct section_offsets *offs;
3543   struct symfile_segment_data *data;
3544
3545   if (symfile_objfile == NULL)
3546     return;
3547
3548   putpkt ("qOffsets");
3549   getpkt (&rs->buf, &rs->buf_size, 0);
3550   buf = rs->buf;
3551
3552   if (buf[0] == '\000')
3553     return;                     /* Return silently.  Stub doesn't support
3554                                    this command.  */
3555   if (buf[0] == 'E')
3556     {
3557       warning (_("Remote failure reply: %s"), buf);
3558       return;
3559     }
3560
3561   /* Pick up each field in turn.  This used to be done with scanf, but
3562      scanf will make trouble if CORE_ADDR size doesn't match
3563      conversion directives correctly.  The following code will work
3564      with any size of CORE_ADDR.  */
3565   text_addr = data_addr = bss_addr = 0;
3566   ptr = buf;
3567   lose = 0;
3568
3569   if (startswith (ptr, "Text="))
3570     {
3571       ptr += 5;
3572       /* Don't use strtol, could lose on big values.  */
3573       while (*ptr && *ptr != ';')
3574         text_addr = (text_addr << 4) + fromhex (*ptr++);
3575
3576       if (startswith (ptr, ";Data="))
3577         {
3578           ptr += 6;
3579           while (*ptr && *ptr != ';')
3580             data_addr = (data_addr << 4) + fromhex (*ptr++);
3581         }
3582       else
3583         lose = 1;
3584
3585       if (!lose && startswith (ptr, ";Bss="))
3586         {
3587           ptr += 5;
3588           while (*ptr && *ptr != ';')
3589             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3590
3591           if (bss_addr != data_addr)
3592             warning (_("Target reported unsupported offsets: %s"), buf);
3593         }
3594       else
3595         lose = 1;
3596     }
3597   else if (startswith (ptr, "TextSeg="))
3598     {
3599       ptr += 8;
3600       /* Don't use strtol, could lose on big values.  */
3601       while (*ptr && *ptr != ';')
3602         text_addr = (text_addr << 4) + fromhex (*ptr++);
3603       num_segments = 1;
3604
3605       if (startswith (ptr, ";DataSeg="))
3606         {
3607           ptr += 9;
3608           while (*ptr && *ptr != ';')
3609             data_addr = (data_addr << 4) + fromhex (*ptr++);
3610           num_segments++;
3611         }
3612     }
3613   else
3614     lose = 1;
3615
3616   if (lose)
3617     error (_("Malformed response to offset query, %s"), buf);
3618   else if (*ptr != '\0')
3619     warning (_("Target reported unsupported offsets: %s"), buf);
3620
3621   offs = ((struct section_offsets *)
3622           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3623   memcpy (offs, symfile_objfile->section_offsets,
3624           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3625
3626   data = get_symfile_segment_data (symfile_objfile->obfd);
3627   do_segments = (data != NULL);
3628   do_sections = num_segments == 0;
3629
3630   if (num_segments > 0)
3631     {
3632       segments[0] = text_addr;
3633       segments[1] = data_addr;
3634     }
3635   /* If we have two segments, we can still try to relocate everything
3636      by assuming that the .text and .data offsets apply to the whole
3637      text and data segments.  Convert the offsets given in the packet
3638      to base addresses for symfile_map_offsets_to_segments.  */
3639   else if (data && data->num_segments == 2)
3640     {
3641       segments[0] = data->segment_bases[0] + text_addr;
3642       segments[1] = data->segment_bases[1] + data_addr;
3643       num_segments = 2;
3644     }
3645   /* If the object file has only one segment, assume that it is text
3646      rather than data; main programs with no writable data are rare,
3647      but programs with no code are useless.  Of course the code might
3648      have ended up in the data segment... to detect that we would need
3649      the permissions here.  */
3650   else if (data && data->num_segments == 1)
3651     {
3652       segments[0] = data->segment_bases[0] + text_addr;
3653       num_segments = 1;
3654     }
3655   /* There's no way to relocate by segment.  */
3656   else
3657     do_segments = 0;
3658
3659   if (do_segments)
3660     {
3661       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3662                                                  offs, num_segments, segments);
3663
3664       if (ret == 0 && !do_sections)
3665         error (_("Can not handle qOffsets TextSeg "
3666                  "response with this symbol file"));
3667
3668       if (ret > 0)
3669         do_sections = 0;
3670     }
3671
3672   if (data)
3673     free_symfile_segment_data (data);
3674
3675   if (do_sections)
3676     {
3677       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3678
3679       /* This is a temporary kludge to force data and bss to use the
3680          same offsets because that's what nlmconv does now.  The real
3681          solution requires changes to the stub and remote.c that I
3682          don't have time to do right now.  */
3683
3684       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3685       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3686     }
3687
3688   objfile_relocate (symfile_objfile, offs);
3689 }
3690
3691 /* Send interrupt_sequence to remote target.  */
3692 static void
3693 send_interrupt_sequence (void)
3694 {
3695   struct remote_state *rs = get_remote_state ();
3696
3697   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3698     remote_serial_write ("\x03", 1);
3699   else if (interrupt_sequence_mode == interrupt_sequence_break)
3700     serial_send_break (rs->remote_desc);
3701   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3702     {
3703       serial_send_break (rs->remote_desc);
3704       remote_serial_write ("g", 1);
3705     }
3706   else
3707     internal_error (__FILE__, __LINE__,
3708                     _("Invalid value for interrupt_sequence_mode: %s."),
3709                     interrupt_sequence_mode);
3710 }
3711
3712
3713 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3714    and extract the PTID.  Returns NULL_PTID if not found.  */
3715
3716 static ptid_t
3717 stop_reply_extract_thread (char *stop_reply)
3718 {
3719   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3720     {
3721       char *p;
3722
3723       /* Txx r:val ; r:val (...)  */
3724       p = &stop_reply[3];
3725
3726       /* Look for "register" named "thread".  */
3727       while (*p != '\0')
3728         {
3729           char *p1;
3730
3731           p1 = strchr (p, ':');
3732           if (p1 == NULL)
3733             return null_ptid;
3734
3735           if (strncmp (p, "thread", p1 - p) == 0)
3736             return read_ptid (++p1, &p);
3737
3738           p1 = strchr (p, ';');
3739           if (p1 == NULL)
3740             return null_ptid;
3741           p1++;
3742
3743           p = p1;
3744         }
3745     }
3746
3747   return null_ptid;
3748 }
3749
3750 /* Determine the remote side's current thread.  If we have a stop
3751    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3752    "thread" register we can extract the current thread from.  If not,
3753    ask the remote which is the current thread with qC.  The former
3754    method avoids a roundtrip.  */
3755
3756 static ptid_t
3757 get_current_thread (char *wait_status)
3758 {
3759   ptid_t ptid = null_ptid;
3760
3761   /* Note we don't use remote_parse_stop_reply as that makes use of
3762      the target architecture, which we haven't yet fully determined at
3763      this point.  */
3764   if (wait_status != NULL)
3765     ptid = stop_reply_extract_thread (wait_status);
3766   if (ptid_equal (ptid, null_ptid))
3767     ptid = remote_current_thread (inferior_ptid);
3768
3769   return ptid;
3770 }
3771
3772 /* Query the remote target for which is the current thread/process,
3773    add it to our tables, and update INFERIOR_PTID.  The caller is
3774    responsible for setting the state such that the remote end is ready
3775    to return the current thread.
3776
3777    This function is called after handling the '?' or 'vRun' packets,
3778    whose response is a stop reply from which we can also try
3779    extracting the thread.  If the target doesn't support the explicit
3780    qC query, we infer the current thread from that stop reply, passed
3781    in in WAIT_STATUS, which may be NULL.  */
3782
3783 static void
3784 add_current_inferior_and_thread (char *wait_status)
3785 {
3786   struct remote_state *rs = get_remote_state ();
3787   int fake_pid_p = 0;
3788   ptid_t ptid;
3789
3790   inferior_ptid = null_ptid;
3791
3792   /* Now, if we have thread information, update inferior_ptid.  */
3793   ptid = get_current_thread (wait_status);
3794
3795   if (!ptid_equal (ptid, null_ptid))
3796     {
3797       if (!remote_multi_process_p (rs))
3798         fake_pid_p = 1;
3799
3800       inferior_ptid = ptid;
3801     }
3802   else
3803     {
3804       /* Without this, some commands which require an active target
3805          (such as kill) won't work.  This variable serves (at least)
3806          double duty as both the pid of the target process (if it has
3807          such), and as a flag indicating that a target is active.  */
3808       inferior_ptid = magic_null_ptid;
3809       fake_pid_p = 1;
3810     }
3811
3812   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3813
3814   /* Add the main thread.  */
3815   add_thread_silent (inferior_ptid);
3816 }
3817
3818 /* Print info about a thread that was found already stopped on
3819    connection.  */
3820
3821 static void
3822 print_one_stopped_thread (struct thread_info *thread)
3823 {
3824   struct target_waitstatus *ws = &thread->suspend.waitstatus;
3825
3826   switch_to_thread (thread->ptid);
3827   stop_pc = get_frame_pc (get_current_frame ());
3828   set_current_sal_from_frame (get_current_frame ());
3829
3830   thread->suspend.waitstatus_pending_p = 0;
3831
3832   if (ws->kind == TARGET_WAITKIND_STOPPED)
3833     {
3834       enum gdb_signal sig = ws->value.sig;
3835
3836       if (signal_print_state (sig))
3837         observer_notify_signal_received (sig);
3838     }
3839   observer_notify_normal_stop (NULL, 1);
3840 }
3841
3842 /* Process all initial stop replies the remote side sent in response
3843    to the ? packet.  These indicate threads that were already stopped
3844    on initial connection.  We mark these threads as stopped and print
3845    their current frame before giving the user the prompt.  */
3846
3847 static void
3848 process_initial_stop_replies (int from_tty)
3849 {
3850   int pending_stop_replies = stop_reply_queue_length ();
3851   struct inferior *inf;
3852   struct thread_info *thread;
3853   struct thread_info *selected = NULL;
3854   struct thread_info *lowest_stopped = NULL;
3855   struct thread_info *first = NULL;
3856
3857   /* Consume the initial pending events.  */
3858   while (pending_stop_replies-- > 0)
3859     {
3860       ptid_t waiton_ptid = minus_one_ptid;
3861       ptid_t event_ptid;
3862       struct target_waitstatus ws;
3863       int ignore_event = 0;
3864       struct thread_info *thread;
3865
3866       memset (&ws, 0, sizeof (ws));
3867       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3868       if (remote_debug)
3869         print_target_wait_results (waiton_ptid, event_ptid, &ws);
3870
3871       switch (ws.kind)
3872         {
3873         case TARGET_WAITKIND_IGNORE:
3874         case TARGET_WAITKIND_NO_RESUMED:
3875         case TARGET_WAITKIND_SIGNALLED:
3876         case TARGET_WAITKIND_EXITED:
3877           /* We shouldn't see these, but if we do, just ignore.  */
3878           if (remote_debug)
3879             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3880           ignore_event = 1;
3881           break;
3882
3883         case TARGET_WAITKIND_EXECD:
3884           xfree (ws.value.execd_pathname);
3885           break;
3886         default:
3887           break;
3888         }
3889
3890       if (ignore_event)
3891         continue;
3892
3893       thread = find_thread_ptid (event_ptid);
3894
3895       if (ws.kind == TARGET_WAITKIND_STOPPED)
3896         {
3897           enum gdb_signal sig = ws.value.sig;
3898
3899           /* Stubs traditionally report SIGTRAP as initial signal,
3900              instead of signal 0.  Suppress it.  */
3901           if (sig == GDB_SIGNAL_TRAP)
3902             sig = GDB_SIGNAL_0;
3903           thread->suspend.stop_signal = sig;
3904           ws.value.sig = sig;
3905         }
3906
3907       thread->suspend.waitstatus = ws;
3908
3909       if (ws.kind != TARGET_WAITKIND_STOPPED
3910           || ws.value.sig != GDB_SIGNAL_0)
3911         thread->suspend.waitstatus_pending_p = 1;
3912
3913       set_executing (event_ptid, 0);
3914       set_running (event_ptid, 0);
3915     }
3916
3917   /* "Notice" the new inferiors before anything related to
3918      registers/memory.  */
3919   ALL_INFERIORS (inf)
3920     {
3921       if (inf->pid == 0)
3922         continue;
3923
3924       inf->needs_setup = 1;
3925
3926       if (non_stop)
3927         {
3928           thread = any_live_thread_of_process (inf->pid);
3929           notice_new_inferior (thread->ptid,
3930                                thread->state == THREAD_RUNNING,
3931                                from_tty);
3932         }
3933     }
3934
3935   /* If all-stop on top of non-stop, pause all threads.  Note this
3936      records the threads' stop pc, so must be done after "noticing"
3937      the inferiors.  */
3938   if (!non_stop)
3939     {
3940       stop_all_threads ();
3941
3942       /* If all threads of an inferior were already stopped, we
3943          haven't setup the inferior yet.  */
3944       ALL_INFERIORS (inf)
3945         {
3946           if (inf->pid == 0)
3947             continue;
3948
3949           if (inf->needs_setup)
3950             {
3951               thread = any_live_thread_of_process (inf->pid);
3952               switch_to_thread_no_regs (thread);
3953               setup_inferior (0);
3954             }
3955         }
3956     }
3957
3958   /* Now go over all threads that are stopped, and print their current
3959      frame.  If all-stop, then if there's a signalled thread, pick
3960      that as current.  */
3961   ALL_NON_EXITED_THREADS (thread)
3962     {
3963       if (first == NULL)
3964         first = thread;
3965
3966       if (!non_stop)
3967         set_running (thread->ptid, 0);
3968       else if (thread->state != THREAD_STOPPED)
3969         continue;
3970
3971       if (selected == NULL
3972           && thread->suspend.waitstatus_pending_p)
3973         selected = thread;
3974
3975       if (lowest_stopped == NULL
3976           || thread->inf->num < lowest_stopped->inf->num
3977           || thread->per_inf_num < lowest_stopped->per_inf_num)
3978         lowest_stopped = thread;
3979
3980       if (non_stop)
3981         print_one_stopped_thread (thread);
3982     }
3983
3984   /* In all-stop, we only print the status of one thread, and leave
3985      others with their status pending.  */
3986   if (!non_stop)
3987     {
3988       thread = selected;
3989       if (thread == NULL)
3990         thread = lowest_stopped;
3991       if (thread == NULL)
3992         thread = first;
3993
3994       print_one_stopped_thread (thread);
3995     }
3996
3997   /* For "info program".  */
3998   thread = inferior_thread ();
3999   if (thread->state == THREAD_STOPPED)
4000     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4001 }
4002
4003 /* Start the remote connection and sync state.  */
4004
4005 static void
4006 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4007 {
4008   struct remote_state *rs = get_remote_state ();
4009   struct packet_config *noack_config;
4010   char *wait_status = NULL;
4011
4012   /* Signal other parts that we're going through the initial setup,
4013      and so things may not be stable yet.  E.g., we don't try to
4014      install tracepoints until we've relocated symbols.  Also, a
4015      Ctrl-C before we're connected and synced up can't interrupt the
4016      target.  Instead, it offers to drop the (potentially wedged)
4017      connection.  */
4018   rs->starting_up = 1;
4019
4020   QUIT;
4021
4022   if (interrupt_on_connect)
4023     send_interrupt_sequence ();
4024
4025   /* Ack any packet which the remote side has already sent.  */
4026   remote_serial_write ("+", 1);
4027
4028   /* The first packet we send to the target is the optional "supported
4029      packets" request.  If the target can answer this, it will tell us
4030      which later probes to skip.  */
4031   remote_query_supported ();
4032
4033   /* If the stub wants to get a QAllow, compose one and send it.  */
4034   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4035     remote_set_permissions (target);
4036
4037   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4038      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
4039      as a reply to known packet.  For packet "vFile:setfs:" it is an
4040      invalid reply and GDB would return error in
4041      remote_hostio_set_filesystem, making remote files access impossible.
4042      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
4043      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
4044   {
4045     const char v_mustreplyempty[] = "vMustReplyEmpty";
4046
4047     putpkt (v_mustreplyempty);
4048     getpkt (&rs->buf, &rs->buf_size, 0);
4049     if (strcmp (rs->buf, "OK") == 0)
4050       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4051     else if (strcmp (rs->buf, "") != 0)
4052       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4053              rs->buf);
4054   }
4055
4056   /* Next, we possibly activate noack mode.
4057
4058      If the QStartNoAckMode packet configuration is set to AUTO,
4059      enable noack mode if the stub reported a wish for it with
4060      qSupported.
4061
4062      If set to TRUE, then enable noack mode even if the stub didn't
4063      report it in qSupported.  If the stub doesn't reply OK, the
4064      session ends with an error.
4065
4066      If FALSE, then don't activate noack mode, regardless of what the
4067      stub claimed should be the default with qSupported.  */
4068
4069   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4070   if (packet_config_support (noack_config) != PACKET_DISABLE)
4071     {
4072       putpkt ("QStartNoAckMode");
4073       getpkt (&rs->buf, &rs->buf_size, 0);
4074       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4075         rs->noack_mode = 1;
4076     }
4077
4078   if (extended_p)
4079     {
4080       /* Tell the remote that we are using the extended protocol.  */
4081       putpkt ("!");
4082       getpkt (&rs->buf, &rs->buf_size, 0);
4083     }
4084
4085   /* Let the target know which signals it is allowed to pass down to
4086      the program.  */
4087   update_signals_program_target ();
4088
4089   /* Next, if the target can specify a description, read it.  We do
4090      this before anything involving memory or registers.  */
4091   target_find_description ();
4092
4093   /* Next, now that we know something about the target, update the
4094      address spaces in the program spaces.  */
4095   update_address_spaces ();
4096
4097   /* On OSs where the list of libraries is global to all
4098      processes, we fetch them early.  */
4099   if (gdbarch_has_global_solist (target_gdbarch ()))
4100     solib_add (NULL, from_tty, target, auto_solib_add);
4101
4102   if (target_is_non_stop_p ())
4103     {
4104       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4105         error (_("Non-stop mode requested, but remote "
4106                  "does not support non-stop"));
4107
4108       putpkt ("QNonStop:1");
4109       getpkt (&rs->buf, &rs->buf_size, 0);
4110
4111       if (strcmp (rs->buf, "OK") != 0)
4112         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4113
4114       /* Find about threads and processes the stub is already
4115          controlling.  We default to adding them in the running state.
4116          The '?' query below will then tell us about which threads are
4117          stopped.  */
4118       remote_update_thread_list (target);
4119     }
4120   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4121     {
4122       /* Don't assume that the stub can operate in all-stop mode.
4123          Request it explicitly.  */
4124       putpkt ("QNonStop:0");
4125       getpkt (&rs->buf, &rs->buf_size, 0);
4126
4127       if (strcmp (rs->buf, "OK") != 0)
4128         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4129     }
4130
4131   /* Upload TSVs regardless of whether the target is running or not.  The
4132      remote stub, such as GDBserver, may have some predefined or builtin
4133      TSVs, even if the target is not running.  */
4134   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4135     {
4136       struct uploaded_tsv *uploaded_tsvs = NULL;
4137
4138       remote_upload_trace_state_variables (target, &uploaded_tsvs);
4139       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4140     }
4141
4142   /* Check whether the target is running now.  */
4143   putpkt ("?");
4144   getpkt (&rs->buf, &rs->buf_size, 0);
4145
4146   if (!target_is_non_stop_p ())
4147     {
4148       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4149         {
4150           if (!extended_p)
4151             error (_("The target is not running (try extended-remote?)"));
4152
4153           /* We're connected, but not running.  Drop out before we
4154              call start_remote.  */
4155           rs->starting_up = 0;
4156           return;
4157         }
4158       else
4159         {
4160           /* Save the reply for later.  */
4161           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4162           strcpy (wait_status, rs->buf);
4163         }
4164
4165       /* Fetch thread list.  */
4166       target_update_thread_list ();
4167
4168       /* Let the stub know that we want it to return the thread.  */
4169       set_continue_thread (minus_one_ptid);
4170
4171       if (thread_count () == 0)
4172         {
4173           /* Target has no concept of threads at all.  GDB treats
4174              non-threaded target as single-threaded; add a main
4175              thread.  */
4176           add_current_inferior_and_thread (wait_status);
4177         }
4178       else
4179         {
4180           /* We have thread information; select the thread the target
4181              says should be current.  If we're reconnecting to a
4182              multi-threaded program, this will ideally be the thread
4183              that last reported an event before GDB disconnected.  */
4184           inferior_ptid = get_current_thread (wait_status);
4185           if (ptid_equal (inferior_ptid, null_ptid))
4186             {
4187               /* Odd... The target was able to list threads, but not
4188                  tell us which thread was current (no "thread"
4189                  register in T stop reply?).  Just pick the first
4190                  thread in the thread list then.  */
4191               
4192               if (remote_debug)
4193                 fprintf_unfiltered (gdb_stdlog,
4194                                     "warning: couldn't determine remote "
4195                                     "current thread; picking first in list.\n");
4196
4197               inferior_ptid = thread_list->ptid;
4198             }
4199         }
4200
4201       /* init_wait_for_inferior should be called before get_offsets in order
4202          to manage `inserted' flag in bp loc in a correct state.
4203          breakpoint_init_inferior, called from init_wait_for_inferior, set
4204          `inserted' flag to 0, while before breakpoint_re_set, called from
4205          start_remote, set `inserted' flag to 1.  In the initialization of
4206          inferior, breakpoint_init_inferior should be called first, and then
4207          breakpoint_re_set can be called.  If this order is broken, state of
4208          `inserted' flag is wrong, and cause some problems on breakpoint
4209          manipulation.  */
4210       init_wait_for_inferior ();
4211
4212       get_offsets ();           /* Get text, data & bss offsets.  */
4213
4214       /* If we could not find a description using qXfer, and we know
4215          how to do it some other way, try again.  This is not
4216          supported for non-stop; it could be, but it is tricky if
4217          there are no stopped threads when we connect.  */
4218       if (remote_read_description_p (target)
4219           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4220         {
4221           target_clear_description ();
4222           target_find_description ();
4223         }
4224
4225       /* Use the previously fetched status.  */
4226       gdb_assert (wait_status != NULL);
4227       strcpy (rs->buf, wait_status);
4228       rs->cached_wait_status = 1;
4229
4230       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4231     }
4232   else
4233     {
4234       /* Clear WFI global state.  Do this before finding about new
4235          threads and inferiors, and setting the current inferior.
4236          Otherwise we would clear the proceed status of the current
4237          inferior when we want its stop_soon state to be preserved
4238          (see notice_new_inferior).  */
4239       init_wait_for_inferior ();
4240
4241       /* In non-stop, we will either get an "OK", meaning that there
4242          are no stopped threads at this time; or, a regular stop
4243          reply.  In the latter case, there may be more than one thread
4244          stopped --- we pull them all out using the vStopped
4245          mechanism.  */
4246       if (strcmp (rs->buf, "OK") != 0)
4247         {
4248           struct notif_client *notif = &notif_client_stop;
4249
4250           /* remote_notif_get_pending_replies acks this one, and gets
4251              the rest out.  */
4252           rs->notif_state->pending_event[notif_client_stop.id]
4253             = remote_notif_parse (notif, rs->buf);
4254           remote_notif_get_pending_events (notif);
4255         }
4256
4257       if (thread_count () == 0)
4258         {
4259           if (!extended_p)
4260             error (_("The target is not running (try extended-remote?)"));
4261
4262           /* We're connected, but not running.  Drop out before we
4263              call start_remote.  */
4264           rs->starting_up = 0;
4265           return;
4266         }
4267
4268       /* In non-stop mode, any cached wait status will be stored in
4269          the stop reply queue.  */
4270       gdb_assert (wait_status == NULL);
4271
4272       /* Report all signals during attach/startup.  */
4273       remote_pass_signals (target, 0, NULL);
4274
4275       /* If there are already stopped threads, mark them stopped and
4276          report their stops before giving the prompt to the user.  */
4277       process_initial_stop_replies (from_tty);
4278
4279       if (target_can_async_p ())
4280         target_async (1);
4281     }
4282
4283   /* If we connected to a live target, do some additional setup.  */
4284   if (target_has_execution)
4285     {
4286       if (symfile_objfile)      /* No use without a symbol-file.  */
4287         remote_check_symbols ();
4288     }
4289
4290   /* Possibly the target has been engaged in a trace run started
4291      previously; find out where things are at.  */
4292   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4293     {
4294       struct uploaded_tp *uploaded_tps = NULL;
4295
4296       if (current_trace_status ()->running)
4297         printf_filtered (_("Trace is already running on the target.\n"));
4298
4299       remote_upload_tracepoints (target, &uploaded_tps);
4300
4301       merge_uploaded_tracepoints (&uploaded_tps);
4302     }
4303
4304   /* Possibly the target has been engaged in a btrace record started
4305      previously; find out where things are at.  */
4306   remote_btrace_maybe_reopen ();
4307
4308   /* The thread and inferior lists are now synchronized with the
4309      target, our symbols have been relocated, and we're merged the
4310      target's tracepoints with ours.  We're done with basic start
4311      up.  */
4312   rs->starting_up = 0;
4313
4314   /* Maybe breakpoints are global and need to be inserted now.  */
4315   if (breakpoints_should_be_inserted_now ())
4316     insert_breakpoints ();
4317 }
4318
4319 /* Open a connection to a remote debugger.
4320    NAME is the filename used for communication.  */
4321
4322 static void
4323 remote_open (const char *name, int from_tty)
4324 {
4325   remote_open_1 (name, from_tty, &remote_ops, 0);
4326 }
4327
4328 /* Open a connection to a remote debugger using the extended
4329    remote gdb protocol.  NAME is the filename used for communication.  */
4330
4331 static void
4332 extended_remote_open (const char *name, int from_tty)
4333 {
4334   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4335 }
4336
4337 /* Reset all packets back to "unknown support".  Called when opening a
4338    new connection to a remote target.  */
4339
4340 static void
4341 reset_all_packet_configs_support (void)
4342 {
4343   int i;
4344
4345   for (i = 0; i < PACKET_MAX; i++)
4346     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4347 }
4348
4349 /* Initialize all packet configs.  */
4350
4351 static void
4352 init_all_packet_configs (void)
4353 {
4354   int i;
4355
4356   for (i = 0; i < PACKET_MAX; i++)
4357     {
4358       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4359       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4360     }
4361 }
4362
4363 /* Symbol look-up.  */
4364
4365 static void
4366 remote_check_symbols (void)
4367 {
4368   struct remote_state *rs = get_remote_state ();
4369   char *msg, *reply, *tmp;
4370   int end;
4371   long reply_size;
4372   struct cleanup *old_chain;
4373
4374   /* The remote side has no concept of inferiors that aren't running
4375      yet, it only knows about running processes.  If we're connected
4376      but our current inferior is not running, we should not invite the
4377      remote target to request symbol lookups related to its
4378      (unrelated) current process.  */
4379   if (!target_has_execution)
4380     return;
4381
4382   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4383     return;
4384
4385   /* Make sure the remote is pointing at the right process.  Note
4386      there's no way to select "no process".  */
4387   set_general_process ();
4388
4389   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4390      because we need both at the same time.  */
4391   msg = (char *) xmalloc (get_remote_packet_size ());
4392   old_chain = make_cleanup (xfree, msg);
4393   reply = (char *) xmalloc (get_remote_packet_size ());
4394   make_cleanup (free_current_contents, &reply);
4395   reply_size = get_remote_packet_size ();
4396
4397   /* Invite target to request symbol lookups.  */
4398
4399   putpkt ("qSymbol::");
4400   getpkt (&reply, &reply_size, 0);
4401   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4402
4403   while (startswith (reply, "qSymbol:"))
4404     {
4405       struct bound_minimal_symbol sym;
4406
4407       tmp = &reply[8];
4408       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4409       msg[end] = '\0';
4410       sym = lookup_minimal_symbol (msg, NULL, NULL);
4411       if (sym.minsym == NULL)
4412         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4413       else
4414         {
4415           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4416           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4417
4418           /* If this is a function address, return the start of code
4419              instead of any data function descriptor.  */
4420           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4421                                                          sym_addr,
4422                                                          &current_target);
4423
4424           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4425                      phex_nz (sym_addr, addr_size), &reply[8]);
4426         }
4427   
4428       putpkt (msg);
4429       getpkt (&reply, &reply_size, 0);
4430     }
4431
4432   do_cleanups (old_chain);
4433 }
4434
4435 static struct serial *
4436 remote_serial_open (const char *name)
4437 {
4438   static int udp_warning = 0;
4439
4440   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4441      of in ser-tcp.c, because it is the remote protocol assuming that the
4442      serial connection is reliable and not the serial connection promising
4443      to be.  */
4444   if (!udp_warning && startswith (name, "udp:"))
4445     {
4446       warning (_("The remote protocol may be unreliable over UDP.\n"
4447                  "Some events may be lost, rendering further debugging "
4448                  "impossible."));
4449       udp_warning = 1;
4450     }
4451
4452   return serial_open (name);
4453 }
4454
4455 /* Inform the target of our permission settings.  The permission flags
4456    work without this, but if the target knows the settings, it can do
4457    a couple things.  First, it can add its own check, to catch cases
4458    that somehow manage to get by the permissions checks in target
4459    methods.  Second, if the target is wired to disallow particular
4460    settings (for instance, a system in the field that is not set up to
4461    be able to stop at a breakpoint), it can object to any unavailable
4462    permissions.  */
4463
4464 void
4465 remote_set_permissions (struct target_ops *self)
4466 {
4467   struct remote_state *rs = get_remote_state ();
4468
4469   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4470              "WriteReg:%x;WriteMem:%x;"
4471              "InsertBreak:%x;InsertTrace:%x;"
4472              "InsertFastTrace:%x;Stop:%x",
4473              may_write_registers, may_write_memory,
4474              may_insert_breakpoints, may_insert_tracepoints,
4475              may_insert_fast_tracepoints, may_stop);
4476   putpkt (rs->buf);
4477   getpkt (&rs->buf, &rs->buf_size, 0);
4478
4479   /* If the target didn't like the packet, warn the user.  Do not try
4480      to undo the user's settings, that would just be maddening.  */
4481   if (strcmp (rs->buf, "OK") != 0)
4482     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4483 }
4484
4485 /* This type describes each known response to the qSupported
4486    packet.  */
4487 struct protocol_feature
4488 {
4489   /* The name of this protocol feature.  */
4490   const char *name;
4491
4492   /* The default for this protocol feature.  */
4493   enum packet_support default_support;
4494
4495   /* The function to call when this feature is reported, or after
4496      qSupported processing if the feature is not supported.
4497      The first argument points to this structure.  The second
4498      argument indicates whether the packet requested support be
4499      enabled, disabled, or probed (or the default, if this function
4500      is being called at the end of processing and this feature was
4501      not reported).  The third argument may be NULL; if not NULL, it
4502      is a NUL-terminated string taken from the packet following
4503      this feature's name and an equals sign.  */
4504   void (*func) (const struct protocol_feature *, enum packet_support,
4505                 const char *);
4506
4507   /* The corresponding packet for this feature.  Only used if
4508      FUNC is remote_supported_packet.  */
4509   int packet;
4510 };
4511
4512 static void
4513 remote_supported_packet (const struct protocol_feature *feature,
4514                          enum packet_support support,
4515                          const char *argument)
4516 {
4517   if (argument)
4518     {
4519       warning (_("Remote qSupported response supplied an unexpected value for"
4520                  " \"%s\"."), feature->name);
4521       return;
4522     }
4523
4524   remote_protocol_packets[feature->packet].support = support;
4525 }
4526
4527 static void
4528 remote_packet_size (const struct protocol_feature *feature,
4529                     enum packet_support support, const char *value)
4530 {
4531   struct remote_state *rs = get_remote_state ();
4532
4533   int packet_size;
4534   char *value_end;
4535
4536   if (support != PACKET_ENABLE)
4537     return;
4538
4539   if (value == NULL || *value == '\0')
4540     {
4541       warning (_("Remote target reported \"%s\" without a size."),
4542                feature->name);
4543       return;
4544     }
4545
4546   errno = 0;
4547   packet_size = strtol (value, &value_end, 16);
4548   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4549     {
4550       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4551                feature->name, value);
4552       return;
4553     }
4554
4555   /* Record the new maximum packet size.  */
4556   rs->explicit_packet_size = packet_size;
4557 }
4558
4559 static const struct protocol_feature remote_protocol_features[] = {
4560   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4561   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4562     PACKET_qXfer_auxv },
4563   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4564     PACKET_qXfer_exec_file },
4565   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4566     PACKET_qXfer_features },
4567   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4568     PACKET_qXfer_libraries },
4569   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4570     PACKET_qXfer_libraries_svr4 },
4571   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4572     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4573   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4574     PACKET_qXfer_memory_map },
4575   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4576     PACKET_qXfer_spu_read },
4577   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4578     PACKET_qXfer_spu_write },
4579   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4580     PACKET_qXfer_osdata },
4581   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4582     PACKET_qXfer_threads },
4583   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4584     PACKET_qXfer_traceframe_info },
4585   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4586     PACKET_QPassSignals },
4587   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4588     PACKET_QCatchSyscalls },
4589   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4590     PACKET_QProgramSignals },
4591   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4592     PACKET_QStartNoAckMode },
4593   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4594     PACKET_multiprocess_feature },
4595   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4596   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4597     PACKET_qXfer_siginfo_read },
4598   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4599     PACKET_qXfer_siginfo_write },
4600   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4601     PACKET_ConditionalTracepoints },
4602   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4603     PACKET_ConditionalBreakpoints },
4604   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4605     PACKET_BreakpointCommands },
4606   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4607     PACKET_FastTracepoints },
4608   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4609     PACKET_StaticTracepoints },
4610   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4611    PACKET_InstallInTrace},
4612   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4613     PACKET_DisconnectedTracing_feature },
4614   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4615     PACKET_bc },
4616   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4617     PACKET_bs },
4618   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4619     PACKET_TracepointSource },
4620   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4621     PACKET_QAllow },
4622   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4623     PACKET_EnableDisableTracepoints_feature },
4624   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4625     PACKET_qXfer_fdpic },
4626   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4627     PACKET_qXfer_uib },
4628   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4629     PACKET_QDisableRandomization },
4630   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4631   { "QTBuffer:size", PACKET_DISABLE,
4632     remote_supported_packet, PACKET_QTBuffer_size},
4633   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4634   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4635   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4636   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4637   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4638     PACKET_qXfer_btrace },
4639   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4640     PACKET_qXfer_btrace_conf },
4641   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4642     PACKET_Qbtrace_conf_bts_size },
4643   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4644   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4645   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4646     PACKET_fork_event_feature },
4647   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4648     PACKET_vfork_event_feature },
4649   { "exec-events", PACKET_DISABLE, remote_supported_packet,
4650     PACKET_exec_event_feature },
4651   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4652     PACKET_Qbtrace_conf_pt_size },
4653   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4654   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4655   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4656 };
4657
4658 static char *remote_support_xml;
4659
4660 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4661
4662 void
4663 register_remote_support_xml (const char *xml)
4664 {
4665 #if defined(HAVE_LIBEXPAT)
4666   if (remote_support_xml == NULL)
4667     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4668   else
4669     {
4670       char *copy = xstrdup (remote_support_xml + 13);
4671       char *p = strtok (copy, ",");
4672
4673       do
4674         {
4675           if (strcmp (p, xml) == 0)
4676             {
4677               /* already there */
4678               xfree (copy);
4679               return;
4680             }
4681         }
4682       while ((p = strtok (NULL, ",")) != NULL);
4683       xfree (copy);
4684
4685       remote_support_xml = reconcat (remote_support_xml,
4686                                      remote_support_xml, ",", xml,
4687                                      (char *) NULL);
4688     }
4689 #endif
4690 }
4691
4692 static char *
4693 remote_query_supported_append (char *msg, const char *append)
4694 {
4695   if (msg)
4696     return reconcat (msg, msg, ";", append, (char *) NULL);
4697   else
4698     return xstrdup (append);
4699 }
4700
4701 static void
4702 remote_query_supported (void)
4703 {
4704   struct remote_state *rs = get_remote_state ();
4705   char *next;
4706   int i;
4707   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4708
4709   /* The packet support flags are handled differently for this packet
4710      than for most others.  We treat an error, a disabled packet, and
4711      an empty response identically: any features which must be reported
4712      to be used will be automatically disabled.  An empty buffer
4713      accomplishes this, since that is also the representation for a list
4714      containing no features.  */
4715
4716   rs->buf[0] = 0;
4717   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4718     {
4719       char *q = NULL;
4720       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4721
4722       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4723         q = remote_query_supported_append (q, "multiprocess+");
4724
4725       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4726         q = remote_query_supported_append (q, "swbreak+");
4727       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4728         q = remote_query_supported_append (q, "hwbreak+");
4729
4730       q = remote_query_supported_append (q, "qRelocInsn+");
4731
4732       if (packet_set_cmd_state (PACKET_fork_event_feature)
4733           != AUTO_BOOLEAN_FALSE)
4734         q = remote_query_supported_append (q, "fork-events+");
4735       if (packet_set_cmd_state (PACKET_vfork_event_feature)
4736           != AUTO_BOOLEAN_FALSE)
4737         q = remote_query_supported_append (q, "vfork-events+");
4738       if (packet_set_cmd_state (PACKET_exec_event_feature)
4739           != AUTO_BOOLEAN_FALSE)
4740         q = remote_query_supported_append (q, "exec-events+");
4741
4742       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4743         q = remote_query_supported_append (q, "vContSupported+");
4744
4745       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4746         q = remote_query_supported_append (q, "QThreadEvents+");
4747
4748       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4749         q = remote_query_supported_append (q, "no-resumed+");
4750
4751       /* Keep this one last to work around a gdbserver <= 7.10 bug in
4752          the qSupported:xmlRegisters=i386 handling.  */
4753       if (remote_support_xml != NULL)
4754         q = remote_query_supported_append (q, remote_support_xml);
4755
4756       q = reconcat (q, "qSupported:", q, (char *) NULL);
4757       putpkt (q);
4758
4759       do_cleanups (old_chain);
4760
4761       getpkt (&rs->buf, &rs->buf_size, 0);
4762
4763       /* If an error occured, warn, but do not return - just reset the
4764          buffer to empty and go on to disable features.  */
4765       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4766           == PACKET_ERROR)
4767         {
4768           warning (_("Remote failure reply: %s"), rs->buf);
4769           rs->buf[0] = 0;
4770         }
4771     }
4772
4773   memset (seen, 0, sizeof (seen));
4774
4775   next = rs->buf;
4776   while (*next)
4777     {
4778       enum packet_support is_supported;
4779       char *p, *end, *name_end, *value;
4780
4781       /* First separate out this item from the rest of the packet.  If
4782          there's another item after this, we overwrite the separator
4783          (terminated strings are much easier to work with).  */
4784       p = next;
4785       end = strchr (p, ';');
4786       if (end == NULL)
4787         {
4788           end = p + strlen (p);
4789           next = end;
4790         }
4791       else
4792         {
4793           *end = '\0';
4794           next = end + 1;
4795
4796           if (end == p)
4797             {
4798               warning (_("empty item in \"qSupported\" response"));
4799               continue;
4800             }
4801         }
4802
4803       name_end = strchr (p, '=');
4804       if (name_end)
4805         {
4806           /* This is a name=value entry.  */
4807           is_supported = PACKET_ENABLE;
4808           value = name_end + 1;
4809           *name_end = '\0';
4810         }
4811       else
4812         {
4813           value = NULL;
4814           switch (end[-1])
4815             {
4816             case '+':
4817               is_supported = PACKET_ENABLE;
4818               break;
4819
4820             case '-':
4821               is_supported = PACKET_DISABLE;
4822               break;
4823
4824             case '?':
4825               is_supported = PACKET_SUPPORT_UNKNOWN;
4826               break;
4827
4828             default:
4829               warning (_("unrecognized item \"%s\" "
4830                          "in \"qSupported\" response"), p);
4831               continue;
4832             }
4833           end[-1] = '\0';
4834         }
4835
4836       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4837         if (strcmp (remote_protocol_features[i].name, p) == 0)
4838           {
4839             const struct protocol_feature *feature;
4840
4841             seen[i] = 1;
4842             feature = &remote_protocol_features[i];
4843             feature->func (feature, is_supported, value);
4844             break;
4845           }
4846     }
4847
4848   /* If we increased the packet size, make sure to increase the global
4849      buffer size also.  We delay this until after parsing the entire
4850      qSupported packet, because this is the same buffer we were
4851      parsing.  */
4852   if (rs->buf_size < rs->explicit_packet_size)
4853     {
4854       rs->buf_size = rs->explicit_packet_size;
4855       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4856     }
4857
4858   /* Handle the defaults for unmentioned features.  */
4859   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4860     if (!seen[i])
4861       {
4862         const struct protocol_feature *feature;
4863
4864         feature = &remote_protocol_features[i];
4865         feature->func (feature, feature->default_support, NULL);
4866       }
4867 }
4868
4869 /* Serial QUIT handler for the remote serial descriptor.
4870
4871    Defers handling a Ctrl-C until we're done with the current
4872    command/response packet sequence, unless:
4873
4874    - We're setting up the connection.  Don't send a remote interrupt
4875      request, as we're not fully synced yet.  Quit immediately
4876      instead.
4877
4878    - The target has been resumed in the foreground
4879      (target_terminal_is_ours is false) with a synchronous resume
4880      packet, and we're blocked waiting for the stop reply, thus a
4881      Ctrl-C should be immediately sent to the target.
4882
4883    - We get a second Ctrl-C while still within the same serial read or
4884      write.  In that case the serial is seemingly wedged --- offer to
4885      quit/disconnect.
4886
4887    - We see a second Ctrl-C without target response, after having
4888      previously interrupted the target.  In that case the target/stub
4889      is probably wedged --- offer to quit/disconnect.
4890 */
4891
4892 static void
4893 remote_serial_quit_handler (void)
4894 {
4895   struct remote_state *rs = get_remote_state ();
4896
4897   if (check_quit_flag ())
4898     {
4899       /* If we're starting up, we're not fully synced yet.  Quit
4900          immediately.  */
4901       if (rs->starting_up)
4902         quit ();
4903       else if (rs->got_ctrlc_during_io)
4904         {
4905           if (query (_("The target is not responding to GDB commands.\n"
4906                        "Stop debugging it? ")))
4907             remote_unpush_and_throw ();
4908         }
4909       /* If ^C has already been sent once, offer to disconnect.  */
4910       else if (!target_terminal_is_ours () && rs->ctrlc_pending_p)
4911         interrupt_query ();
4912       /* All-stop protocol, and blocked waiting for stop reply.  Send
4913          an interrupt request.  */
4914       else if (!target_terminal_is_ours () && rs->waiting_for_stop_reply)
4915         target_interrupt (inferior_ptid);
4916       else
4917         rs->got_ctrlc_during_io = 1;
4918     }
4919 }
4920
4921 /* Remove any of the remote.c targets from target stack.  Upper targets depend
4922    on it so remove them first.  */
4923
4924 static void
4925 remote_unpush_target (void)
4926 {
4927   pop_all_targets_at_and_above (process_stratum);
4928 }
4929
4930 static void
4931 remote_unpush_and_throw (void)
4932 {
4933   remote_unpush_target ();
4934   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
4935 }
4936
4937 static void
4938 remote_open_1 (const char *name, int from_tty,
4939                struct target_ops *target, int extended_p)
4940 {
4941   struct remote_state *rs = get_remote_state ();
4942
4943   if (name == 0)
4944     error (_("To open a remote debug connection, you need to specify what\n"
4945            "serial device is attached to the remote system\n"
4946            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4947
4948   /* See FIXME above.  */
4949   if (!target_async_permitted)
4950     wait_forever_enabled_p = 1;
4951
4952   /* If we're connected to a running target, target_preopen will kill it.
4953      Ask this question first, before target_preopen has a chance to kill
4954      anything.  */
4955   if (rs->remote_desc != NULL && !have_inferiors ())
4956     {
4957       if (from_tty
4958           && !query (_("Already connected to a remote target.  Disconnect? ")))
4959         error (_("Still connected."));
4960     }
4961
4962   /* Here the possibly existing remote target gets unpushed.  */
4963   target_preopen (from_tty);
4964
4965   /* Make sure we send the passed signals list the next time we resume.  */
4966   xfree (rs->last_pass_packet);
4967   rs->last_pass_packet = NULL;
4968
4969   /* Make sure we send the program signals list the next time we
4970      resume.  */
4971   xfree (rs->last_program_signals_packet);
4972   rs->last_program_signals_packet = NULL;
4973
4974   remote_fileio_reset ();
4975   reopen_exec_file ();
4976   reread_symbols ();
4977
4978   rs->remote_desc = remote_serial_open (name);
4979   if (!rs->remote_desc)
4980     perror_with_name (name);
4981
4982   if (baud_rate != -1)
4983     {
4984       if (serial_setbaudrate (rs->remote_desc, baud_rate))
4985         {
4986           /* The requested speed could not be set.  Error out to
4987              top level after closing remote_desc.  Take care to
4988              set remote_desc to NULL to avoid closing remote_desc
4989              more than once.  */
4990           serial_close (rs->remote_desc);
4991           rs->remote_desc = NULL;
4992           perror_with_name (name);
4993         }
4994     }
4995
4996   serial_setparity (rs->remote_desc, serial_parity);
4997   serial_raw (rs->remote_desc);
4998
4999   /* If there is something sitting in the buffer we might take it as a
5000      response to a command, which would be bad.  */
5001   serial_flush_input (rs->remote_desc);
5002
5003   if (from_tty)
5004     {
5005       puts_filtered ("Remote debugging using ");
5006       puts_filtered (name);
5007       puts_filtered ("\n");
5008     }
5009   push_target (target);         /* Switch to using remote target now.  */
5010
5011   /* Register extra event sources in the event loop.  */
5012   remote_async_inferior_event_token
5013     = create_async_event_handler (remote_async_inferior_event_handler,
5014                                   NULL);
5015   rs->notif_state = remote_notif_state_allocate ();
5016
5017   /* Reset the target state; these things will be queried either by
5018      remote_query_supported or as they are needed.  */
5019   reset_all_packet_configs_support ();
5020   rs->cached_wait_status = 0;
5021   rs->explicit_packet_size = 0;
5022   rs->noack_mode = 0;
5023   rs->extended = extended_p;
5024   rs->waiting_for_stop_reply = 0;
5025   rs->ctrlc_pending_p = 0;
5026   rs->got_ctrlc_during_io = 0;
5027
5028   rs->general_thread = not_sent_ptid;
5029   rs->continue_thread = not_sent_ptid;
5030   rs->remote_traceframe_number = -1;
5031
5032   rs->last_resume_exec_dir = EXEC_FORWARD;
5033
5034   /* Probe for ability to use "ThreadInfo" query, as required.  */
5035   rs->use_threadinfo_query = 1;
5036   rs->use_threadextra_query = 1;
5037
5038   readahead_cache_invalidate ();
5039
5040   /* Start out by owning the terminal.  */
5041   remote_async_terminal_ours_p = 1;
5042
5043   if (target_async_permitted)
5044     {
5045       /* FIXME: cagney/1999-09-23: During the initial connection it is
5046          assumed that the target is already ready and able to respond to
5047          requests.  Unfortunately remote_start_remote() eventually calls
5048          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
5049          around this.  Eventually a mechanism that allows
5050          wait_for_inferior() to expect/get timeouts will be
5051          implemented.  */
5052       wait_forever_enabled_p = 0;
5053     }
5054
5055   /* First delete any symbols previously loaded from shared libraries.  */
5056   no_shared_libraries (NULL, 0);
5057
5058   /* Start afresh.  */
5059   init_thread_list ();
5060
5061   /* Start the remote connection.  If error() or QUIT, discard this
5062      target (we'd otherwise be in an inconsistent state) and then
5063      propogate the error on up the exception chain.  This ensures that
5064      the caller doesn't stumble along blindly assuming that the
5065      function succeeded.  The CLI doesn't have this problem but other
5066      UI's, such as MI do.
5067
5068      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5069      this function should return an error indication letting the
5070      caller restore the previous state.  Unfortunately the command
5071      ``target remote'' is directly wired to this function making that
5072      impossible.  On a positive note, the CLI side of this problem has
5073      been fixed - the function set_cmd_context() makes it possible for
5074      all the ``target ....'' commands to share a common callback
5075      function.  See cli-dump.c.  */
5076   {
5077
5078     TRY
5079       {
5080         remote_start_remote (from_tty, target, extended_p);
5081       }
5082     CATCH (ex, RETURN_MASK_ALL)
5083       {
5084         /* Pop the partially set up target - unless something else did
5085            already before throwing the exception.  */
5086         if (rs->remote_desc != NULL)
5087           remote_unpush_target ();
5088         if (target_async_permitted)
5089           wait_forever_enabled_p = 1;
5090         throw_exception (ex);
5091       }
5092     END_CATCH
5093   }
5094
5095   remote_btrace_reset ();
5096
5097   if (target_async_permitted)
5098     wait_forever_enabled_p = 1;
5099 }
5100
5101 /* Detach the specified process.  */
5102
5103 static void
5104 remote_detach_pid (int pid)
5105 {
5106   struct remote_state *rs = get_remote_state ();
5107
5108   if (remote_multi_process_p (rs))
5109     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5110   else
5111     strcpy (rs->buf, "D");
5112
5113   putpkt (rs->buf);
5114   getpkt (&rs->buf, &rs->buf_size, 0);
5115
5116   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5117     ;
5118   else if (rs->buf[0] == '\0')
5119     error (_("Remote doesn't know how to detach"));
5120   else
5121     error (_("Can't detach process."));
5122 }
5123
5124 /* This detaches a program to which we previously attached, using
5125    inferior_ptid to identify the process.  After this is done, GDB
5126    can be used to debug some other program.  We better not have left
5127    any breakpoints in the target program or it'll die when it hits
5128    one.  */
5129
5130 static void
5131 remote_detach_1 (const char *args, int from_tty)
5132 {
5133   int pid = ptid_get_pid (inferior_ptid);
5134   struct remote_state *rs = get_remote_state ();
5135   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5136   int is_fork_parent;
5137
5138   if (args)
5139     error (_("Argument given to \"detach\" when remotely debugging."));
5140
5141   if (!target_has_execution)
5142     error (_("No process to detach from."));
5143
5144   target_announce_detach (from_tty);
5145
5146   /* Tell the remote target to detach.  */
5147   remote_detach_pid (pid);
5148
5149   /* Exit only if this is the only active inferior.  */
5150   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5151     puts_filtered (_("Ending remote debugging.\n"));
5152
5153   /* Check to see if we are detaching a fork parent.  Note that if we
5154      are detaching a fork child, tp == NULL.  */
5155   is_fork_parent = (tp != NULL
5156                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5157
5158   /* If doing detach-on-fork, we don't mourn, because that will delete
5159      breakpoints that should be available for the followed inferior.  */
5160   if (!is_fork_parent)
5161     target_mourn_inferior ();
5162   else
5163     {
5164       inferior_ptid = null_ptid;
5165       detach_inferior (pid);
5166     }
5167 }
5168
5169 static void
5170 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5171 {
5172   remote_detach_1 (args, from_tty);
5173 }
5174
5175 static void
5176 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5177 {
5178   remote_detach_1 (args, from_tty);
5179 }
5180
5181 /* Target follow-fork function for remote targets.  On entry, and
5182    at return, the current inferior is the fork parent.
5183
5184    Note that although this is currently only used for extended-remote,
5185    it is named remote_follow_fork in anticipation of using it for the
5186    remote target as well.  */
5187
5188 static int
5189 remote_follow_fork (struct target_ops *ops, int follow_child,
5190                     int detach_fork)
5191 {
5192   struct remote_state *rs = get_remote_state ();
5193   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5194
5195   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5196       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5197     {
5198       /* When following the parent and detaching the child, we detach
5199          the child here.  For the case of following the child and
5200          detaching the parent, the detach is done in the target-
5201          independent follow fork code in infrun.c.  We can't use
5202          target_detach when detaching an unfollowed child because
5203          the client side doesn't know anything about the child.  */
5204       if (detach_fork && !follow_child)
5205         {
5206           /* Detach the fork child.  */
5207           ptid_t child_ptid;
5208           pid_t child_pid;
5209
5210           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5211           child_pid = ptid_get_pid (child_ptid);
5212
5213           remote_detach_pid (child_pid);
5214           detach_inferior (child_pid);
5215         }
5216     }
5217   return 0;
5218 }
5219
5220 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5221    in the program space of the new inferior.  On entry and at return the
5222    current inferior is the exec'ing inferior.  INF is the new exec'd
5223    inferior, which may be the same as the exec'ing inferior unless
5224    follow-exec-mode is "new".  */
5225
5226 static void
5227 remote_follow_exec (struct target_ops *ops,
5228                     struct inferior *inf, char *execd_pathname)
5229 {
5230   /* We know that this is a target file name, so if it has the "target:"
5231      prefix we strip it off before saving it in the program space.  */
5232   if (is_target_filename (execd_pathname))
5233     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5234
5235   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5236 }
5237
5238 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5239
5240 static void
5241 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5242 {
5243   if (args)
5244     error (_("Argument given to \"disconnect\" when remotely debugging."));
5245
5246   /* Make sure we unpush even the extended remote targets.  Calling
5247      target_mourn_inferior won't unpush, and remote_mourn won't
5248      unpush if there is more than one inferior left.  */
5249   unpush_target (target);
5250   generic_mourn_inferior ();
5251
5252   if (from_tty)
5253     puts_filtered ("Ending remote debugging.\n");
5254 }
5255
5256 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5257    be chatty about it.  */
5258
5259 static void
5260 extended_remote_attach (struct target_ops *target, const char *args,
5261                         int from_tty)
5262 {
5263   struct remote_state *rs = get_remote_state ();
5264   int pid;
5265   char *wait_status = NULL;
5266
5267   pid = parse_pid_to_attach (args);
5268
5269   /* Remote PID can be freely equal to getpid, do not check it here the same
5270      way as in other targets.  */
5271
5272   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5273     error (_("This target does not support attaching to a process"));
5274
5275   if (from_tty)
5276     {
5277       char *exec_file = get_exec_file (0);
5278
5279       if (exec_file)
5280         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5281                            target_pid_to_str (pid_to_ptid (pid)));
5282       else
5283         printf_unfiltered (_("Attaching to %s\n"),
5284                            target_pid_to_str (pid_to_ptid (pid)));
5285
5286       gdb_flush (gdb_stdout);
5287     }
5288
5289   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5290   putpkt (rs->buf);
5291   getpkt (&rs->buf, &rs->buf_size, 0);
5292
5293   switch (packet_ok (rs->buf,
5294                      &remote_protocol_packets[PACKET_vAttach]))
5295     {
5296     case PACKET_OK:
5297       if (!target_is_non_stop_p ())
5298         {
5299           /* Save the reply for later.  */
5300           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5301           strcpy (wait_status, rs->buf);
5302         }
5303       else if (strcmp (rs->buf, "OK") != 0)
5304         error (_("Attaching to %s failed with: %s"),
5305                target_pid_to_str (pid_to_ptid (pid)),
5306                rs->buf);
5307       break;
5308     case PACKET_UNKNOWN:
5309       error (_("This target does not support attaching to a process"));
5310     default:
5311       error (_("Attaching to %s failed"),
5312              target_pid_to_str (pid_to_ptid (pid)));
5313     }
5314
5315   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5316
5317   inferior_ptid = pid_to_ptid (pid);
5318
5319   if (target_is_non_stop_p ())
5320     {
5321       struct thread_info *thread;
5322
5323       /* Get list of threads.  */
5324       remote_update_thread_list (target);
5325
5326       thread = first_thread_of_process (pid);
5327       if (thread)
5328         inferior_ptid = thread->ptid;
5329       else
5330         inferior_ptid = pid_to_ptid (pid);
5331
5332       /* Invalidate our notion of the remote current thread.  */
5333       record_currthread (rs, minus_one_ptid);
5334     }
5335   else
5336     {
5337       /* Now, if we have thread information, update inferior_ptid.  */
5338       inferior_ptid = remote_current_thread (inferior_ptid);
5339
5340       /* Add the main thread to the thread list.  */
5341       add_thread_silent (inferior_ptid);
5342     }
5343
5344   /* Next, if the target can specify a description, read it.  We do
5345      this before anything involving memory or registers.  */
5346   target_find_description ();
5347
5348   if (!target_is_non_stop_p ())
5349     {
5350       /* Use the previously fetched status.  */
5351       gdb_assert (wait_status != NULL);
5352
5353       if (target_can_async_p ())
5354         {
5355           struct notif_event *reply
5356             =  remote_notif_parse (&notif_client_stop, wait_status);
5357
5358           push_stop_reply ((struct stop_reply *) reply);
5359
5360           target_async (1);
5361         }
5362       else
5363         {
5364           gdb_assert (wait_status != NULL);
5365           strcpy (rs->buf, wait_status);
5366           rs->cached_wait_status = 1;
5367         }
5368     }
5369   else
5370     gdb_assert (wait_status == NULL);
5371 }
5372
5373 /* Implementation of the to_post_attach method.  */
5374
5375 static void
5376 extended_remote_post_attach (struct target_ops *ops, int pid)
5377 {
5378   /* Get text, data & bss offsets.  */
5379   get_offsets ();
5380
5381   /* In certain cases GDB might not have had the chance to start
5382      symbol lookup up until now.  This could happen if the debugged
5383      binary is not using shared libraries, the vsyscall page is not
5384      present (on Linux) and the binary itself hadn't changed since the
5385      debugging process was started.  */
5386   if (symfile_objfile != NULL)
5387     remote_check_symbols();
5388 }
5389
5390 \f
5391 /* Check for the availability of vCont.  This function should also check
5392    the response.  */
5393
5394 static void
5395 remote_vcont_probe (struct remote_state *rs)
5396 {
5397   char *buf;
5398
5399   strcpy (rs->buf, "vCont?");
5400   putpkt (rs->buf);
5401   getpkt (&rs->buf, &rs->buf_size, 0);
5402   buf = rs->buf;
5403
5404   /* Make sure that the features we assume are supported.  */
5405   if (startswith (buf, "vCont"))
5406     {
5407       char *p = &buf[5];
5408       int support_c, support_C;
5409
5410       rs->supports_vCont.s = 0;
5411       rs->supports_vCont.S = 0;
5412       support_c = 0;
5413       support_C = 0;
5414       rs->supports_vCont.t = 0;
5415       rs->supports_vCont.r = 0;
5416       while (p && *p == ';')
5417         {
5418           p++;
5419           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5420             rs->supports_vCont.s = 1;
5421           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5422             rs->supports_vCont.S = 1;
5423           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5424             support_c = 1;
5425           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5426             support_C = 1;
5427           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5428             rs->supports_vCont.t = 1;
5429           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5430             rs->supports_vCont.r = 1;
5431
5432           p = strchr (p, ';');
5433         }
5434
5435       /* If c, and C are not all supported, we can't use vCont.  Clearing
5436          BUF will make packet_ok disable the packet.  */
5437       if (!support_c || !support_C)
5438         buf[0] = 0;
5439     }
5440
5441   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5442 }
5443
5444 /* Helper function for building "vCont" resumptions.  Write a
5445    resumption to P.  ENDP points to one-passed-the-end of the buffer
5446    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5447    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5448    resumed thread should be single-stepped and/or signalled.  If PTID
5449    equals minus_one_ptid, then all threads are resumed; if PTID
5450    represents a process, then all threads of the process are resumed;
5451    the thread to be stepped and/or signalled is given in the global
5452    INFERIOR_PTID.  */
5453
5454 static char *
5455 append_resumption (char *p, char *endp,
5456                    ptid_t ptid, int step, enum gdb_signal siggnal)
5457 {
5458   struct remote_state *rs = get_remote_state ();
5459
5460   if (step && siggnal != GDB_SIGNAL_0)
5461     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5462   else if (step
5463            /* GDB is willing to range step.  */
5464            && use_range_stepping
5465            /* Target supports range stepping.  */
5466            && rs->supports_vCont.r
5467            /* We don't currently support range stepping multiple
5468               threads with a wildcard (though the protocol allows it,
5469               so stubs shouldn't make an active effort to forbid
5470               it).  */
5471            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5472     {
5473       struct thread_info *tp;
5474
5475       if (ptid_equal (ptid, minus_one_ptid))
5476         {
5477           /* If we don't know about the target thread's tid, then
5478              we're resuming magic_null_ptid (see caller).  */
5479           tp = find_thread_ptid (magic_null_ptid);
5480         }
5481       else
5482         tp = find_thread_ptid (ptid);
5483       gdb_assert (tp != NULL);
5484
5485       if (tp->control.may_range_step)
5486         {
5487           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5488
5489           p += xsnprintf (p, endp - p, ";r%s,%s",
5490                           phex_nz (tp->control.step_range_start,
5491                                    addr_size),
5492                           phex_nz (tp->control.step_range_end,
5493                                    addr_size));
5494         }
5495       else
5496         p += xsnprintf (p, endp - p, ";s");
5497     }
5498   else if (step)
5499     p += xsnprintf (p, endp - p, ";s");
5500   else if (siggnal != GDB_SIGNAL_0)
5501     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5502   else
5503     p += xsnprintf (p, endp - p, ";c");
5504
5505   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5506     {
5507       ptid_t nptid;
5508
5509       /* All (-1) threads of process.  */
5510       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5511
5512       p += xsnprintf (p, endp - p, ":");
5513       p = write_ptid (p, endp, nptid);
5514     }
5515   else if (!ptid_equal (ptid, minus_one_ptid))
5516     {
5517       p += xsnprintf (p, endp - p, ":");
5518       p = write_ptid (p, endp, ptid);
5519     }
5520
5521   return p;
5522 }
5523
5524 /* Clear the thread's private info on resume.  */
5525
5526 static void
5527 resume_clear_thread_private_info (struct thread_info *thread)
5528 {
5529   if (thread->priv != NULL)
5530     {
5531       thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5532       thread->priv->watch_data_address = 0;
5533     }
5534 }
5535
5536 /* Append a vCont continue-with-signal action for threads that have a
5537    non-zero stop signal.  */
5538
5539 static char *
5540 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5541 {
5542   struct thread_info *thread;
5543
5544   ALL_NON_EXITED_THREADS (thread)
5545     if (ptid_match (thread->ptid, ptid)
5546         && !ptid_equal (inferior_ptid, thread->ptid)
5547         && thread->suspend.stop_signal != GDB_SIGNAL_0)
5548       {
5549         p = append_resumption (p, endp, thread->ptid,
5550                                0, thread->suspend.stop_signal);
5551         thread->suspend.stop_signal = GDB_SIGNAL_0;
5552         resume_clear_thread_private_info (thread);
5553       }
5554
5555   return p;
5556 }
5557
5558 /* Resume the remote inferior by using a "vCont" packet.  The thread
5559    to be resumed is PTID; STEP and SIGGNAL indicate whether the
5560    resumed thread should be single-stepped and/or signalled.  If PTID
5561    equals minus_one_ptid, then all threads are resumed; the thread to
5562    be stepped and/or signalled is given in the global INFERIOR_PTID.
5563    This function returns non-zero iff it resumes the inferior.
5564
5565    This function issues a strict subset of all possible vCont commands at the
5566    moment.  */
5567
5568 static int
5569 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5570 {
5571   struct remote_state *rs = get_remote_state ();
5572   char *p;
5573   char *endp;
5574
5575   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5576     remote_vcont_probe (rs);
5577
5578   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5579     return 0;
5580
5581   p = rs->buf;
5582   endp = rs->buf + get_remote_packet_size ();
5583
5584   /* If we could generate a wider range of packets, we'd have to worry
5585      about overflowing BUF.  Should there be a generic
5586      "multi-part-packet" packet?  */
5587
5588   p += xsnprintf (p, endp - p, "vCont");
5589
5590   if (ptid_equal (ptid, magic_null_ptid))
5591     {
5592       /* MAGIC_NULL_PTID means that we don't have any active threads,
5593          so we don't have any TID numbers the inferior will
5594          understand.  Make sure to only send forms that do not specify
5595          a TID.  */
5596       append_resumption (p, endp, minus_one_ptid, step, siggnal);
5597     }
5598   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5599     {
5600       /* Resume all threads (of all processes, or of a single
5601          process), with preference for INFERIOR_PTID.  This assumes
5602          inferior_ptid belongs to the set of all threads we are about
5603          to resume.  */
5604       if (step || siggnal != GDB_SIGNAL_0)
5605         {
5606           /* Step inferior_ptid, with or without signal.  */
5607           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5608         }
5609
5610       /* Also pass down any pending signaled resumption for other
5611          threads not the current.  */
5612       p = append_pending_thread_resumptions (p, endp, ptid);
5613
5614       /* And continue others without a signal.  */
5615       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5616     }
5617   else
5618     {
5619       /* Scheduler locking; resume only PTID.  */
5620       append_resumption (p, endp, ptid, step, siggnal);
5621     }
5622
5623   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5624   putpkt (rs->buf);
5625
5626   if (target_is_non_stop_p ())
5627     {
5628       /* In non-stop, the stub replies to vCont with "OK".  The stop
5629          reply will be reported asynchronously by means of a `%Stop'
5630          notification.  */
5631       getpkt (&rs->buf, &rs->buf_size, 0);
5632       if (strcmp (rs->buf, "OK") != 0)
5633         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5634     }
5635
5636   return 1;
5637 }
5638
5639 /* Tell the remote machine to resume.  */
5640
5641 static void
5642 remote_resume (struct target_ops *ops,
5643                ptid_t ptid, int step, enum gdb_signal siggnal)
5644 {
5645   struct remote_state *rs = get_remote_state ();
5646   char *buf;
5647   struct thread_info *thread;
5648
5649   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5650      (explained in remote-notif.c:handle_notification) so
5651      remote_notif_process is not called.  We need find a place where
5652      it is safe to start a 'vNotif' sequence.  It is good to do it
5653      before resuming inferior, because inferior was stopped and no RSP
5654      traffic at that moment.  */
5655   if (!target_is_non_stop_p ())
5656     remote_notif_process (rs->notif_state, &notif_client_stop);
5657
5658   rs->last_sent_signal = siggnal;
5659   rs->last_sent_step = step;
5660
5661   rs->last_resume_exec_dir = execution_direction;
5662
5663   /* The vCont packet doesn't need to specify threads via Hc.  */
5664   /* No reverse support (yet) for vCont.  */
5665   if (execution_direction != EXEC_REVERSE)
5666     if (remote_vcont_resume (ptid, step, siggnal))
5667       goto done;
5668
5669   /* All other supported resume packets do use Hc, so set the continue
5670      thread.  */
5671   if (ptid_equal (ptid, minus_one_ptid))
5672     set_continue_thread (any_thread_ptid);
5673   else
5674     set_continue_thread (ptid);
5675
5676   ALL_NON_EXITED_THREADS (thread)
5677     resume_clear_thread_private_info (thread);
5678
5679   buf = rs->buf;
5680   if (execution_direction == EXEC_REVERSE)
5681     {
5682       /* We don't pass signals to the target in reverse exec mode.  */
5683       if (info_verbose && siggnal != GDB_SIGNAL_0)
5684         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5685                  siggnal);
5686
5687       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5688         error (_("Remote reverse-step not supported."));
5689       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5690         error (_("Remote reverse-continue not supported."));
5691
5692       strcpy (buf, step ? "bs" : "bc");
5693     }
5694   else if (siggnal != GDB_SIGNAL_0)
5695     {
5696       buf[0] = step ? 'S' : 'C';
5697       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5698       buf[2] = tohex (((int) siggnal) & 0xf);
5699       buf[3] = '\0';
5700     }
5701   else
5702     strcpy (buf, step ? "s" : "c");
5703
5704   putpkt (buf);
5705
5706  done:
5707   /* We are about to start executing the inferior, let's register it
5708      with the event loop.  NOTE: this is the one place where all the
5709      execution commands end up.  We could alternatively do this in each
5710      of the execution commands in infcmd.c.  */
5711   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5712      into infcmd.c in order to allow inferior function calls to work
5713      NOT asynchronously.  */
5714   if (target_can_async_p ())
5715     target_async (1);
5716
5717   /* We've just told the target to resume.  The remote server will
5718      wait for the inferior to stop, and then send a stop reply.  In
5719      the mean time, we can't start another command/query ourselves
5720      because the stub wouldn't be ready to process it.  This applies
5721      only to the base all-stop protocol, however.  In non-stop (which
5722      only supports vCont), the stub replies with an "OK", and is
5723      immediate able to process further serial input.  */
5724   if (!target_is_non_stop_p ())
5725     rs->waiting_for_stop_reply = 1;
5726 }
5727 \f
5728
5729 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
5730    thread, all threads of a remote process, or all threads of all
5731    processes.  */
5732
5733 static void
5734 remote_stop_ns (ptid_t ptid)
5735 {
5736   struct remote_state *rs = get_remote_state ();
5737   char *p = rs->buf;
5738   char *endp = rs->buf + get_remote_packet_size ();
5739
5740   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5741     remote_vcont_probe (rs);
5742
5743   if (!rs->supports_vCont.t)
5744     error (_("Remote server does not support stopping threads"));
5745
5746   if (ptid_equal (ptid, minus_one_ptid)
5747       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5748     p += xsnprintf (p, endp - p, "vCont;t");
5749   else
5750     {
5751       ptid_t nptid;
5752
5753       p += xsnprintf (p, endp - p, "vCont;t:");
5754
5755       if (ptid_is_pid (ptid))
5756           /* All (-1) threads of process.  */
5757         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5758       else
5759         {
5760           /* Small optimization: if we already have a stop reply for
5761              this thread, no use in telling the stub we want this
5762              stopped.  */
5763           if (peek_stop_reply (ptid))
5764             return;
5765
5766           nptid = ptid;
5767         }
5768
5769       write_ptid (p, endp, nptid);
5770     }
5771
5772   /* In non-stop, we get an immediate OK reply.  The stop reply will
5773      come in asynchronously by notification.  */
5774   putpkt (rs->buf);
5775   getpkt (&rs->buf, &rs->buf_size, 0);
5776   if (strcmp (rs->buf, "OK") != 0)
5777     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5778 }
5779
5780 /* All-stop version of target_interrupt.  Sends a break or a ^C to
5781    interrupt the remote target.  It is undefined which thread of which
5782    process reports the interrupt.  */
5783
5784 static void
5785 remote_interrupt_as (void)
5786 {
5787   struct remote_state *rs = get_remote_state ();
5788
5789   rs->ctrlc_pending_p = 1;
5790
5791   /* If the inferior is stopped already, but the core didn't know
5792      about it yet, just ignore the request.  The cached wait status
5793      will be collected in remote_wait.  */
5794   if (rs->cached_wait_status)
5795     return;
5796
5797   /* Send interrupt_sequence to remote target.  */
5798   send_interrupt_sequence ();
5799 }
5800
5801 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
5802    the remote target.  It is undefined which thread of which process
5803    reports the interrupt.  Throws an error if the packet is not
5804    supported by the server.  */
5805
5806 static void
5807 remote_interrupt_ns (void)
5808 {
5809   struct remote_state *rs = get_remote_state ();
5810   char *p = rs->buf;
5811   char *endp = rs->buf + get_remote_packet_size ();
5812
5813   xsnprintf (p, endp - p, "vCtrlC");
5814
5815   /* In non-stop, we get an immediate OK reply.  The stop reply will
5816      come in asynchronously by notification.  */
5817   putpkt (rs->buf);
5818   getpkt (&rs->buf, &rs->buf_size, 0);
5819
5820   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5821     {
5822     case PACKET_OK:
5823       break;
5824     case PACKET_UNKNOWN:
5825       error (_("No support for interrupting the remote target."));
5826     case PACKET_ERROR:
5827       error (_("Interrupting target failed: %s"), rs->buf);
5828     }
5829 }
5830
5831 /* Implement the to_stop function for the remote targets.  */
5832
5833 static void
5834 remote_stop (struct target_ops *self, ptid_t ptid)
5835 {
5836   if (remote_debug)
5837     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5838
5839   if (target_is_non_stop_p ())
5840     remote_stop_ns (ptid);
5841   else
5842     {
5843       /* We don't currently have a way to transparently pause the
5844          remote target in all-stop mode.  Interrupt it instead.  */
5845       remote_interrupt_as ();
5846     }
5847 }
5848
5849 /* Implement the to_interrupt function for the remote targets.  */
5850
5851 static void
5852 remote_interrupt (struct target_ops *self, ptid_t ptid)
5853 {
5854   struct remote_state *rs = get_remote_state ();
5855
5856   if (remote_debug)
5857     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5858
5859   if (target_is_non_stop_p ())
5860     remote_interrupt_ns ();
5861   else
5862     remote_interrupt_as ();
5863 }
5864
5865 /* Implement the to_pass_ctrlc function for the remote targets.  */
5866
5867 static void
5868 remote_pass_ctrlc (struct target_ops *self)
5869 {
5870   struct remote_state *rs = get_remote_state ();
5871
5872   if (remote_debug)
5873     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
5874
5875   /* If we're starting up, we're not fully synced yet.  Quit
5876      immediately.  */
5877   if (rs->starting_up)
5878     quit ();
5879   /* If ^C has already been sent once, offer to disconnect.  */
5880   else if (rs->ctrlc_pending_p)
5881     interrupt_query ();
5882   else
5883     target_interrupt (inferior_ptid);
5884 }
5885
5886 /* Ask the user what to do when an interrupt is received.  */
5887
5888 static void
5889 interrupt_query (void)
5890 {
5891   struct remote_state *rs = get_remote_state ();
5892
5893   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5894     {
5895       if (query (_("The target is not responding to interrupt requests.\n"
5896                    "Stop debugging it? ")))
5897         {
5898           remote_unpush_target ();
5899           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5900         }
5901     }
5902   else
5903     {
5904       if (query (_("Interrupted while waiting for the program.\n"
5905                    "Give up waiting? ")))
5906         quit ();
5907     }
5908 }
5909
5910 /* Enable/disable target terminal ownership.  Most targets can use
5911    terminal groups to control terminal ownership.  Remote targets are
5912    different in that explicit transfer of ownership to/from GDB/target
5913    is required.  */
5914
5915 static void
5916 remote_terminal_inferior (struct target_ops *self)
5917 {
5918   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5919      idempotent.  The event-loop GDB talking to an asynchronous target
5920      with a synchronous command calls this function from both
5921      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
5922      transfer the terminal to the target when it shouldn't this guard
5923      can go away.  */
5924   if (!remote_async_terminal_ours_p)
5925     return;
5926   remote_async_terminal_ours_p = 0;
5927   /* NOTE: At this point we could also register our selves as the
5928      recipient of all input.  Any characters typed could then be
5929      passed on down to the target.  */
5930 }
5931
5932 static void
5933 remote_terminal_ours (struct target_ops *self)
5934 {
5935   /* See FIXME in remote_terminal_inferior.  */
5936   if (remote_async_terminal_ours_p)
5937     return;
5938   remote_async_terminal_ours_p = 1;
5939 }
5940
5941 static void
5942 remote_console_output (char *msg)
5943 {
5944   char *p;
5945
5946   for (p = msg; p[0] && p[1]; p += 2)
5947     {
5948       char tb[2];
5949       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5950
5951       tb[0] = c;
5952       tb[1] = 0;
5953       fputs_unfiltered (tb, gdb_stdtarg);
5954     }
5955   gdb_flush (gdb_stdtarg);
5956 }
5957
5958 typedef struct cached_reg
5959 {
5960   int num;
5961   gdb_byte data[MAX_REGISTER_SIZE];
5962 } cached_reg_t;
5963
5964 DEF_VEC_O(cached_reg_t);
5965
5966 typedef struct stop_reply
5967 {
5968   struct notif_event base;
5969
5970   /* The identifier of the thread about this event  */
5971   ptid_t ptid;
5972
5973   /* The remote state this event is associated with.  When the remote
5974      connection, represented by a remote_state object, is closed,
5975      all the associated stop_reply events should be released.  */
5976   struct remote_state *rs;
5977
5978   struct target_waitstatus ws;
5979
5980   /* Expedited registers.  This makes remote debugging a bit more
5981      efficient for those targets that provide critical registers as
5982      part of their normal status mechanism (as another roundtrip to
5983      fetch them is avoided).  */
5984   VEC(cached_reg_t) *regcache;
5985
5986   enum target_stop_reason stop_reason;
5987
5988   CORE_ADDR watch_data_address;
5989
5990   int core;
5991 } *stop_reply_p;
5992
5993 DECLARE_QUEUE_P (stop_reply_p);
5994 DEFINE_QUEUE_P (stop_reply_p);
5995 /* The list of already fetched and acknowledged stop events.  This
5996    queue is used for notification Stop, and other notifications
5997    don't need queue for their events, because the notification events
5998    of Stop can't be consumed immediately, so that events should be
5999    queued first, and be consumed by remote_wait_{ns,as} one per
6000    time.  Other notifications can consume their events immediately,
6001    so queue is not needed for them.  */
6002 static QUEUE (stop_reply_p) *stop_reply_queue;
6003
6004 static void
6005 stop_reply_xfree (struct stop_reply *r)
6006 {
6007   notif_event_xfree ((struct notif_event *) r);
6008 }
6009
6010 /* Return the length of the stop reply queue.  */
6011
6012 static int
6013 stop_reply_queue_length (void)
6014 {
6015   return QUEUE_length (stop_reply_p, stop_reply_queue);
6016 }
6017
6018 static void
6019 remote_notif_stop_parse (struct notif_client *self, char *buf,
6020                          struct notif_event *event)
6021 {
6022   remote_parse_stop_reply (buf, (struct stop_reply *) event);
6023 }
6024
6025 static void
6026 remote_notif_stop_ack (struct notif_client *self, char *buf,
6027                        struct notif_event *event)
6028 {
6029   struct stop_reply *stop_reply = (struct stop_reply *) event;
6030
6031   /* acknowledge */
6032   putpkt (self->ack_command);
6033
6034   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6035       /* We got an unknown stop reply.  */
6036       error (_("Unknown stop reply"));
6037
6038   push_stop_reply (stop_reply);
6039 }
6040
6041 static int
6042 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6043 {
6044   /* We can't get pending events in remote_notif_process for
6045      notification stop, and we have to do this in remote_wait_ns
6046      instead.  If we fetch all queued events from stub, remote stub
6047      may exit and we have no chance to process them back in
6048      remote_wait_ns.  */
6049   mark_async_event_handler (remote_async_inferior_event_token);
6050   return 0;
6051 }
6052
6053 static void
6054 stop_reply_dtr (struct notif_event *event)
6055 {
6056   struct stop_reply *r = (struct stop_reply *) event;
6057
6058   VEC_free (cached_reg_t, r->regcache);
6059 }
6060
6061 static struct notif_event *
6062 remote_notif_stop_alloc_reply (void)
6063 {
6064   /* We cast to a pointer to the "base class".  */
6065   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6066
6067   r->dtr = stop_reply_dtr;
6068
6069   return r;
6070 }
6071
6072 /* A client of notification Stop.  */
6073
6074 struct notif_client notif_client_stop =
6075 {
6076   "Stop",
6077   "vStopped",
6078   remote_notif_stop_parse,
6079   remote_notif_stop_ack,
6080   remote_notif_stop_can_get_pending_events,
6081   remote_notif_stop_alloc_reply,
6082   REMOTE_NOTIF_STOP,
6083 };
6084
6085 /* A parameter to pass data in and out.  */
6086
6087 struct queue_iter_param
6088 {
6089   void *input;
6090   struct stop_reply *output;
6091 };
6092
6093 /* Determine if THREAD is a pending fork parent thread.  ARG contains
6094    the pid of the process that owns the threads we want to check, or
6095    -1 if we want to check all threads.  */
6096
6097 static int
6098 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6099                         ptid_t thread_ptid)
6100 {
6101   if (ws->kind == TARGET_WAITKIND_FORKED
6102       || ws->kind == TARGET_WAITKIND_VFORKED)
6103     {
6104       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6105         return 1;
6106     }
6107
6108   return 0;
6109 }
6110
6111 /* Check whether EVENT is a fork event, and if it is, remove the
6112    fork child from the context list passed in DATA.  */
6113
6114 static int
6115 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6116                               QUEUE_ITER (stop_reply_p) *iter,
6117                               stop_reply_p event,
6118                               void *data)
6119 {
6120   struct queue_iter_param *param = (struct queue_iter_param *) data;
6121   struct threads_listing_context *context
6122     = (struct threads_listing_context *) param->input;
6123
6124   if (event->ws.kind == TARGET_WAITKIND_FORKED
6125       || event->ws.kind == TARGET_WAITKIND_VFORKED
6126       || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6127     threads_listing_context_remove (&event->ws, context);
6128
6129   return 1;
6130 }
6131
6132 /* If CONTEXT contains any fork child threads that have not been
6133    reported yet, remove them from the CONTEXT list.  If such a
6134    thread exists it is because we are stopped at a fork catchpoint
6135    and have not yet called follow_fork, which will set up the
6136    host-side data structures for the new process.  */
6137
6138 static void
6139 remove_new_fork_children (struct threads_listing_context *context)
6140 {
6141   struct thread_info * thread;
6142   int pid = -1;
6143   struct notif_client *notif = &notif_client_stop;
6144   struct queue_iter_param param;
6145
6146   /* For any threads stopped at a fork event, remove the corresponding
6147      fork child threads from the CONTEXT list.  */
6148   ALL_NON_EXITED_THREADS (thread)
6149     {
6150       struct target_waitstatus *ws;
6151
6152       if (thread->suspend.waitstatus_pending_p)
6153         ws = &thread->suspend.waitstatus;
6154       else
6155         ws = &thread->pending_follow;
6156
6157       if (is_pending_fork_parent (ws, pid, thread->ptid))
6158         {
6159           threads_listing_context_remove (ws, context);
6160         }
6161     }
6162
6163   /* Check for any pending fork events (not reported or processed yet)
6164      in process PID and remove those fork child threads from the
6165      CONTEXT list as well.  */
6166   remote_notif_get_pending_events (notif);
6167   param.input = context;
6168   param.output = NULL;
6169   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6170                  remove_child_of_pending_fork, &param);
6171 }
6172
6173 /* Remove stop replies in the queue if its pid is equal to the given
6174    inferior's pid.  */
6175
6176 static int
6177 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6178                                 QUEUE_ITER (stop_reply_p) *iter,
6179                                 stop_reply_p event,
6180                                 void *data)
6181 {
6182   struct queue_iter_param *param = (struct queue_iter_param *) data;
6183   struct inferior *inf = (struct inferior *) param->input;
6184
6185   if (ptid_get_pid (event->ptid) == inf->pid)
6186     {
6187       stop_reply_xfree (event);
6188       QUEUE_remove_elem (stop_reply_p, q, iter);
6189     }
6190
6191   return 1;
6192 }
6193
6194 /* Discard all pending stop replies of inferior INF.  */
6195
6196 static void
6197 discard_pending_stop_replies (struct inferior *inf)
6198 {
6199   struct queue_iter_param param;
6200   struct stop_reply *reply;
6201   struct remote_state *rs = get_remote_state ();
6202   struct remote_notif_state *rns = rs->notif_state;
6203
6204   /* This function can be notified when an inferior exists.  When the
6205      target is not remote, the notification state is NULL.  */
6206   if (rs->remote_desc == NULL)
6207     return;
6208
6209   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6210
6211   /* Discard the in-flight notification.  */
6212   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6213     {
6214       stop_reply_xfree (reply);
6215       rns->pending_event[notif_client_stop.id] = NULL;
6216     }
6217
6218   param.input = inf;
6219   param.output = NULL;
6220   /* Discard the stop replies we have already pulled with
6221      vStopped.  */
6222   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6223                  remove_stop_reply_for_inferior, &param);
6224 }
6225
6226 /* If its remote state is equal to the given remote state,
6227    remove EVENT from the stop reply queue.  */
6228
6229 static int
6230 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6231                                    QUEUE_ITER (stop_reply_p) *iter,
6232                                    stop_reply_p event,
6233                                    void *data)
6234 {
6235   struct queue_iter_param *param = (struct queue_iter_param *) data;
6236   struct remote_state *rs = (struct remote_state *) param->input;
6237
6238   if (event->rs == rs)
6239     {
6240       stop_reply_xfree (event);
6241       QUEUE_remove_elem (stop_reply_p, q, iter);
6242     }
6243
6244   return 1;
6245 }
6246
6247 /* Discard the stop replies for RS in stop_reply_queue.  */
6248
6249 static void
6250 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6251 {
6252   struct queue_iter_param param;
6253
6254   param.input = rs;
6255   param.output = NULL;
6256   /* Discard the stop replies we have already pulled with
6257      vStopped.  */
6258   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6259                  remove_stop_reply_of_remote_state, &param);
6260 }
6261
6262 /* A parameter to pass data in and out.  */
6263
6264 static int
6265 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6266                                    QUEUE_ITER (stop_reply_p) *iter,
6267                                    stop_reply_p event,
6268                                    void *data)
6269 {
6270   struct queue_iter_param *param = (struct queue_iter_param *) data;
6271   ptid_t *ptid = (ptid_t *) param->input;
6272
6273   if (ptid_match (event->ptid, *ptid))
6274     {
6275       param->output = event;
6276       QUEUE_remove_elem (stop_reply_p, q, iter);
6277       return 0;
6278     }
6279
6280   return 1;
6281 }
6282
6283 /* Remove the first reply in 'stop_reply_queue' which matches
6284    PTID.  */
6285
6286 static struct stop_reply *
6287 remote_notif_remove_queued_reply (ptid_t ptid)
6288 {
6289   struct queue_iter_param param;
6290
6291   param.input = &ptid;
6292   param.output = NULL;
6293
6294   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6295                  remote_notif_remove_once_on_match, &param);
6296   if (notif_debug)
6297     fprintf_unfiltered (gdb_stdlog,
6298                         "notif: discard queued event: 'Stop' in %s\n",
6299                         target_pid_to_str (ptid));
6300
6301   return param.output;
6302 }
6303
6304 /* Look for a queued stop reply belonging to PTID.  If one is found,
6305    remove it from the queue, and return it.  Returns NULL if none is
6306    found.  If there are still queued events left to process, tell the
6307    event loop to get back to target_wait soon.  */
6308
6309 static struct stop_reply *
6310 queued_stop_reply (ptid_t ptid)
6311 {
6312   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6313
6314   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6315     /* There's still at least an event left.  */
6316     mark_async_event_handler (remote_async_inferior_event_token);
6317
6318   return r;
6319 }
6320
6321 /* Push a fully parsed stop reply in the stop reply queue.  Since we
6322    know that we now have at least one queued event left to pass to the
6323    core side, tell the event loop to get back to target_wait soon.  */
6324
6325 static void
6326 push_stop_reply (struct stop_reply *new_event)
6327 {
6328   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6329
6330   if (notif_debug)
6331     fprintf_unfiltered (gdb_stdlog,
6332                         "notif: push 'Stop' %s to queue %d\n",
6333                         target_pid_to_str (new_event->ptid),
6334                         QUEUE_length (stop_reply_p,
6335                                       stop_reply_queue));
6336
6337   mark_async_event_handler (remote_async_inferior_event_token);
6338 }
6339
6340 static int
6341 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6342                               QUEUE_ITER (stop_reply_p) *iter,
6343                               struct stop_reply *event,
6344                               void *data)
6345 {
6346   ptid_t *ptid = (ptid_t *) data;
6347
6348   return !(ptid_equal (*ptid, event->ptid)
6349            && event->ws.kind == TARGET_WAITKIND_STOPPED);
6350 }
6351
6352 /* Returns true if we have a stop reply for PTID.  */
6353
6354 static int
6355 peek_stop_reply (ptid_t ptid)
6356 {
6357   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6358                          stop_reply_match_ptid_and_ws, &ptid);
6359 }
6360
6361 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
6362    starting with P and ending with PEND matches PREFIX.  */
6363
6364 static int
6365 strprefix (const char *p, const char *pend, const char *prefix)
6366 {
6367   for ( ; p < pend; p++, prefix++)
6368     if (*p != *prefix)
6369       return 0;
6370   return *prefix == '\0';
6371 }
6372
6373 /* Parse the stop reply in BUF.  Either the function succeeds, and the
6374    result is stored in EVENT, or throws an error.  */
6375
6376 static void
6377 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6378 {
6379   struct remote_arch_state *rsa = get_remote_arch_state ();
6380   ULONGEST addr;
6381   char *p;
6382   int skipregs = 0;
6383
6384   event->ptid = null_ptid;
6385   event->rs = get_remote_state ();
6386   event->ws.kind = TARGET_WAITKIND_IGNORE;
6387   event->ws.value.integer = 0;
6388   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6389   event->regcache = NULL;
6390   event->core = -1;
6391
6392   switch (buf[0])
6393     {
6394     case 'T':           /* Status with PC, SP, FP, ...  */
6395       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
6396       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
6397             ss = signal number
6398             n... = register number
6399             r... = register contents
6400       */
6401
6402       p = &buf[3];      /* after Txx */
6403       while (*p)
6404         {
6405           char *p1;
6406           int fieldsize;
6407
6408           p1 = strchr (p, ':');
6409           if (p1 == NULL)
6410             error (_("Malformed packet(a) (missing colon): %s\n\
6411 Packet: '%s'\n"),
6412                    p, buf);
6413           if (p == p1)
6414             error (_("Malformed packet(a) (missing register number): %s\n\
6415 Packet: '%s'\n"),
6416                    p, buf);
6417
6418           /* Some "registers" are actually extended stop information.
6419              Note if you're adding a new entry here: GDB 7.9 and
6420              earlier assume that all register "numbers" that start
6421              with an hex digit are real register numbers.  Make sure
6422              the server only sends such a packet if it knows the
6423              client understands it.  */
6424
6425           if (strprefix (p, p1, "thread"))
6426             event->ptid = read_ptid (++p1, &p);
6427           else if (strprefix (p, p1, "syscall_entry"))
6428             {
6429               ULONGEST sysno;
6430
6431               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6432               p = unpack_varlen_hex (++p1, &sysno);
6433               event->ws.value.syscall_number = (int) sysno;
6434             }
6435           else if (strprefix (p, p1, "syscall_return"))
6436             {
6437               ULONGEST sysno;
6438
6439               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6440               p = unpack_varlen_hex (++p1, &sysno);
6441               event->ws.value.syscall_number = (int) sysno;
6442             }
6443           else if (strprefix (p, p1, "watch")
6444                    || strprefix (p, p1, "rwatch")
6445                    || strprefix (p, p1, "awatch"))
6446             {
6447               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6448               p = unpack_varlen_hex (++p1, &addr);
6449               event->watch_data_address = (CORE_ADDR) addr;
6450             }
6451           else if (strprefix (p, p1, "swbreak"))
6452             {
6453               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6454
6455               /* Make sure the stub doesn't forget to indicate support
6456                  with qSupported.  */
6457               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6458                 error (_("Unexpected swbreak stop reason"));
6459
6460               /* The value part is documented as "must be empty",
6461                  though we ignore it, in case we ever decide to make
6462                  use of it in a backward compatible way.  */
6463               p = strchrnul (p1 + 1, ';');
6464             }
6465           else if (strprefix (p, p1, "hwbreak"))
6466             {
6467               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6468
6469               /* Make sure the stub doesn't forget to indicate support
6470                  with qSupported.  */
6471               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6472                 error (_("Unexpected hwbreak stop reason"));
6473
6474               /* See above.  */
6475               p = strchrnul (p1 + 1, ';');
6476             }
6477           else if (strprefix (p, p1, "library"))
6478             {
6479               event->ws.kind = TARGET_WAITKIND_LOADED;
6480               p = strchrnul (p1 + 1, ';');
6481             }
6482           else if (strprefix (p, p1, "replaylog"))
6483             {
6484               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6485               /* p1 will indicate "begin" or "end", but it makes
6486                  no difference for now, so ignore it.  */
6487               p = strchrnul (p1 + 1, ';');
6488             }
6489           else if (strprefix (p, p1, "core"))
6490             {
6491               ULONGEST c;
6492
6493               p = unpack_varlen_hex (++p1, &c);
6494               event->core = c;
6495             }
6496           else if (strprefix (p, p1, "fork"))
6497             {
6498               event->ws.value.related_pid = read_ptid (++p1, &p);
6499               event->ws.kind = TARGET_WAITKIND_FORKED;
6500             }
6501           else if (strprefix (p, p1, "vfork"))
6502             {
6503               event->ws.value.related_pid = read_ptid (++p1, &p);
6504               event->ws.kind = TARGET_WAITKIND_VFORKED;
6505             }
6506           else if (strprefix (p, p1, "vforkdone"))
6507             {
6508               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6509               p = strchrnul (p1 + 1, ';');
6510             }
6511           else if (strprefix (p, p1, "exec"))
6512             {
6513               ULONGEST ignored;
6514               char pathname[PATH_MAX];
6515               int pathlen;
6516
6517               /* Determine the length of the execd pathname.  */
6518               p = unpack_varlen_hex (++p1, &ignored);
6519               pathlen = (p - p1) / 2;
6520
6521               /* Save the pathname for event reporting and for
6522                  the next run command.  */
6523               hex2bin (p1, (gdb_byte *) pathname, pathlen);
6524               pathname[pathlen] = '\0';
6525
6526               /* This is freed during event handling.  */
6527               event->ws.value.execd_pathname = xstrdup (pathname);
6528               event->ws.kind = TARGET_WAITKIND_EXECD;
6529
6530               /* Skip the registers included in this packet, since
6531                  they may be for an architecture different from the
6532                  one used by the original program.  */
6533               skipregs = 1;
6534             }
6535           else if (strprefix (p, p1, "create"))
6536             {
6537               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6538               p = strchrnul (p1 + 1, ';');
6539             }
6540           else
6541             {
6542               ULONGEST pnum;
6543               char *p_temp;
6544
6545               if (skipregs)
6546                 {
6547                   p = strchrnul (p1 + 1, ';');
6548                   p++;
6549                   continue;
6550                 }
6551
6552               /* Maybe a real ``P'' register number.  */
6553               p_temp = unpack_varlen_hex (p, &pnum);
6554               /* If the first invalid character is the colon, we got a
6555                  register number.  Otherwise, it's an unknown stop
6556                  reason.  */
6557               if (p_temp == p1)
6558                 {
6559                   struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6560                   cached_reg_t cached_reg;
6561
6562                   if (reg == NULL)
6563                     error (_("Remote sent bad register number %s: %s\n\
6564 Packet: '%s'\n"),
6565                            hex_string (pnum), p, buf);
6566
6567                   cached_reg.num = reg->regnum;
6568
6569                   p = p1 + 1;
6570                   fieldsize = hex2bin (p, cached_reg.data,
6571                                        register_size (target_gdbarch (),
6572                                                       reg->regnum));
6573                   p += 2 * fieldsize;
6574                   if (fieldsize < register_size (target_gdbarch (),
6575                                                  reg->regnum))
6576                     warning (_("Remote reply is too short: %s"), buf);
6577
6578                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6579                 }
6580               else
6581                 {
6582                   /* Not a number.  Silently skip unknown optional
6583                      info.  */
6584                   p = strchrnul (p1 + 1, ';');
6585                 }
6586             }
6587
6588           if (*p != ';')
6589             error (_("Remote register badly formatted: %s\nhere: %s"),
6590                    buf, p);
6591           ++p;
6592         }
6593
6594       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6595         break;
6596
6597       /* fall through */
6598     case 'S':           /* Old style status, just signal only.  */
6599       {
6600         int sig;
6601
6602         event->ws.kind = TARGET_WAITKIND_STOPPED;
6603         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6604         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6605           event->ws.value.sig = (enum gdb_signal) sig;
6606         else
6607           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6608       }
6609       break;
6610     case 'w':           /* Thread exited.  */
6611       {
6612         char *p;
6613         ULONGEST value;
6614
6615         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6616         p = unpack_varlen_hex (&buf[1], &value);
6617         event->ws.value.integer = value;
6618         if (*p != ';')
6619           error (_("stop reply packet badly formatted: %s"), buf);
6620         event->ptid = read_ptid (++p, NULL);
6621         break;
6622       }
6623     case 'W':           /* Target exited.  */
6624     case 'X':
6625       {
6626         char *p;
6627         int pid;
6628         ULONGEST value;
6629
6630         /* GDB used to accept only 2 hex chars here.  Stubs should
6631            only send more if they detect GDB supports multi-process
6632            support.  */
6633         p = unpack_varlen_hex (&buf[1], &value);
6634
6635         if (buf[0] == 'W')
6636           {
6637             /* The remote process exited.  */
6638             event->ws.kind = TARGET_WAITKIND_EXITED;
6639             event->ws.value.integer = value;
6640           }
6641         else
6642           {
6643             /* The remote process exited with a signal.  */
6644             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6645             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6646               event->ws.value.sig = (enum gdb_signal) value;
6647             else
6648               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6649           }
6650
6651         /* If no process is specified, assume inferior_ptid.  */
6652         pid = ptid_get_pid (inferior_ptid);
6653         if (*p == '\0')
6654           ;
6655         else if (*p == ';')
6656           {
6657             p++;
6658
6659             if (*p == '\0')
6660               ;
6661             else if (startswith (p, "process:"))
6662               {
6663                 ULONGEST upid;
6664
6665                 p += sizeof ("process:") - 1;
6666                 unpack_varlen_hex (p, &upid);
6667                 pid = upid;
6668               }
6669             else
6670               error (_("unknown stop reply packet: %s"), buf);
6671           }
6672         else
6673           error (_("unknown stop reply packet: %s"), buf);
6674         event->ptid = pid_to_ptid (pid);
6675       }
6676       break;
6677     case 'N':
6678       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6679       event->ptid = minus_one_ptid;
6680       break;
6681     }
6682
6683   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6684     error (_("No process or thread specified in stop reply: %s"), buf);
6685 }
6686
6687 /* When the stub wants to tell GDB about a new notification reply, it
6688    sends a notification (%Stop, for example).  Those can come it at
6689    any time, hence, we have to make sure that any pending
6690    putpkt/getpkt sequence we're making is finished, before querying
6691    the stub for more events with the corresponding ack command
6692    (vStopped, for example).  E.g., if we started a vStopped sequence
6693    immediately upon receiving the notification, something like this
6694    could happen:
6695
6696     1.1) --> Hg 1
6697     1.2) <-- OK
6698     1.3) --> g
6699     1.4) <-- %Stop
6700     1.5) --> vStopped
6701     1.6) <-- (registers reply to step #1.3)
6702
6703    Obviously, the reply in step #1.6 would be unexpected to a vStopped
6704    query.
6705
6706    To solve this, whenever we parse a %Stop notification successfully,
6707    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6708    doing whatever we were doing:
6709
6710     2.1) --> Hg 1
6711     2.2) <-- OK
6712     2.3) --> g
6713     2.4) <-- %Stop
6714       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6715     2.5) <-- (registers reply to step #2.3)
6716
6717    Eventualy after step #2.5, we return to the event loop, which
6718    notices there's an event on the
6719    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6720    associated callback --- the function below.  At this point, we're
6721    always safe to start a vStopped sequence. :
6722
6723     2.6) --> vStopped
6724     2.7) <-- T05 thread:2
6725     2.8) --> vStopped
6726     2.9) --> OK
6727 */
6728
6729 void
6730 remote_notif_get_pending_events (struct notif_client *nc)
6731 {
6732   struct remote_state *rs = get_remote_state ();
6733
6734   if (rs->notif_state->pending_event[nc->id] != NULL)
6735     {
6736       if (notif_debug)
6737         fprintf_unfiltered (gdb_stdlog,
6738                             "notif: process: '%s' ack pending event\n",
6739                             nc->name);
6740
6741       /* acknowledge */
6742       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6743       rs->notif_state->pending_event[nc->id] = NULL;
6744
6745       while (1)
6746         {
6747           getpkt (&rs->buf, &rs->buf_size, 0);
6748           if (strcmp (rs->buf, "OK") == 0)
6749             break;
6750           else
6751             remote_notif_ack (nc, rs->buf);
6752         }
6753     }
6754   else
6755     {
6756       if (notif_debug)
6757         fprintf_unfiltered (gdb_stdlog,
6758                             "notif: process: '%s' no pending reply\n",
6759                             nc->name);
6760     }
6761 }
6762
6763 /* Called when it is decided that STOP_REPLY holds the info of the
6764    event that is to be returned to the core.  This function always
6765    destroys STOP_REPLY.  */
6766
6767 static ptid_t
6768 process_stop_reply (struct stop_reply *stop_reply,
6769                     struct target_waitstatus *status)
6770 {
6771   ptid_t ptid;
6772
6773   *status = stop_reply->ws;
6774   ptid = stop_reply->ptid;
6775
6776   /* If no thread/process was reported by the stub, assume the current
6777      inferior.  */
6778   if (ptid_equal (ptid, null_ptid))
6779     ptid = inferior_ptid;
6780
6781   if (status->kind != TARGET_WAITKIND_EXITED
6782       && status->kind != TARGET_WAITKIND_SIGNALLED
6783       && status->kind != TARGET_WAITKIND_NO_RESUMED)
6784     {
6785       struct private_thread_info *remote_thr;
6786
6787       /* Expedited registers.  */
6788       if (stop_reply->regcache)
6789         {
6790           struct regcache *regcache
6791             = get_thread_arch_regcache (ptid, target_gdbarch ());
6792           cached_reg_t *reg;
6793           int ix;
6794
6795           for (ix = 0;
6796                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6797                ix++)
6798             regcache_raw_supply (regcache, reg->num, reg->data);
6799           VEC_free (cached_reg_t, stop_reply->regcache);
6800         }
6801
6802       remote_notice_new_inferior (ptid, 0);
6803       remote_thr = demand_private_info (ptid);
6804       remote_thr->core = stop_reply->core;
6805       remote_thr->stop_reason = stop_reply->stop_reason;
6806       remote_thr->watch_data_address = stop_reply->watch_data_address;
6807     }
6808
6809   stop_reply_xfree (stop_reply);
6810   return ptid;
6811 }
6812
6813 /* The non-stop mode version of target_wait.  */
6814
6815 static ptid_t
6816 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6817 {
6818   struct remote_state *rs = get_remote_state ();
6819   struct stop_reply *stop_reply;
6820   int ret;
6821   int is_notif = 0;
6822
6823   /* If in non-stop mode, get out of getpkt even if a
6824      notification is received.  */
6825
6826   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6827                               0 /* forever */, &is_notif);
6828   while (1)
6829     {
6830       if (ret != -1 && !is_notif)
6831         switch (rs->buf[0])
6832           {
6833           case 'E':             /* Error of some sort.  */
6834             /* We're out of sync with the target now.  Did it continue
6835                or not?  We can't tell which thread it was in non-stop,
6836                so just ignore this.  */
6837             warning (_("Remote failure reply: %s"), rs->buf);
6838             break;
6839           case 'O':             /* Console output.  */
6840             remote_console_output (rs->buf + 1);
6841             break;
6842           default:
6843             warning (_("Invalid remote reply: %s"), rs->buf);
6844             break;
6845           }
6846
6847       /* Acknowledge a pending stop reply that may have arrived in the
6848          mean time.  */
6849       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6850         remote_notif_get_pending_events (&notif_client_stop);
6851
6852       /* If indeed we noticed a stop reply, we're done.  */
6853       stop_reply = queued_stop_reply (ptid);
6854       if (stop_reply != NULL)
6855         return process_stop_reply (stop_reply, status);
6856
6857       /* Still no event.  If we're just polling for an event, then
6858          return to the event loop.  */
6859       if (options & TARGET_WNOHANG)
6860         {
6861           status->kind = TARGET_WAITKIND_IGNORE;
6862           return minus_one_ptid;
6863         }
6864
6865       /* Otherwise do a blocking wait.  */
6866       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6867                                   1 /* forever */, &is_notif);
6868     }
6869 }
6870
6871 /* Wait until the remote machine stops, then return, storing status in
6872    STATUS just as `wait' would.  */
6873
6874 static ptid_t
6875 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6876 {
6877   struct remote_state *rs = get_remote_state ();
6878   ptid_t event_ptid = null_ptid;
6879   char *buf;
6880   struct stop_reply *stop_reply;
6881
6882  again:
6883
6884   status->kind = TARGET_WAITKIND_IGNORE;
6885   status->value.integer = 0;
6886
6887   stop_reply = queued_stop_reply (ptid);
6888   if (stop_reply != NULL)
6889     return process_stop_reply (stop_reply, status);
6890
6891   if (rs->cached_wait_status)
6892     /* Use the cached wait status, but only once.  */
6893     rs->cached_wait_status = 0;
6894   else
6895     {
6896       int ret;
6897       int is_notif;
6898       int forever = ((options & TARGET_WNOHANG) == 0
6899                      && wait_forever_enabled_p);
6900
6901       if (!rs->waiting_for_stop_reply)
6902         {
6903           status->kind = TARGET_WAITKIND_NO_RESUMED;
6904           return minus_one_ptid;
6905         }
6906
6907       /* FIXME: cagney/1999-09-27: If we're in async mode we should
6908          _never_ wait for ever -> test on target_is_async_p().
6909          However, before we do that we need to ensure that the caller
6910          knows how to take the target into/out of async mode.  */
6911       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6912                                   forever, &is_notif);
6913
6914       /* GDB gets a notification.  Return to core as this event is
6915          not interesting.  */
6916       if (ret != -1 && is_notif)
6917         return minus_one_ptid;
6918
6919       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6920         return minus_one_ptid;
6921     }
6922
6923   buf = rs->buf;
6924
6925   /* Assume that the target has acknowledged Ctrl-C unless we receive
6926      an 'F' or 'O' packet.  */
6927   if (buf[0] != 'F' && buf[0] != 'O')
6928     rs->ctrlc_pending_p = 0;
6929
6930   switch (buf[0])
6931     {
6932     case 'E':           /* Error of some sort.  */
6933       /* We're out of sync with the target now.  Did it continue or
6934          not?  Not is more likely, so report a stop.  */
6935       rs->waiting_for_stop_reply = 0;
6936
6937       warning (_("Remote failure reply: %s"), buf);
6938       status->kind = TARGET_WAITKIND_STOPPED;
6939       status->value.sig = GDB_SIGNAL_0;
6940       break;
6941     case 'F':           /* File-I/O request.  */
6942       /* GDB may access the inferior memory while handling the File-I/O
6943          request, but we don't want GDB accessing memory while waiting
6944          for a stop reply.  See the comments in putpkt_binary.  Set
6945          waiting_for_stop_reply to 0 temporarily.  */
6946       rs->waiting_for_stop_reply = 0;
6947       remote_fileio_request (buf, rs->ctrlc_pending_p);
6948       rs->ctrlc_pending_p = 0;
6949       /* GDB handled the File-I/O request, and the target is running
6950          again.  Keep waiting for events.  */
6951       rs->waiting_for_stop_reply = 1;
6952       break;
6953     case 'N': case 'T': case 'S': case 'X': case 'W':
6954       {
6955         struct stop_reply *stop_reply;
6956
6957         /* There is a stop reply to handle.  */
6958         rs->waiting_for_stop_reply = 0;
6959
6960         stop_reply
6961           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6962                                                       rs->buf);
6963
6964         event_ptid = process_stop_reply (stop_reply, status);
6965         break;
6966       }
6967     case 'O':           /* Console output.  */
6968       remote_console_output (buf + 1);
6969       break;
6970     case '\0':
6971       if (rs->last_sent_signal != GDB_SIGNAL_0)
6972         {
6973           /* Zero length reply means that we tried 'S' or 'C' and the
6974              remote system doesn't support it.  */
6975           target_terminal_ours_for_output ();
6976           printf_filtered
6977             ("Can't send signals to this remote system.  %s not sent.\n",
6978              gdb_signal_to_name (rs->last_sent_signal));
6979           rs->last_sent_signal = GDB_SIGNAL_0;
6980           target_terminal_inferior ();
6981
6982           strcpy (buf, rs->last_sent_step ? "s" : "c");
6983           putpkt (buf);
6984           break;
6985         }
6986       /* else fallthrough */
6987     default:
6988       warning (_("Invalid remote reply: %s"), buf);
6989       break;
6990     }
6991
6992   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
6993     return minus_one_ptid;
6994   else if (status->kind == TARGET_WAITKIND_IGNORE)
6995     {
6996       /* Nothing interesting happened.  If we're doing a non-blocking
6997          poll, we're done.  Otherwise, go back to waiting.  */
6998       if (options & TARGET_WNOHANG)
6999         return minus_one_ptid;
7000       else
7001         goto again;
7002     }
7003   else if (status->kind != TARGET_WAITKIND_EXITED
7004            && status->kind != TARGET_WAITKIND_SIGNALLED)
7005     {
7006       if (!ptid_equal (event_ptid, null_ptid))
7007         record_currthread (rs, event_ptid);
7008       else
7009         event_ptid = inferior_ptid;
7010     }
7011   else
7012     /* A process exit.  Invalidate our notion of current thread.  */
7013     record_currthread (rs, minus_one_ptid);
7014
7015   return event_ptid;
7016 }
7017
7018 /* Wait until the remote machine stops, then return, storing status in
7019    STATUS just as `wait' would.  */
7020
7021 static ptid_t
7022 remote_wait (struct target_ops *ops,
7023              ptid_t ptid, struct target_waitstatus *status, int options)
7024 {
7025   ptid_t event_ptid;
7026
7027   if (target_is_non_stop_p ())
7028     event_ptid = remote_wait_ns (ptid, status, options);
7029   else
7030     event_ptid = remote_wait_as (ptid, status, options);
7031
7032   if (target_is_async_p ())
7033     {
7034       /* If there are are events left in the queue tell the event loop
7035          to return here.  */
7036       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7037         mark_async_event_handler (remote_async_inferior_event_token);
7038     }
7039
7040   return event_ptid;
7041 }
7042
7043 /* Fetch a single register using a 'p' packet.  */
7044
7045 static int
7046 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7047 {
7048   struct remote_state *rs = get_remote_state ();
7049   char *buf, *p;
7050   char regp[MAX_REGISTER_SIZE];
7051   int i;
7052
7053   if (packet_support (PACKET_p) == PACKET_DISABLE)
7054     return 0;
7055
7056   if (reg->pnum == -1)
7057     return 0;
7058
7059   p = rs->buf;
7060   *p++ = 'p';
7061   p += hexnumstr (p, reg->pnum);
7062   *p++ = '\0';
7063   putpkt (rs->buf);
7064   getpkt (&rs->buf, &rs->buf_size, 0);
7065
7066   buf = rs->buf;
7067
7068   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7069     {
7070     case PACKET_OK:
7071       break;
7072     case PACKET_UNKNOWN:
7073       return 0;
7074     case PACKET_ERROR:
7075       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7076              gdbarch_register_name (get_regcache_arch (regcache), 
7077                                     reg->regnum), 
7078              buf);
7079     }
7080
7081   /* If this register is unfetchable, tell the regcache.  */
7082   if (buf[0] == 'x')
7083     {
7084       regcache_raw_supply (regcache, reg->regnum, NULL);
7085       return 1;
7086     }
7087
7088   /* Otherwise, parse and supply the value.  */
7089   p = buf;
7090   i = 0;
7091   while (p[0] != 0)
7092     {
7093       if (p[1] == 0)
7094         error (_("fetch_register_using_p: early buf termination"));
7095
7096       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7097       p += 2;
7098     }
7099   regcache_raw_supply (regcache, reg->regnum, regp);
7100   return 1;
7101 }
7102
7103 /* Fetch the registers included in the target's 'g' packet.  */
7104
7105 static int
7106 send_g_packet (void)
7107 {
7108   struct remote_state *rs = get_remote_state ();
7109   int buf_len;
7110
7111   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7112   remote_send (&rs->buf, &rs->buf_size);
7113
7114   /* We can get out of synch in various cases.  If the first character
7115      in the buffer is not a hex character, assume that has happened
7116      and try to fetch another packet to read.  */
7117   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7118          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7119          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7120          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
7121     {
7122       if (remote_debug)
7123         fprintf_unfiltered (gdb_stdlog,
7124                             "Bad register packet; fetching a new packet\n");
7125       getpkt (&rs->buf, &rs->buf_size, 0);
7126     }
7127
7128   buf_len = strlen (rs->buf);
7129
7130   /* Sanity check the received packet.  */
7131   if (buf_len % 2 != 0)
7132     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7133
7134   return buf_len / 2;
7135 }
7136
7137 static void
7138 process_g_packet (struct regcache *regcache)
7139 {
7140   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7141   struct remote_state *rs = get_remote_state ();
7142   struct remote_arch_state *rsa = get_remote_arch_state ();
7143   int i, buf_len;
7144   char *p;
7145   char *regs;
7146
7147   buf_len = strlen (rs->buf);
7148
7149   /* Further sanity checks, with knowledge of the architecture.  */
7150   if (buf_len > 2 * rsa->sizeof_g_packet)
7151     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7152
7153   /* Save the size of the packet sent to us by the target.  It is used
7154      as a heuristic when determining the max size of packets that the
7155      target can safely receive.  */
7156   if (rsa->actual_register_packet_size == 0)
7157     rsa->actual_register_packet_size = buf_len;
7158
7159   /* If this is smaller than we guessed the 'g' packet would be,
7160      update our records.  A 'g' reply that doesn't include a register's
7161      value implies either that the register is not available, or that
7162      the 'p' packet must be used.  */
7163   if (buf_len < 2 * rsa->sizeof_g_packet)
7164     {
7165       rsa->sizeof_g_packet = buf_len / 2;
7166
7167       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7168         {
7169           if (rsa->regs[i].pnum == -1)
7170             continue;
7171
7172           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7173             rsa->regs[i].in_g_packet = 0;
7174           else
7175             rsa->regs[i].in_g_packet = 1;
7176         }
7177     }
7178
7179   regs = (char *) alloca (rsa->sizeof_g_packet);
7180
7181   /* Unimplemented registers read as all bits zero.  */
7182   memset (regs, 0, rsa->sizeof_g_packet);
7183
7184   /* Reply describes registers byte by byte, each byte encoded as two
7185      hex characters.  Suck them all up, then supply them to the
7186      register cacheing/storage mechanism.  */
7187
7188   p = rs->buf;
7189   for (i = 0; i < rsa->sizeof_g_packet; i++)
7190     {
7191       if (p[0] == 0 || p[1] == 0)
7192         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
7193         internal_error (__FILE__, __LINE__,
7194                         _("unexpected end of 'g' packet reply"));
7195
7196       if (p[0] == 'x' && p[1] == 'x')
7197         regs[i] = 0;            /* 'x' */
7198       else
7199         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7200       p += 2;
7201     }
7202
7203   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7204     {
7205       struct packet_reg *r = &rsa->regs[i];
7206
7207       if (r->in_g_packet)
7208         {
7209           if (r->offset * 2 >= strlen (rs->buf))
7210             /* This shouldn't happen - we adjusted in_g_packet above.  */
7211             internal_error (__FILE__, __LINE__,
7212                             _("unexpected end of 'g' packet reply"));
7213           else if (rs->buf[r->offset * 2] == 'x')
7214             {
7215               gdb_assert (r->offset * 2 < strlen (rs->buf));
7216               /* The register isn't available, mark it as such (at
7217                  the same time setting the value to zero).  */
7218               regcache_raw_supply (regcache, r->regnum, NULL);
7219             }
7220           else
7221             regcache_raw_supply (regcache, r->regnum,
7222                                  regs + r->offset);
7223         }
7224     }
7225 }
7226
7227 static void
7228 fetch_registers_using_g (struct regcache *regcache)
7229 {
7230   send_g_packet ();
7231   process_g_packet (regcache);
7232 }
7233
7234 /* Make the remote selected traceframe match GDB's selected
7235    traceframe.  */
7236
7237 static void
7238 set_remote_traceframe (void)
7239 {
7240   int newnum;
7241   struct remote_state *rs = get_remote_state ();
7242
7243   if (rs->remote_traceframe_number == get_traceframe_number ())
7244     return;
7245
7246   /* Avoid recursion, remote_trace_find calls us again.  */
7247   rs->remote_traceframe_number = get_traceframe_number ();
7248
7249   newnum = target_trace_find (tfind_number,
7250                               get_traceframe_number (), 0, 0, NULL);
7251
7252   /* Should not happen.  If it does, all bets are off.  */
7253   if (newnum != get_traceframe_number ())
7254     warning (_("could not set remote traceframe"));
7255 }
7256
7257 static void
7258 remote_fetch_registers (struct target_ops *ops,
7259                         struct regcache *regcache, int regnum)
7260 {
7261   struct remote_arch_state *rsa = get_remote_arch_state ();
7262   int i;
7263
7264   set_remote_traceframe ();
7265   set_general_thread (inferior_ptid);
7266
7267   if (regnum >= 0)
7268     {
7269       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7270
7271       gdb_assert (reg != NULL);
7272
7273       /* If this register might be in the 'g' packet, try that first -
7274          we are likely to read more than one register.  If this is the
7275          first 'g' packet, we might be overly optimistic about its
7276          contents, so fall back to 'p'.  */
7277       if (reg->in_g_packet)
7278         {
7279           fetch_registers_using_g (regcache);
7280           if (reg->in_g_packet)
7281             return;
7282         }
7283
7284       if (fetch_register_using_p (regcache, reg))
7285         return;
7286
7287       /* This register is not available.  */
7288       regcache_raw_supply (regcache, reg->regnum, NULL);
7289
7290       return;
7291     }
7292
7293   fetch_registers_using_g (regcache);
7294
7295   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7296     if (!rsa->regs[i].in_g_packet)
7297       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7298         {
7299           /* This register is not available.  */
7300           regcache_raw_supply (regcache, i, NULL);
7301         }
7302 }
7303
7304 /* Prepare to store registers.  Since we may send them all (using a
7305    'G' request), we have to read out the ones we don't want to change
7306    first.  */
7307
7308 static void
7309 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7310 {
7311   struct remote_arch_state *rsa = get_remote_arch_state ();
7312   int i;
7313   gdb_byte buf[MAX_REGISTER_SIZE];
7314
7315   /* Make sure the entire registers array is valid.  */
7316   switch (packet_support (PACKET_P))
7317     {
7318     case PACKET_DISABLE:
7319     case PACKET_SUPPORT_UNKNOWN:
7320       /* Make sure all the necessary registers are cached.  */
7321       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7322         if (rsa->regs[i].in_g_packet)
7323           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7324       break;
7325     case PACKET_ENABLE:
7326       break;
7327     }
7328 }
7329
7330 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
7331    packet was not recognized.  */
7332
7333 static int
7334 store_register_using_P (const struct regcache *regcache, 
7335                         struct packet_reg *reg)
7336 {
7337   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7338   struct remote_state *rs = get_remote_state ();
7339   /* Try storing a single register.  */
7340   char *buf = rs->buf;
7341   gdb_byte regp[MAX_REGISTER_SIZE];
7342   char *p;
7343
7344   if (packet_support (PACKET_P) == PACKET_DISABLE)
7345     return 0;
7346
7347   if (reg->pnum == -1)
7348     return 0;
7349
7350   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7351   p = buf + strlen (buf);
7352   regcache_raw_collect (regcache, reg->regnum, regp);
7353   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7354   putpkt (rs->buf);
7355   getpkt (&rs->buf, &rs->buf_size, 0);
7356
7357   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7358     {
7359     case PACKET_OK:
7360       return 1;
7361     case PACKET_ERROR:
7362       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7363              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7364     case PACKET_UNKNOWN:
7365       return 0;
7366     default:
7367       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7368     }
7369 }
7370
7371 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7372    contents of the register cache buffer.  FIXME: ignores errors.  */
7373
7374 static void
7375 store_registers_using_G (const struct regcache *regcache)
7376 {
7377   struct remote_state *rs = get_remote_state ();
7378   struct remote_arch_state *rsa = get_remote_arch_state ();
7379   gdb_byte *regs;
7380   char *p;
7381
7382   /* Extract all the registers in the regcache copying them into a
7383      local buffer.  */
7384   {
7385     int i;
7386
7387     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7388     memset (regs, 0, rsa->sizeof_g_packet);
7389     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7390       {
7391         struct packet_reg *r = &rsa->regs[i];
7392
7393         if (r->in_g_packet)
7394           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7395       }
7396   }
7397
7398   /* Command describes registers byte by byte,
7399      each byte encoded as two hex characters.  */
7400   p = rs->buf;
7401   *p++ = 'G';
7402   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7403      updated.  */
7404   bin2hex (regs, p, rsa->sizeof_g_packet);
7405   putpkt (rs->buf);
7406   getpkt (&rs->buf, &rs->buf_size, 0);
7407   if (packet_check_result (rs->buf) == PACKET_ERROR)
7408     error (_("Could not write registers; remote failure reply '%s'"), 
7409            rs->buf);
7410 }
7411
7412 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7413    of the register cache buffer.  FIXME: ignores errors.  */
7414
7415 static void
7416 remote_store_registers (struct target_ops *ops,
7417                         struct regcache *regcache, int regnum)
7418 {
7419   struct remote_arch_state *rsa = get_remote_arch_state ();
7420   int i;
7421
7422   set_remote_traceframe ();
7423   set_general_thread (inferior_ptid);
7424
7425   if (regnum >= 0)
7426     {
7427       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7428
7429       gdb_assert (reg != NULL);
7430
7431       /* Always prefer to store registers using the 'P' packet if
7432          possible; we often change only a small number of registers.
7433          Sometimes we change a larger number; we'd need help from a
7434          higher layer to know to use 'G'.  */
7435       if (store_register_using_P (regcache, reg))
7436         return;
7437
7438       /* For now, don't complain if we have no way to write the
7439          register.  GDB loses track of unavailable registers too
7440          easily.  Some day, this may be an error.  We don't have
7441          any way to read the register, either...  */
7442       if (!reg->in_g_packet)
7443         return;
7444
7445       store_registers_using_G (regcache);
7446       return;
7447     }
7448
7449   store_registers_using_G (regcache);
7450
7451   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7452     if (!rsa->regs[i].in_g_packet)
7453       if (!store_register_using_P (regcache, &rsa->regs[i]))
7454         /* See above for why we do not issue an error here.  */
7455         continue;
7456 }
7457 \f
7458
7459 /* Return the number of hex digits in num.  */
7460
7461 static int
7462 hexnumlen (ULONGEST num)
7463 {
7464   int i;
7465
7466   for (i = 0; num != 0; i++)
7467     num >>= 4;
7468
7469   return max (i, 1);
7470 }
7471
7472 /* Set BUF to the minimum number of hex digits representing NUM.  */
7473
7474 static int
7475 hexnumstr (char *buf, ULONGEST num)
7476 {
7477   int len = hexnumlen (num);
7478
7479   return hexnumnstr (buf, num, len);
7480 }
7481
7482
7483 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
7484
7485 static int
7486 hexnumnstr (char *buf, ULONGEST num, int width)
7487 {
7488   int i;
7489
7490   buf[width] = '\0';
7491
7492   for (i = width - 1; i >= 0; i--)
7493     {
7494       buf[i] = "0123456789abcdef"[(num & 0xf)];
7495       num >>= 4;
7496     }
7497
7498   return width;
7499 }
7500
7501 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
7502
7503 static CORE_ADDR
7504 remote_address_masked (CORE_ADDR addr)
7505 {
7506   unsigned int address_size = remote_address_size;
7507
7508   /* If "remoteaddresssize" was not set, default to target address size.  */
7509   if (!address_size)
7510     address_size = gdbarch_addr_bit (target_gdbarch ());
7511
7512   if (address_size > 0
7513       && address_size < (sizeof (ULONGEST) * 8))
7514     {
7515       /* Only create a mask when that mask can safely be constructed
7516          in a ULONGEST variable.  */
7517       ULONGEST mask = 1;
7518
7519       mask = (mask << address_size) - 1;
7520       addr &= mask;
7521     }
7522   return addr;
7523 }
7524
7525 /* Determine whether the remote target supports binary downloading.
7526    This is accomplished by sending a no-op memory write of zero length
7527    to the target at the specified address. It does not suffice to send
7528    the whole packet, since many stubs strip the eighth bit and
7529    subsequently compute a wrong checksum, which causes real havoc with
7530    remote_write_bytes.
7531
7532    NOTE: This can still lose if the serial line is not eight-bit
7533    clean.  In cases like this, the user should clear "remote
7534    X-packet".  */
7535
7536 static void
7537 check_binary_download (CORE_ADDR addr)
7538 {
7539   struct remote_state *rs = get_remote_state ();
7540
7541   switch (packet_support (PACKET_X))
7542     {
7543     case PACKET_DISABLE:
7544       break;
7545     case PACKET_ENABLE:
7546       break;
7547     case PACKET_SUPPORT_UNKNOWN:
7548       {
7549         char *p;
7550
7551         p = rs->buf;
7552         *p++ = 'X';
7553         p += hexnumstr (p, (ULONGEST) addr);
7554         *p++ = ',';
7555         p += hexnumstr (p, (ULONGEST) 0);
7556         *p++ = ':';
7557         *p = '\0';
7558
7559         putpkt_binary (rs->buf, (int) (p - rs->buf));
7560         getpkt (&rs->buf, &rs->buf_size, 0);
7561
7562         if (rs->buf[0] == '\0')
7563           {
7564             if (remote_debug)
7565               fprintf_unfiltered (gdb_stdlog,
7566                                   "binary downloading NOT "
7567                                   "supported by target\n");
7568             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7569           }
7570         else
7571           {
7572             if (remote_debug)
7573               fprintf_unfiltered (gdb_stdlog,
7574                                   "binary downloading supported by target\n");
7575             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7576           }
7577         break;
7578       }
7579     }
7580 }
7581
7582 /* Helper function to resize the payload in order to try to get a good
7583    alignment.  We try to write an amount of data such that the next write will
7584    start on an address aligned on REMOTE_ALIGN_WRITES.  */
7585
7586 static int
7587 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7588 {
7589   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7590 }
7591
7592 /* Write memory data directly to the remote machine.
7593    This does not inform the data cache; the data cache uses this.
7594    HEADER is the starting part of the packet.
7595    MEMADDR is the address in the remote memory space.
7596    MYADDR is the address of the buffer in our space.
7597    LEN_UNITS is the number of addressable units to write.
7598    UNIT_SIZE is the length in bytes of an addressable unit.
7599    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7600    should send data as binary ('X'), or hex-encoded ('M').
7601
7602    The function creates packet of the form
7603        <HEADER><ADDRESS>,<LENGTH>:<DATA>
7604
7605    where encoding of <DATA> is terminated by PACKET_FORMAT.
7606
7607    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7608    are omitted.
7609
7610    Return the transferred status, error or OK (an
7611    'enum target_xfer_status' value).  Save the number of addressable units
7612    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
7613
7614    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7615    exchange between gdb and the stub could look like (?? in place of the
7616    checksum):
7617
7618    -> $m1000,4#??
7619    <- aaaabbbbccccdddd
7620
7621    -> $M1000,3:eeeeffffeeee#??
7622    <- OK
7623
7624    -> $m1000,4#??
7625    <- eeeeffffeeeedddd  */
7626
7627 static enum target_xfer_status
7628 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7629                         const gdb_byte *myaddr, ULONGEST len_units,
7630                         int unit_size, ULONGEST *xfered_len_units,
7631                         char packet_format, int use_length)
7632 {
7633   struct remote_state *rs = get_remote_state ();
7634   char *p;
7635   char *plen = NULL;
7636   int plenlen = 0;
7637   int todo_units;
7638   int units_written;
7639   int payload_capacity_bytes;
7640   int payload_length_bytes;
7641
7642   if (packet_format != 'X' && packet_format != 'M')
7643     internal_error (__FILE__, __LINE__,
7644                     _("remote_write_bytes_aux: bad packet format"));
7645
7646   if (len_units == 0)
7647     return TARGET_XFER_EOF;
7648
7649   payload_capacity_bytes = get_memory_write_packet_size ();
7650
7651   /* The packet buffer will be large enough for the payload;
7652      get_memory_packet_size ensures this.  */
7653   rs->buf[0] = '\0';
7654
7655   /* Compute the size of the actual payload by subtracting out the
7656      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
7657
7658   payload_capacity_bytes -= strlen ("$,:#NN");
7659   if (!use_length)
7660     /* The comma won't be used.  */
7661     payload_capacity_bytes += 1;
7662   payload_capacity_bytes -= strlen (header);
7663   payload_capacity_bytes -= hexnumlen (memaddr);
7664
7665   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
7666
7667   strcat (rs->buf, header);
7668   p = rs->buf + strlen (header);
7669
7670   /* Compute a best guess of the number of bytes actually transfered.  */
7671   if (packet_format == 'X')
7672     {
7673       /* Best guess at number of bytes that will fit.  */
7674       todo_units = min (len_units, payload_capacity_bytes / unit_size);
7675       if (use_length)
7676         payload_capacity_bytes -= hexnumlen (todo_units);
7677       todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7678     }
7679   else
7680     {
7681       /* Number of bytes that will fit.  */
7682       todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7683       if (use_length)
7684         payload_capacity_bytes -= hexnumlen (todo_units);
7685       todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7686     }
7687
7688   if (todo_units <= 0)
7689     internal_error (__FILE__, __LINE__,
7690                     _("minimum packet size too small to write data"));
7691
7692   /* If we already need another packet, then try to align the end
7693      of this packet to a useful boundary.  */
7694   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7695     todo_units = align_for_efficient_write (todo_units, memaddr);
7696
7697   /* Append "<memaddr>".  */
7698   memaddr = remote_address_masked (memaddr);
7699   p += hexnumstr (p, (ULONGEST) memaddr);
7700
7701   if (use_length)
7702     {
7703       /* Append ",".  */
7704       *p++ = ',';
7705
7706       /* Append the length and retain its location and size.  It may need to be
7707          adjusted once the packet body has been created.  */
7708       plen = p;
7709       plenlen = hexnumstr (p, (ULONGEST) todo_units);
7710       p += plenlen;
7711     }
7712
7713   /* Append ":".  */
7714   *p++ = ':';
7715   *p = '\0';
7716
7717   /* Append the packet body.  */
7718   if (packet_format == 'X')
7719     {
7720       /* Binary mode.  Send target system values byte by byte, in
7721          increasing byte addresses.  Only escape certain critical
7722          characters.  */
7723       payload_length_bytes =
7724           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7725                                 &units_written, payload_capacity_bytes);
7726
7727       /* If not all TODO units fit, then we'll need another packet.  Make
7728          a second try to keep the end of the packet aligned.  Don't do
7729          this if the packet is tiny.  */
7730       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7731         {
7732           int new_todo_units;
7733
7734           new_todo_units = align_for_efficient_write (units_written, memaddr);
7735
7736           if (new_todo_units != units_written)
7737             payload_length_bytes =
7738                 remote_escape_output (myaddr, new_todo_units, unit_size,
7739                                       (gdb_byte *) p, &units_written,
7740                                       payload_capacity_bytes);
7741         }
7742
7743       p += payload_length_bytes;
7744       if (use_length && units_written < todo_units)
7745         {
7746           /* Escape chars have filled up the buffer prematurely,
7747              and we have actually sent fewer units than planned.
7748              Fix-up the length field of the packet.  Use the same
7749              number of characters as before.  */
7750           plen += hexnumnstr (plen, (ULONGEST) units_written,
7751                               plenlen);
7752           *plen = ':';  /* overwrite \0 from hexnumnstr() */
7753         }
7754     }
7755   else
7756     {
7757       /* Normal mode: Send target system values byte by byte, in
7758          increasing byte addresses.  Each byte is encoded as a two hex
7759          value.  */
7760       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7761       units_written = todo_units;
7762     }
7763
7764   putpkt_binary (rs->buf, (int) (p - rs->buf));
7765   getpkt (&rs->buf, &rs->buf_size, 0);
7766
7767   if (rs->buf[0] == 'E')
7768     return TARGET_XFER_E_IO;
7769
7770   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7771      send fewer units than we'd planned.  */
7772   *xfered_len_units = (ULONGEST) units_written;
7773   return TARGET_XFER_OK;
7774 }
7775
7776 /* Write memory data directly to the remote machine.
7777    This does not inform the data cache; the data cache uses this.
7778    MEMADDR is the address in the remote memory space.
7779    MYADDR is the address of the buffer in our space.
7780    LEN is the number of bytes.
7781
7782    Return the transferred status, error or OK (an
7783    'enum target_xfer_status' value).  Save the number of bytes
7784    transferred in *XFERED_LEN.  Only transfer a single packet.  */
7785
7786 static enum target_xfer_status
7787 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7788                     int unit_size, ULONGEST *xfered_len)
7789 {
7790   char *packet_format = 0;
7791
7792   /* Check whether the target supports binary download.  */
7793   check_binary_download (memaddr);
7794
7795   switch (packet_support (PACKET_X))
7796     {
7797     case PACKET_ENABLE:
7798       packet_format = "X";
7799       break;
7800     case PACKET_DISABLE:
7801       packet_format = "M";
7802       break;
7803     case PACKET_SUPPORT_UNKNOWN:
7804       internal_error (__FILE__, __LINE__,
7805                       _("remote_write_bytes: bad internal state"));
7806     default:
7807       internal_error (__FILE__, __LINE__, _("bad switch"));
7808     }
7809
7810   return remote_write_bytes_aux (packet_format,
7811                                  memaddr, myaddr, len, unit_size, xfered_len,
7812                                  packet_format[0], 1);
7813 }
7814
7815 /* Read memory data directly from the remote machine.
7816    This does not use the data cache; the data cache uses this.
7817    MEMADDR is the address in the remote memory space.
7818    MYADDR is the address of the buffer in our space.
7819    LEN_UNITS is the number of addressable memory units to read..
7820    UNIT_SIZE is the length in bytes of an addressable unit.
7821
7822    Return the transferred status, error or OK (an
7823    'enum target_xfer_status' value).  Save the number of bytes
7824    transferred in *XFERED_LEN_UNITS.
7825
7826    See the comment of remote_write_bytes_aux for an example of
7827    memory read/write exchange between gdb and the stub.  */
7828
7829 static enum target_xfer_status
7830 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7831                      int unit_size, ULONGEST *xfered_len_units)
7832 {
7833   struct remote_state *rs = get_remote_state ();
7834   int buf_size_bytes;           /* Max size of packet output buffer.  */
7835   char *p;
7836   int todo_units;
7837   int decoded_bytes;
7838
7839   buf_size_bytes = get_memory_read_packet_size ();
7840   /* The packet buffer will be large enough for the payload;
7841      get_memory_packet_size ensures this.  */
7842
7843   /* Number of units that will fit.  */
7844   todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7845
7846   /* Construct "m"<memaddr>","<len>".  */
7847   memaddr = remote_address_masked (memaddr);
7848   p = rs->buf;
7849   *p++ = 'm';
7850   p += hexnumstr (p, (ULONGEST) memaddr);
7851   *p++ = ',';
7852   p += hexnumstr (p, (ULONGEST) todo_units);
7853   *p = '\0';
7854   putpkt (rs->buf);
7855   getpkt (&rs->buf, &rs->buf_size, 0);
7856   if (rs->buf[0] == 'E'
7857       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7858       && rs->buf[3] == '\0')
7859     return TARGET_XFER_E_IO;
7860   /* Reply describes memory byte by byte, each byte encoded as two hex
7861      characters.  */
7862   p = rs->buf;
7863   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7864   /* Return what we have.  Let higher layers handle partial reads.  */
7865   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7866   return TARGET_XFER_OK;
7867 }
7868
7869 /* Using the set of read-only target sections of remote, read live
7870    read-only memory.
7871
7872    For interface/parameters/return description see target.h,
7873    to_xfer_partial.  */
7874
7875 static enum target_xfer_status
7876 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7877                                    ULONGEST memaddr, ULONGEST len,
7878                                    int unit_size, ULONGEST *xfered_len)
7879 {
7880   struct target_section *secp;
7881   struct target_section_table *table;
7882
7883   secp = target_section_by_addr (ops, memaddr);
7884   if (secp != NULL
7885       && (bfd_get_section_flags (secp->the_bfd_section->owner,
7886                                  secp->the_bfd_section)
7887           & SEC_READONLY))
7888     {
7889       struct target_section *p;
7890       ULONGEST memend = memaddr + len;
7891
7892       table = target_get_section_table (ops);
7893
7894       for (p = table->sections; p < table->sections_end; p++)
7895         {
7896           if (memaddr >= p->addr)
7897             {
7898               if (memend <= p->endaddr)
7899                 {
7900                   /* Entire transfer is within this section.  */
7901                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7902                                               xfered_len);
7903                 }
7904               else if (memaddr >= p->endaddr)
7905                 {
7906                   /* This section ends before the transfer starts.  */
7907                   continue;
7908                 }
7909               else
7910                 {
7911                   /* This section overlaps the transfer.  Just do half.  */
7912                   len = p->endaddr - memaddr;
7913                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7914                                               xfered_len);
7915                 }
7916             }
7917         }
7918     }
7919
7920   return TARGET_XFER_EOF;
7921 }
7922
7923 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7924    first if the requested memory is unavailable in traceframe.
7925    Otherwise, fall back to remote_read_bytes_1.  */
7926
7927 static enum target_xfer_status
7928 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7929                    gdb_byte *myaddr, ULONGEST len, int unit_size,
7930                    ULONGEST *xfered_len)
7931 {
7932   if (len == 0)
7933     return TARGET_XFER_EOF;
7934
7935   if (get_traceframe_number () != -1)
7936     {
7937       VEC(mem_range_s) *available;
7938
7939       /* If we fail to get the set of available memory, then the
7940          target does not support querying traceframe info, and so we
7941          attempt reading from the traceframe anyway (assuming the
7942          target implements the old QTro packet then).  */
7943       if (traceframe_available_memory (&available, memaddr, len))
7944         {
7945           struct cleanup *old_chain;
7946
7947           old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7948
7949           if (VEC_empty (mem_range_s, available)
7950               || VEC_index (mem_range_s, available, 0)->start != memaddr)
7951             {
7952               enum target_xfer_status res;
7953
7954               /* Don't read into the traceframe's available
7955                  memory.  */
7956               if (!VEC_empty (mem_range_s, available))
7957                 {
7958                   LONGEST oldlen = len;
7959
7960                   len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7961                   gdb_assert (len <= oldlen);
7962                 }
7963
7964               do_cleanups (old_chain);
7965
7966               /* This goes through the topmost target again.  */
7967               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7968                                                        len, unit_size, xfered_len);
7969               if (res == TARGET_XFER_OK)
7970                 return TARGET_XFER_OK;
7971               else
7972                 {
7973                   /* No use trying further, we know some memory starting
7974                      at MEMADDR isn't available.  */
7975                   *xfered_len = len;
7976                   return TARGET_XFER_UNAVAILABLE;
7977                 }
7978             }
7979
7980           /* Don't try to read more than how much is available, in
7981              case the target implements the deprecated QTro packet to
7982              cater for older GDBs (the target's knowledge of read-only
7983              sections may be outdated by now).  */
7984           len = VEC_index (mem_range_s, available, 0)->length;
7985
7986           do_cleanups (old_chain);
7987         }
7988     }
7989
7990   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7991 }
7992
7993 \f
7994
7995 /* Sends a packet with content determined by the printf format string
7996    FORMAT and the remaining arguments, then gets the reply.  Returns
7997    whether the packet was a success, a failure, or unknown.  */
7998
7999 static enum packet_result remote_send_printf (const char *format, ...)
8000   ATTRIBUTE_PRINTF (1, 2);
8001
8002 static enum packet_result
8003 remote_send_printf (const char *format, ...)
8004 {
8005   struct remote_state *rs = get_remote_state ();
8006   int max_size = get_remote_packet_size ();
8007   va_list ap;
8008
8009   va_start (ap, format);
8010
8011   rs->buf[0] = '\0';
8012   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8013     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8014
8015   if (putpkt (rs->buf) < 0)
8016     error (_("Communication problem with target."));
8017
8018   rs->buf[0] = '\0';
8019   getpkt (&rs->buf, &rs->buf_size, 0);
8020
8021   return packet_check_result (rs->buf);
8022 }
8023
8024 static void
8025 restore_remote_timeout (void *p)
8026 {
8027   int value = *(int *)p;
8028
8029   remote_timeout = value;
8030 }
8031
8032 /* Flash writing can take quite some time.  We'll set
8033    effectively infinite timeout for flash operations.
8034    In future, we'll need to decide on a better approach.  */
8035 static const int remote_flash_timeout = 1000;
8036
8037 static void
8038 remote_flash_erase (struct target_ops *ops,
8039                     ULONGEST address, LONGEST length)
8040 {
8041   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8042   int saved_remote_timeout = remote_timeout;
8043   enum packet_result ret;
8044   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8045                                           &saved_remote_timeout);
8046
8047   remote_timeout = remote_flash_timeout;
8048
8049   ret = remote_send_printf ("vFlashErase:%s,%s",
8050                             phex (address, addr_size),
8051                             phex (length, 4));
8052   switch (ret)
8053     {
8054     case PACKET_UNKNOWN:
8055       error (_("Remote target does not support flash erase"));
8056     case PACKET_ERROR:
8057       error (_("Error erasing flash with vFlashErase packet"));
8058     default:
8059       break;
8060     }
8061
8062   do_cleanups (back_to);
8063 }
8064
8065 static enum target_xfer_status
8066 remote_flash_write (struct target_ops *ops, ULONGEST address,
8067                     ULONGEST length, ULONGEST *xfered_len,
8068                     const gdb_byte *data)
8069 {
8070   int saved_remote_timeout = remote_timeout;
8071   enum target_xfer_status ret;
8072   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8073                                           &saved_remote_timeout);
8074
8075   remote_timeout = remote_flash_timeout;
8076   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8077                                 xfered_len,'X', 0);
8078   do_cleanups (back_to);
8079
8080   return ret;
8081 }
8082
8083 static void
8084 remote_flash_done (struct target_ops *ops)
8085 {
8086   int saved_remote_timeout = remote_timeout;
8087   int ret;
8088   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8089                                           &saved_remote_timeout);
8090
8091   remote_timeout = remote_flash_timeout;
8092   ret = remote_send_printf ("vFlashDone");
8093   do_cleanups (back_to);
8094
8095   switch (ret)
8096     {
8097     case PACKET_UNKNOWN:
8098       error (_("Remote target does not support vFlashDone"));
8099     case PACKET_ERROR:
8100       error (_("Error finishing flash operation"));
8101     default:
8102       break;
8103     }
8104 }
8105
8106 static void
8107 remote_files_info (struct target_ops *ignore)
8108 {
8109   puts_filtered ("Debugging a target over a serial line.\n");
8110 }
8111 \f
8112 /* Stuff for dealing with the packets which are part of this protocol.
8113    See comment at top of file for details.  */
8114
8115 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8116    error to higher layers.  Called when a serial error is detected.
8117    The exception message is STRING, followed by a colon and a blank,
8118    the system error message for errno at function entry and final dot
8119    for output compatibility with throw_perror_with_name.  */
8120
8121 static void
8122 unpush_and_perror (const char *string)
8123 {
8124   int saved_errno = errno;
8125
8126   remote_unpush_target ();
8127   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8128                safe_strerror (saved_errno));
8129 }
8130
8131 /* Read a single character from the remote end.  The current quit
8132    handler is overridden to avoid quitting in the middle of packet
8133    sequence, as that would break communication with the remote server.
8134    See remote_serial_quit_handler for more detail.  */
8135
8136 static int
8137 readchar (int timeout)
8138 {
8139   int ch;
8140   struct remote_state *rs = get_remote_state ();
8141   struct cleanup *old_chain;
8142
8143   old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8144
8145   rs->got_ctrlc_during_io = 0;
8146
8147   ch = serial_readchar (rs->remote_desc, timeout);
8148
8149   if (rs->got_ctrlc_during_io)
8150     set_quit_flag ();
8151
8152   do_cleanups (old_chain);
8153
8154   if (ch >= 0)
8155     return ch;
8156
8157   switch ((enum serial_rc) ch)
8158     {
8159     case SERIAL_EOF:
8160       remote_unpush_target ();
8161       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8162       /* no return */
8163     case SERIAL_ERROR:
8164       unpush_and_perror (_("Remote communication error.  "
8165                            "Target disconnected."));
8166       /* no return */
8167     case SERIAL_TIMEOUT:
8168       break;
8169     }
8170   return ch;
8171 }
8172
8173 /* Wrapper for serial_write that closes the target and throws if
8174    writing fails.  The current quit handler is overridden to avoid
8175    quitting in the middle of packet sequence, as that would break
8176    communication with the remote server.  See
8177    remote_serial_quit_handler for more detail.  */
8178
8179 static void
8180 remote_serial_write (const char *str, int len)
8181 {
8182   struct remote_state *rs = get_remote_state ();
8183   struct cleanup *old_chain;
8184
8185   old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8186
8187   rs->got_ctrlc_during_io = 0;
8188
8189   if (serial_write (rs->remote_desc, str, len))
8190     {
8191       unpush_and_perror (_("Remote communication error.  "
8192                            "Target disconnected."));
8193     }
8194
8195   if (rs->got_ctrlc_during_io)
8196     set_quit_flag ();
8197
8198   do_cleanups (old_chain);
8199 }
8200
8201 /* Send the command in *BUF to the remote machine, and read the reply
8202    into *BUF.  Report an error if we get an error reply.  Resize
8203    *BUF using xrealloc if necessary to hold the result, and update
8204    *SIZEOF_BUF.  */
8205
8206 static void
8207 remote_send (char **buf,
8208              long *sizeof_buf)
8209 {
8210   putpkt (*buf);
8211   getpkt (buf, sizeof_buf, 0);
8212
8213   if ((*buf)[0] == 'E')
8214     error (_("Remote failure reply: %s"), *buf);
8215 }
8216
8217 /* Return a pointer to an xmalloc'ed string representing an escaped
8218    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
8219    etc.  The caller is responsible for releasing the returned
8220    memory.  */
8221
8222 static char *
8223 escape_buffer (const char *buf, int n)
8224 {
8225   struct cleanup *old_chain;
8226   struct ui_file *stb;
8227   char *str;
8228
8229   stb = mem_fileopen ();
8230   old_chain = make_cleanup_ui_file_delete (stb);
8231
8232   fputstrn_unfiltered (buf, n, '\\', stb);
8233   str = ui_file_xstrdup (stb, NULL);
8234   do_cleanups (old_chain);
8235   return str;
8236 }
8237
8238 /* Display a null-terminated packet on stdout, for debugging, using C
8239    string notation.  */
8240
8241 static void
8242 print_packet (const char *buf)
8243 {
8244   puts_filtered ("\"");
8245   fputstr_filtered (buf, '"', gdb_stdout);
8246   puts_filtered ("\"");
8247 }
8248
8249 int
8250 putpkt (const char *buf)
8251 {
8252   return putpkt_binary (buf, strlen (buf));
8253 }
8254
8255 /* Send a packet to the remote machine, with error checking.  The data
8256    of the packet is in BUF.  The string in BUF can be at most
8257    get_remote_packet_size () - 5 to account for the $, # and checksum,
8258    and for a possible /0 if we are debugging (remote_debug) and want
8259    to print the sent packet as a string.  */
8260
8261 static int
8262 putpkt_binary (const char *buf, int cnt)
8263 {
8264   struct remote_state *rs = get_remote_state ();
8265   int i;
8266   unsigned char csum = 0;
8267   char *buf2 = (char *) xmalloc (cnt + 6);
8268   struct cleanup *old_chain = make_cleanup (xfree, buf2);
8269
8270   int ch;
8271   int tcount = 0;
8272   char *p;
8273
8274   /* Catch cases like trying to read memory or listing threads while
8275      we're waiting for a stop reply.  The remote server wouldn't be
8276      ready to handle this request, so we'd hang and timeout.  We don't
8277      have to worry about this in synchronous mode, because in that
8278      case it's not possible to issue a command while the target is
8279      running.  This is not a problem in non-stop mode, because in that
8280      case, the stub is always ready to process serial input.  */
8281   if (!target_is_non_stop_p ()
8282       && target_is_async_p ()
8283       && rs->waiting_for_stop_reply)
8284     {
8285       error (_("Cannot execute this command while the target is running.\n"
8286                "Use the \"interrupt\" command to stop the target\n"
8287                "and then try again."));
8288     }
8289
8290   /* We're sending out a new packet.  Make sure we don't look at a
8291      stale cached response.  */
8292   rs->cached_wait_status = 0;
8293
8294   /* Copy the packet into buffer BUF2, encapsulating it
8295      and giving it a checksum.  */
8296
8297   p = buf2;
8298   *p++ = '$';
8299
8300   for (i = 0; i < cnt; i++)
8301     {
8302       csum += buf[i];
8303       *p++ = buf[i];
8304     }
8305   *p++ = '#';
8306   *p++ = tohex ((csum >> 4) & 0xf);
8307   *p++ = tohex (csum & 0xf);
8308
8309   /* Send it over and over until we get a positive ack.  */
8310
8311   while (1)
8312     {
8313       int started_error_output = 0;
8314
8315       if (remote_debug)
8316         {
8317           struct cleanup *old_chain;
8318           char *str;
8319
8320           *p = '\0';
8321           str = escape_buffer (buf2, p - buf2);
8322           old_chain = make_cleanup (xfree, str);
8323           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8324           gdb_flush (gdb_stdlog);
8325           do_cleanups (old_chain);
8326         }
8327       remote_serial_write (buf2, p - buf2);
8328
8329       /* If this is a no acks version of the remote protocol, send the
8330          packet and move on.  */
8331       if (rs->noack_mode)
8332         break;
8333
8334       /* Read until either a timeout occurs (-2) or '+' is read.
8335          Handle any notification that arrives in the mean time.  */
8336       while (1)
8337         {
8338           ch = readchar (remote_timeout);
8339
8340           if (remote_debug)
8341             {
8342               switch (ch)
8343                 {
8344                 case '+':
8345                 case '-':
8346                 case SERIAL_TIMEOUT:
8347                 case '$':
8348                 case '%':
8349                   if (started_error_output)
8350                     {
8351                       putchar_unfiltered ('\n');
8352                       started_error_output = 0;
8353                     }
8354                 }
8355             }
8356
8357           switch (ch)
8358             {
8359             case '+':
8360               if (remote_debug)
8361                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8362               do_cleanups (old_chain);
8363               return 1;
8364             case '-':
8365               if (remote_debug)
8366                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8367               /* FALLTHROUGH */
8368             case SERIAL_TIMEOUT:
8369               tcount++;
8370               if (tcount > 3)
8371                 {
8372                   do_cleanups (old_chain);
8373                   return 0;
8374                 }
8375               break;            /* Retransmit buffer.  */
8376             case '$':
8377               {
8378                 if (remote_debug)
8379                   fprintf_unfiltered (gdb_stdlog,
8380                                       "Packet instead of Ack, ignoring it\n");
8381                 /* It's probably an old response sent because an ACK
8382                    was lost.  Gobble up the packet and ack it so it
8383                    doesn't get retransmitted when we resend this
8384                    packet.  */
8385                 skip_frame ();
8386                 remote_serial_write ("+", 1);
8387                 continue;       /* Now, go look for +.  */
8388               }
8389
8390             case '%':
8391               {
8392                 int val;
8393
8394                 /* If we got a notification, handle it, and go back to looking
8395                    for an ack.  */
8396                 /* We've found the start of a notification.  Now
8397                    collect the data.  */
8398                 val = read_frame (&rs->buf, &rs->buf_size);
8399                 if (val >= 0)
8400                   {
8401                     if (remote_debug)
8402                       {
8403                         struct cleanup *old_chain;
8404                         char *str;
8405
8406                         str = escape_buffer (rs->buf, val);
8407                         old_chain = make_cleanup (xfree, str);
8408                         fprintf_unfiltered (gdb_stdlog,
8409                                             "  Notification received: %s\n",
8410                                             str);
8411                         do_cleanups (old_chain);
8412                       }
8413                     handle_notification (rs->notif_state, rs->buf);
8414                     /* We're in sync now, rewait for the ack.  */
8415                     tcount = 0;
8416                   }
8417                 else
8418                   {
8419                     if (remote_debug)
8420                       {
8421                         if (!started_error_output)
8422                           {
8423                             started_error_output = 1;
8424                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8425                           }
8426                         fputc_unfiltered (ch & 0177, gdb_stdlog);
8427                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8428                       }
8429                   }
8430                 continue;
8431               }
8432               /* fall-through */
8433             default:
8434               if (remote_debug)
8435                 {
8436                   if (!started_error_output)
8437                     {
8438                       started_error_output = 1;
8439                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8440                     }
8441                   fputc_unfiltered (ch & 0177, gdb_stdlog);
8442                 }
8443               continue;
8444             }
8445           break;                /* Here to retransmit.  */
8446         }
8447
8448 #if 0
8449       /* This is wrong.  If doing a long backtrace, the user should be
8450          able to get out next time we call QUIT, without anything as
8451          violent as interrupt_query.  If we want to provide a way out of
8452          here without getting to the next QUIT, it should be based on
8453          hitting ^C twice as in remote_wait.  */
8454       if (quit_flag)
8455         {
8456           quit_flag = 0;
8457           interrupt_query ();
8458         }
8459 #endif
8460     }
8461
8462   do_cleanups (old_chain);
8463   return 0;
8464 }
8465
8466 /* Come here after finding the start of a frame when we expected an
8467    ack.  Do our best to discard the rest of this packet.  */
8468
8469 static void
8470 skip_frame (void)
8471 {
8472   int c;
8473
8474   while (1)
8475     {
8476       c = readchar (remote_timeout);
8477       switch (c)
8478         {
8479         case SERIAL_TIMEOUT:
8480           /* Nothing we can do.  */
8481           return;
8482         case '#':
8483           /* Discard the two bytes of checksum and stop.  */
8484           c = readchar (remote_timeout);
8485           if (c >= 0)
8486             c = readchar (remote_timeout);
8487
8488           return;
8489         case '*':               /* Run length encoding.  */
8490           /* Discard the repeat count.  */
8491           c = readchar (remote_timeout);
8492           if (c < 0)
8493             return;
8494           break;
8495         default:
8496           /* A regular character.  */
8497           break;
8498         }
8499     }
8500 }
8501
8502 /* Come here after finding the start of the frame.  Collect the rest
8503    into *BUF, verifying the checksum, length, and handling run-length
8504    compression.  NUL terminate the buffer.  If there is not enough room,
8505    expand *BUF using xrealloc.
8506
8507    Returns -1 on error, number of characters in buffer (ignoring the
8508    trailing NULL) on success. (could be extended to return one of the
8509    SERIAL status indications).  */
8510
8511 static long
8512 read_frame (char **buf_p,
8513             long *sizeof_buf)
8514 {
8515   unsigned char csum;
8516   long bc;
8517   int c;
8518   char *buf = *buf_p;
8519   struct remote_state *rs = get_remote_state ();
8520
8521   csum = 0;
8522   bc = 0;
8523
8524   while (1)
8525     {
8526       c = readchar (remote_timeout);
8527       switch (c)
8528         {
8529         case SERIAL_TIMEOUT:
8530           if (remote_debug)
8531             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8532           return -1;
8533         case '$':
8534           if (remote_debug)
8535             fputs_filtered ("Saw new packet start in middle of old one\n",
8536                             gdb_stdlog);
8537           return -1;            /* Start a new packet, count retries.  */
8538         case '#':
8539           {
8540             unsigned char pktcsum;
8541             int check_0 = 0;
8542             int check_1 = 0;
8543
8544             buf[bc] = '\0';
8545
8546             check_0 = readchar (remote_timeout);
8547             if (check_0 >= 0)
8548               check_1 = readchar (remote_timeout);
8549
8550             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8551               {
8552                 if (remote_debug)
8553                   fputs_filtered ("Timeout in checksum, retrying\n",
8554                                   gdb_stdlog);
8555                 return -1;
8556               }
8557             else if (check_0 < 0 || check_1 < 0)
8558               {
8559                 if (remote_debug)
8560                   fputs_filtered ("Communication error in checksum\n",
8561                                   gdb_stdlog);
8562                 return -1;
8563               }
8564
8565             /* Don't recompute the checksum; with no ack packets we
8566                don't have any way to indicate a packet retransmission
8567                is necessary.  */
8568             if (rs->noack_mode)
8569               return bc;
8570
8571             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8572             if (csum == pktcsum)
8573               return bc;
8574
8575             if (remote_debug)
8576               {
8577                 struct cleanup *old_chain;
8578                 char *str;
8579
8580                 str = escape_buffer (buf, bc);
8581                 old_chain = make_cleanup (xfree, str);
8582                 fprintf_unfiltered (gdb_stdlog,
8583                                     "Bad checksum, sentsum=0x%x, "
8584                                     "csum=0x%x, buf=%s\n",
8585                                     pktcsum, csum, str);
8586                 do_cleanups (old_chain);
8587               }
8588             /* Number of characters in buffer ignoring trailing
8589                NULL.  */
8590             return -1;
8591           }
8592         case '*':               /* Run length encoding.  */
8593           {
8594             int repeat;
8595
8596             csum += c;
8597             c = readchar (remote_timeout);
8598             csum += c;
8599             repeat = c - ' ' + 3;       /* Compute repeat count.  */
8600
8601             /* The character before ``*'' is repeated.  */
8602
8603             if (repeat > 0 && repeat <= 255 && bc > 0)
8604               {
8605                 if (bc + repeat - 1 >= *sizeof_buf - 1)
8606                   {
8607                     /* Make some more room in the buffer.  */
8608                     *sizeof_buf += repeat;
8609                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8610                     buf = *buf_p;
8611                   }
8612
8613                 memset (&buf[bc], buf[bc - 1], repeat);
8614                 bc += repeat;
8615                 continue;
8616               }
8617
8618             buf[bc] = '\0';
8619             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8620             return -1;
8621           }
8622         default:
8623           if (bc >= *sizeof_buf - 1)
8624             {
8625               /* Make some more room in the buffer.  */
8626               *sizeof_buf *= 2;
8627               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8628               buf = *buf_p;
8629             }
8630
8631           buf[bc++] = c;
8632           csum += c;
8633           continue;
8634         }
8635     }
8636 }
8637
8638 /* Read a packet from the remote machine, with error checking, and
8639    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8640    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8641    rather than timing out; this is used (in synchronous mode) to wait
8642    for a target that is is executing user code to stop.  */
8643 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8644    don't have to change all the calls to getpkt to deal with the
8645    return value, because at the moment I don't know what the right
8646    thing to do it for those.  */
8647 void
8648 getpkt (char **buf,
8649         long *sizeof_buf,
8650         int forever)
8651 {
8652   getpkt_sane (buf, sizeof_buf, forever);
8653 }
8654
8655
8656 /* Read a packet from the remote machine, with error checking, and
8657    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
8658    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
8659    rather than timing out; this is used (in synchronous mode) to wait
8660    for a target that is is executing user code to stop.  If FOREVER ==
8661    0, this function is allowed to time out gracefully and return an
8662    indication of this to the caller.  Otherwise return the number of
8663    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
8664    enough reason to return to the caller.  *IS_NOTIF is an output
8665    boolean that indicates whether *BUF holds a notification or not
8666    (a regular packet).  */
8667
8668 static int
8669 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8670                         int expecting_notif, int *is_notif)
8671 {
8672   struct remote_state *rs = get_remote_state ();
8673   int c;
8674   int tries;
8675   int timeout;
8676   int val = -1;
8677
8678   /* We're reading a new response.  Make sure we don't look at a
8679      previously cached response.  */
8680   rs->cached_wait_status = 0;
8681
8682   strcpy (*buf, "timeout");
8683
8684   if (forever)
8685     timeout = watchdog > 0 ? watchdog : -1;
8686   else if (expecting_notif)
8687     timeout = 0; /* There should already be a char in the buffer.  If
8688                     not, bail out.  */
8689   else
8690     timeout = remote_timeout;
8691
8692 #define MAX_TRIES 3
8693
8694   /* Process any number of notifications, and then return when
8695      we get a packet.  */
8696   for (;;)
8697     {
8698       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8699          times.  */
8700       for (tries = 1; tries <= MAX_TRIES; tries++)
8701         {
8702           /* This can loop forever if the remote side sends us
8703              characters continuously, but if it pauses, we'll get
8704              SERIAL_TIMEOUT from readchar because of timeout.  Then
8705              we'll count that as a retry.
8706
8707              Note that even when forever is set, we will only wait
8708              forever prior to the start of a packet.  After that, we
8709              expect characters to arrive at a brisk pace.  They should
8710              show up within remote_timeout intervals.  */
8711           do
8712             c = readchar (timeout);
8713           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8714
8715           if (c == SERIAL_TIMEOUT)
8716             {
8717               if (expecting_notif)
8718                 return -1; /* Don't complain, it's normal to not get
8719                               anything in this case.  */
8720
8721               if (forever)      /* Watchdog went off?  Kill the target.  */
8722                 {
8723                   remote_unpush_target ();
8724                   throw_error (TARGET_CLOSE_ERROR,
8725                                _("Watchdog timeout has expired.  "
8726                                  "Target detached."));
8727                 }
8728               if (remote_debug)
8729                 fputs_filtered ("Timed out.\n", gdb_stdlog);
8730             }
8731           else
8732             {
8733               /* We've found the start of a packet or notification.
8734                  Now collect the data.  */
8735               val = read_frame (buf, sizeof_buf);
8736               if (val >= 0)
8737                 break;
8738             }
8739
8740           remote_serial_write ("-", 1);
8741         }
8742
8743       if (tries > MAX_TRIES)
8744         {
8745           /* We have tried hard enough, and just can't receive the
8746              packet/notification.  Give up.  */
8747           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8748
8749           /* Skip the ack char if we're in no-ack mode.  */
8750           if (!rs->noack_mode)
8751             remote_serial_write ("+", 1);
8752           return -1;
8753         }
8754
8755       /* If we got an ordinary packet, return that to our caller.  */
8756       if (c == '$')
8757         {
8758           if (remote_debug)
8759             {
8760              struct cleanup *old_chain;
8761              char *str;
8762
8763              str = escape_buffer (*buf, val);
8764              old_chain = make_cleanup (xfree, str);
8765              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8766              do_cleanups (old_chain);
8767             }
8768
8769           /* Skip the ack char if we're in no-ack mode.  */
8770           if (!rs->noack_mode)
8771             remote_serial_write ("+", 1);
8772           if (is_notif != NULL)
8773             *is_notif = 0;
8774           return val;
8775         }
8776
8777        /* If we got a notification, handle it, and go back to looking
8778          for a packet.  */
8779       else
8780         {
8781           gdb_assert (c == '%');
8782
8783           if (remote_debug)
8784             {
8785               struct cleanup *old_chain;
8786               char *str;
8787
8788               str = escape_buffer (*buf, val);
8789               old_chain = make_cleanup (xfree, str);
8790               fprintf_unfiltered (gdb_stdlog,
8791                                   "  Notification received: %s\n",
8792                                   str);
8793               do_cleanups (old_chain);
8794             }
8795           if (is_notif != NULL)
8796             *is_notif = 1;
8797
8798           handle_notification (rs->notif_state, *buf);
8799
8800           /* Notifications require no acknowledgement.  */
8801
8802           if (expecting_notif)
8803             return val;
8804         }
8805     }
8806 }
8807
8808 static int
8809 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8810 {
8811   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8812 }
8813
8814 static int
8815 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8816                       int *is_notif)
8817 {
8818   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8819                                  is_notif);
8820 }
8821
8822 /* Check whether EVENT is a fork event for the process specified
8823    by the pid passed in DATA, and if it is, kill the fork child.  */
8824
8825 static int
8826 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8827                             QUEUE_ITER (stop_reply_p) *iter,
8828                             stop_reply_p event,
8829                             void *data)
8830 {
8831   struct queue_iter_param *param = (struct queue_iter_param *) data;
8832   int parent_pid = *(int *) param->input;
8833
8834   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8835     {
8836       struct remote_state *rs = get_remote_state ();
8837       int child_pid = ptid_get_pid (event->ws.value.related_pid);
8838       int res;
8839
8840       res = remote_vkill (child_pid, rs);
8841       if (res != 0)
8842         error (_("Can't kill fork child process %d"), child_pid);
8843     }
8844
8845   return 1;
8846 }
8847
8848 /* Kill any new fork children of process PID that haven't been
8849    processed by follow_fork.  */
8850
8851 static void
8852 kill_new_fork_children (int pid, struct remote_state *rs)
8853 {
8854   struct thread_info *thread;
8855   struct notif_client *notif = &notif_client_stop;
8856   struct queue_iter_param param;
8857
8858   /* Kill the fork child threads of any threads in process PID
8859      that are stopped at a fork event.  */
8860   ALL_NON_EXITED_THREADS (thread)
8861     {
8862       struct target_waitstatus *ws = &thread->pending_follow;
8863
8864       if (is_pending_fork_parent (ws, pid, thread->ptid))
8865         {
8866           struct remote_state *rs = get_remote_state ();
8867           int child_pid = ptid_get_pid (ws->value.related_pid);
8868           int res;
8869
8870           res = remote_vkill (child_pid, rs);
8871           if (res != 0)
8872             error (_("Can't kill fork child process %d"), child_pid);
8873         }
8874     }
8875
8876   /* Check for any pending fork events (not reported or processed yet)
8877      in process PID and kill those fork child threads as well.  */
8878   remote_notif_get_pending_events (notif);
8879   param.input = &pid;
8880   param.output = NULL;
8881   QUEUE_iterate (stop_reply_p, stop_reply_queue,
8882                  kill_child_of_pending_fork, &param);
8883 }
8884
8885 \f
8886 /* Target hook to kill the current inferior.  */
8887
8888 static void
8889 remote_kill (struct target_ops *ops)
8890 {
8891   int res = -1;
8892   int pid = ptid_get_pid (inferior_ptid);
8893   struct remote_state *rs = get_remote_state ();
8894
8895   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
8896     {
8897       /* If we're stopped while forking and we haven't followed yet,
8898          kill the child task.  We need to do this before killing the
8899          parent task because if this is a vfork then the parent will
8900          be sleeping.  */
8901       kill_new_fork_children (pid, rs);
8902
8903       res = remote_vkill (pid, rs);
8904       if (res == 0)
8905         {
8906           target_mourn_inferior ();
8907           return;
8908         }
8909     }
8910
8911   /* If we are in 'target remote' mode and we are killing the only
8912      inferior, then we will tell gdbserver to exit and unpush the
8913      target.  */
8914   if (res == -1 && !remote_multi_process_p (rs)
8915       && number_of_live_inferiors () == 1)
8916     {
8917       remote_kill_k ();
8918
8919       /* We've killed the remote end, we get to mourn it.  If we are
8920          not in extended mode, mourning the inferior also unpushes
8921          remote_ops from the target stack, which closes the remote
8922          connection.  */
8923       target_mourn_inferior ();
8924
8925       return;
8926     }
8927
8928   error (_("Can't kill process"));
8929 }
8930
8931 /* Send a kill request to the target using the 'vKill' packet.  */
8932
8933 static int
8934 remote_vkill (int pid, struct remote_state *rs)
8935 {
8936   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8937     return -1;
8938
8939   /* Tell the remote target to detach.  */
8940   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8941   putpkt (rs->buf);
8942   getpkt (&rs->buf, &rs->buf_size, 0);
8943
8944   switch (packet_ok (rs->buf,
8945                      &remote_protocol_packets[PACKET_vKill]))
8946     {
8947     case PACKET_OK:
8948       return 0;
8949     case PACKET_ERROR:
8950       return 1;
8951     case PACKET_UNKNOWN:
8952       return -1;
8953     default:
8954       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8955     }
8956 }
8957
8958 /* Send a kill request to the target using the 'k' packet.  */
8959
8960 static void
8961 remote_kill_k (void)
8962 {
8963   /* Catch errors so the user can quit from gdb even when we
8964      aren't on speaking terms with the remote system.  */
8965   TRY
8966     {
8967       putpkt ("k");
8968     }
8969   CATCH (ex, RETURN_MASK_ERROR)
8970     {
8971       if (ex.error == TARGET_CLOSE_ERROR)
8972         {
8973           /* If we got an (EOF) error that caused the target
8974              to go away, then we're done, that's what we wanted.
8975              "k" is susceptible to cause a premature EOF, given
8976              that the remote server isn't actually required to
8977              reply to "k", and it can happen that it doesn't
8978              even get to reply ACK to the "k".  */
8979           return;
8980         }
8981
8982       /* Otherwise, something went wrong.  We didn't actually kill
8983          the target.  Just propagate the exception, and let the
8984          user or higher layers decide what to do.  */
8985       throw_exception (ex);
8986     }
8987   END_CATCH
8988 }
8989
8990 static void
8991 remote_mourn (struct target_ops *target)
8992 {
8993   struct remote_state *rs = get_remote_state ();
8994
8995   /* In 'target remote' mode with one inferior, we close the connection.  */
8996   if (!rs->extended && number_of_live_inferiors () <= 1)
8997     {
8998       unpush_target (target);
8999
9000       /* remote_close takes care of doing most of the clean up.  */
9001       generic_mourn_inferior ();
9002       return;
9003     }
9004
9005   /* In case we got here due to an error, but we're going to stay
9006      connected.  */
9007   rs->waiting_for_stop_reply = 0;
9008
9009   /* If the current general thread belonged to the process we just
9010      detached from or has exited, the remote side current general
9011      thread becomes undefined.  Considering a case like this:
9012
9013      - We just got here due to a detach.
9014      - The process that we're detaching from happens to immediately
9015        report a global breakpoint being hit in non-stop mode, in the
9016        same thread we had selected before.
9017      - GDB attaches to this process again.
9018      - This event happens to be the next event we handle.
9019
9020      GDB would consider that the current general thread didn't need to
9021      be set on the stub side (with Hg), since for all it knew,
9022      GENERAL_THREAD hadn't changed.
9023
9024      Notice that although in all-stop mode, the remote server always
9025      sets the current thread to the thread reporting the stop event,
9026      that doesn't happen in non-stop mode; in non-stop, the stub *must
9027      not* change the current thread when reporting a breakpoint hit,
9028      due to the decoupling of event reporting and event handling.
9029
9030      To keep things simple, we always invalidate our notion of the
9031      current thread.  */
9032   record_currthread (rs, minus_one_ptid);
9033
9034   /* Call common code to mark the inferior as not running.  */
9035   generic_mourn_inferior ();
9036
9037   if (!have_inferiors ())
9038     {
9039       if (!remote_multi_process_p (rs))
9040         {
9041           /* Check whether the target is running now - some remote stubs
9042              automatically restart after kill.  */
9043           putpkt ("?");
9044           getpkt (&rs->buf, &rs->buf_size, 0);
9045
9046           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9047             {
9048               /* Assume that the target has been restarted.  Set
9049                  inferior_ptid so that bits of core GDB realizes
9050                  there's something here, e.g., so that the user can
9051                  say "kill" again.  */
9052               inferior_ptid = magic_null_ptid;
9053             }
9054         }
9055     }
9056 }
9057
9058 static int
9059 extended_remote_supports_disable_randomization (struct target_ops *self)
9060 {
9061   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9062 }
9063
9064 static void
9065 extended_remote_disable_randomization (int val)
9066 {
9067   struct remote_state *rs = get_remote_state ();
9068   char *reply;
9069
9070   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9071              val);
9072   putpkt (rs->buf);
9073   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9074   if (*reply == '\0')
9075     error (_("Target does not support QDisableRandomization."));
9076   if (strcmp (reply, "OK") != 0)
9077     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9078 }
9079
9080 static int
9081 extended_remote_run (char *args)
9082 {
9083   struct remote_state *rs = get_remote_state ();
9084   int len;
9085   const char *remote_exec_file = get_remote_exec_file ();
9086
9087   /* If the user has disabled vRun support, or we have detected that
9088      support is not available, do not try it.  */
9089   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9090     return -1;
9091
9092   strcpy (rs->buf, "vRun;");
9093   len = strlen (rs->buf);
9094
9095   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9096     error (_("Remote file name too long for run packet"));
9097   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9098                       strlen (remote_exec_file));
9099
9100   gdb_assert (args != NULL);
9101   if (*args)
9102     {
9103       struct cleanup *back_to;
9104       int i;
9105       char **argv;
9106
9107       argv = gdb_buildargv (args);
9108       back_to = make_cleanup_freeargv (argv);
9109       for (i = 0; argv[i] != NULL; i++)
9110         {
9111           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9112             error (_("Argument list too long for run packet"));
9113           rs->buf[len++] = ';';
9114           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9115                               strlen (argv[i]));
9116         }
9117       do_cleanups (back_to);
9118     }
9119
9120   rs->buf[len++] = '\0';
9121
9122   putpkt (rs->buf);
9123   getpkt (&rs->buf, &rs->buf_size, 0);
9124
9125   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9126     {
9127     case PACKET_OK:
9128       /* We have a wait response.  All is well.  */
9129       return 0;
9130     case PACKET_UNKNOWN:
9131       return -1;
9132     case PACKET_ERROR:
9133       if (remote_exec_file[0] == '\0')
9134         error (_("Running the default executable on the remote target failed; "
9135                  "try \"set remote exec-file\"?"));
9136       else
9137         error (_("Running \"%s\" on the remote target failed"),
9138                remote_exec_file);
9139     default:
9140       gdb_assert_not_reached (_("bad switch"));
9141     }
9142 }
9143
9144 /* In the extended protocol we want to be able to do things like
9145    "run" and have them basically work as expected.  So we need
9146    a special create_inferior function.  We support changing the
9147    executable file and the command line arguments, but not the
9148    environment.  */
9149
9150 static void
9151 extended_remote_create_inferior (struct target_ops *ops,
9152                                  char *exec_file, char *args,
9153                                  char **env, int from_tty)
9154 {
9155   int run_worked;
9156   char *stop_reply;
9157   struct remote_state *rs = get_remote_state ();
9158   const char *remote_exec_file = get_remote_exec_file ();
9159
9160   /* If running asynchronously, register the target file descriptor
9161      with the event loop.  */
9162   if (target_can_async_p ())
9163     target_async (1);
9164
9165   /* Disable address space randomization if requested (and supported).  */
9166   if (extended_remote_supports_disable_randomization (ops))
9167     extended_remote_disable_randomization (disable_randomization);
9168
9169   /* Now restart the remote server.  */
9170   run_worked = extended_remote_run (args) != -1;
9171   if (!run_worked)
9172     {
9173       /* vRun was not supported.  Fail if we need it to do what the
9174          user requested.  */
9175       if (remote_exec_file[0])
9176         error (_("Remote target does not support \"set remote exec-file\""));
9177       if (args[0])
9178         error (_("Remote target does not support \"set args\" or run <ARGS>"));
9179
9180       /* Fall back to "R".  */
9181       extended_remote_restart ();
9182     }
9183
9184   if (!have_inferiors ())
9185     {
9186       /* Clean up from the last time we ran, before we mark the target
9187          running again.  This will mark breakpoints uninserted, and
9188          get_offsets may insert breakpoints.  */
9189       init_thread_list ();
9190       init_wait_for_inferior ();
9191     }
9192
9193   /* vRun's success return is a stop reply.  */
9194   stop_reply = run_worked ? rs->buf : NULL;
9195   add_current_inferior_and_thread (stop_reply);
9196
9197   /* Get updated offsets, if the stub uses qOffsets.  */
9198   get_offsets ();
9199 }
9200 \f
9201
9202 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
9203    the list of conditions (in agent expression bytecode format), if any, the
9204    target needs to evaluate.  The output is placed into the packet buffer
9205    started from BUF and ended at BUF_END.  */
9206
9207 static int
9208 remote_add_target_side_condition (struct gdbarch *gdbarch,
9209                                   struct bp_target_info *bp_tgt, char *buf,
9210                                   char *buf_end)
9211 {
9212   struct agent_expr *aexpr = NULL;
9213   int i, ix;
9214
9215   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9216     return 0;
9217
9218   buf += strlen (buf);
9219   xsnprintf (buf, buf_end - buf, "%s", ";");
9220   buf++;
9221
9222   /* Send conditions to the target and free the vector.  */
9223   for (ix = 0;
9224        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9225        ix++)
9226     {
9227       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9228       buf += strlen (buf);
9229       for (i = 0; i < aexpr->len; ++i)
9230         buf = pack_hex_byte (buf, aexpr->buf[i]);
9231       *buf = '\0';
9232     }
9233   return 0;
9234 }
9235
9236 static void
9237 remote_add_target_side_commands (struct gdbarch *gdbarch,
9238                                  struct bp_target_info *bp_tgt, char *buf)
9239 {
9240   struct agent_expr *aexpr = NULL;
9241   int i, ix;
9242
9243   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9244     return;
9245
9246   buf += strlen (buf);
9247
9248   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9249   buf += strlen (buf);
9250
9251   /* Concatenate all the agent expressions that are commands into the
9252      cmds parameter.  */
9253   for (ix = 0;
9254        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9255        ix++)
9256     {
9257       sprintf (buf, "X%x,", aexpr->len);
9258       buf += strlen (buf);
9259       for (i = 0; i < aexpr->len; ++i)
9260         buf = pack_hex_byte (buf, aexpr->buf[i]);
9261       *buf = '\0';
9262     }
9263 }
9264
9265 /* Insert a breakpoint.  On targets that have software breakpoint
9266    support, we ask the remote target to do the work; on targets
9267    which don't, we insert a traditional memory breakpoint.  */
9268
9269 static int
9270 remote_insert_breakpoint (struct target_ops *ops,
9271                           struct gdbarch *gdbarch,
9272                           struct bp_target_info *bp_tgt)
9273 {
9274   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9275      If it succeeds, then set the support to PACKET_ENABLE.  If it
9276      fails, and the user has explicitly requested the Z support then
9277      report an error, otherwise, mark it disabled and go on.  */
9278
9279   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9280     {
9281       CORE_ADDR addr = bp_tgt->reqstd_address;
9282       struct remote_state *rs;
9283       char *p, *endbuf;
9284       int bpsize;
9285
9286       /* Make sure the remote is pointing at the right process, if
9287          necessary.  */
9288       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9289         set_general_process ();
9290
9291       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9292
9293       rs = get_remote_state ();
9294       p = rs->buf;
9295       endbuf = rs->buf + get_remote_packet_size ();
9296
9297       *(p++) = 'Z';
9298       *(p++) = '0';
9299       *(p++) = ',';
9300       addr = (ULONGEST) remote_address_masked (addr);
9301       p += hexnumstr (p, addr);
9302       xsnprintf (p, endbuf - p, ",%d", bpsize);
9303
9304       if (remote_supports_cond_breakpoints (ops))
9305         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9306
9307       if (remote_can_run_breakpoint_commands (ops))
9308         remote_add_target_side_commands (gdbarch, bp_tgt, p);
9309
9310       putpkt (rs->buf);
9311       getpkt (&rs->buf, &rs->buf_size, 0);
9312
9313       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9314         {
9315         case PACKET_ERROR:
9316           return -1;
9317         case PACKET_OK:
9318           bp_tgt->placed_address = addr;
9319           bp_tgt->placed_size = bpsize;
9320           return 0;
9321         case PACKET_UNKNOWN:
9322           break;
9323         }
9324     }
9325
9326   /* If this breakpoint has target-side commands but this stub doesn't
9327      support Z0 packets, throw error.  */
9328   if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9329     throw_error (NOT_SUPPORTED_ERROR, _("\
9330 Target doesn't support breakpoints that have target side commands."));
9331
9332   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9333 }
9334
9335 static int
9336 remote_remove_breakpoint (struct target_ops *ops,
9337                           struct gdbarch *gdbarch,
9338                           struct bp_target_info *bp_tgt,
9339                           enum remove_bp_reason reason)
9340 {
9341   CORE_ADDR addr = bp_tgt->placed_address;
9342   struct remote_state *rs = get_remote_state ();
9343
9344   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9345     {
9346       char *p = rs->buf;
9347       char *endbuf = rs->buf + get_remote_packet_size ();
9348
9349       /* Make sure the remote is pointing at the right process, if
9350          necessary.  */
9351       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9352         set_general_process ();
9353
9354       *(p++) = 'z';
9355       *(p++) = '0';
9356       *(p++) = ',';
9357
9358       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9359       p += hexnumstr (p, addr);
9360       xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9361
9362       putpkt (rs->buf);
9363       getpkt (&rs->buf, &rs->buf_size, 0);
9364
9365       return (rs->buf[0] == 'E');
9366     }
9367
9368   return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
9369 }
9370
9371 static enum Z_packet_type
9372 watchpoint_to_Z_packet (int type)
9373 {
9374   switch (type)
9375     {
9376     case hw_write:
9377       return Z_PACKET_WRITE_WP;
9378       break;
9379     case hw_read:
9380       return Z_PACKET_READ_WP;
9381       break;
9382     case hw_access:
9383       return Z_PACKET_ACCESS_WP;
9384       break;
9385     default:
9386       internal_error (__FILE__, __LINE__,
9387                       _("hw_bp_to_z: bad watchpoint type %d"), type);
9388     }
9389 }
9390
9391 static int
9392 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9393                           enum target_hw_bp_type type, struct expression *cond)
9394 {
9395   struct remote_state *rs = get_remote_state ();
9396   char *endbuf = rs->buf + get_remote_packet_size ();
9397   char *p;
9398   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9399
9400   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9401     return 1;
9402
9403   /* Make sure the remote is pointing at the right process, if
9404      necessary.  */
9405   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9406     set_general_process ();
9407
9408   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9409   p = strchr (rs->buf, '\0');
9410   addr = remote_address_masked (addr);
9411   p += hexnumstr (p, (ULONGEST) addr);
9412   xsnprintf (p, endbuf - p, ",%x", len);
9413
9414   putpkt (rs->buf);
9415   getpkt (&rs->buf, &rs->buf_size, 0);
9416
9417   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9418     {
9419     case PACKET_ERROR:
9420       return -1;
9421     case PACKET_UNKNOWN:
9422       return 1;
9423     case PACKET_OK:
9424       return 0;
9425     }
9426   internal_error (__FILE__, __LINE__,
9427                   _("remote_insert_watchpoint: reached end of function"));
9428 }
9429
9430 static int
9431 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9432                                      CORE_ADDR start, int length)
9433 {
9434   CORE_ADDR diff = remote_address_masked (addr - start);
9435
9436   return diff < length;
9437 }
9438
9439
9440 static int
9441 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9442                           enum target_hw_bp_type type, struct expression *cond)
9443 {
9444   struct remote_state *rs = get_remote_state ();
9445   char *endbuf = rs->buf + get_remote_packet_size ();
9446   char *p;
9447   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9448
9449   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9450     return -1;
9451
9452   /* Make sure the remote is pointing at the right process, if
9453      necessary.  */
9454   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9455     set_general_process ();
9456
9457   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9458   p = strchr (rs->buf, '\0');
9459   addr = remote_address_masked (addr);
9460   p += hexnumstr (p, (ULONGEST) addr);
9461   xsnprintf (p, endbuf - p, ",%x", len);
9462   putpkt (rs->buf);
9463   getpkt (&rs->buf, &rs->buf_size, 0);
9464
9465   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9466     {
9467     case PACKET_ERROR:
9468     case PACKET_UNKNOWN:
9469       return -1;
9470     case PACKET_OK:
9471       return 0;
9472     }
9473   internal_error (__FILE__, __LINE__,
9474                   _("remote_remove_watchpoint: reached end of function"));
9475 }
9476
9477
9478 int remote_hw_watchpoint_limit = -1;
9479 int remote_hw_watchpoint_length_limit = -1;
9480 int remote_hw_breakpoint_limit = -1;
9481
9482 static int
9483 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9484                                     CORE_ADDR addr, int len)
9485 {
9486   if (remote_hw_watchpoint_length_limit == 0)
9487     return 0;
9488   else if (remote_hw_watchpoint_length_limit < 0)
9489     return 1;
9490   else if (len <= remote_hw_watchpoint_length_limit)
9491     return 1;
9492   else
9493     return 0;
9494 }
9495
9496 static int
9497 remote_check_watch_resources (struct target_ops *self,
9498                               enum bptype type, int cnt, int ot)
9499 {
9500   if (type == bp_hardware_breakpoint)
9501     {
9502       if (remote_hw_breakpoint_limit == 0)
9503         return 0;
9504       else if (remote_hw_breakpoint_limit < 0)
9505         return 1;
9506       else if (cnt <= remote_hw_breakpoint_limit)
9507         return 1;
9508     }
9509   else
9510     {
9511       if (remote_hw_watchpoint_limit == 0)
9512         return 0;
9513       else if (remote_hw_watchpoint_limit < 0)
9514         return 1;
9515       else if (ot)
9516         return -1;
9517       else if (cnt <= remote_hw_watchpoint_limit)
9518         return 1;
9519     }
9520   return -1;
9521 }
9522
9523 /* The to_stopped_by_sw_breakpoint method of target remote.  */
9524
9525 static int
9526 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9527 {
9528   struct thread_info *thread = inferior_thread ();
9529
9530   return (thread->priv != NULL
9531           && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9532 }
9533
9534 /* The to_supports_stopped_by_sw_breakpoint method of target
9535    remote.  */
9536
9537 static int
9538 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9539 {
9540   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9541 }
9542
9543 /* The to_stopped_by_hw_breakpoint method of target remote.  */
9544
9545 static int
9546 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9547 {
9548   struct thread_info *thread = inferior_thread ();
9549
9550   return (thread->priv != NULL
9551           && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9552 }
9553
9554 /* The to_supports_stopped_by_hw_breakpoint method of target
9555    remote.  */
9556
9557 static int
9558 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9559 {
9560   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9561 }
9562
9563 static int
9564 remote_stopped_by_watchpoint (struct target_ops *ops)
9565 {
9566   struct thread_info *thread = inferior_thread ();
9567
9568   return (thread->priv != NULL
9569           && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9570 }
9571
9572 static int
9573 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9574 {
9575   struct thread_info *thread = inferior_thread ();
9576
9577   if (thread->priv != NULL
9578       && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9579     {
9580       *addr_p = thread->priv->watch_data_address;
9581       return 1;
9582     }
9583
9584   return 0;
9585 }
9586
9587
9588 static int
9589 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9590                              struct bp_target_info *bp_tgt)
9591 {
9592   CORE_ADDR addr = bp_tgt->reqstd_address;
9593   struct remote_state *rs;
9594   char *p, *endbuf;
9595   char *message;
9596   int bpsize;
9597
9598   /* The length field should be set to the size of a breakpoint
9599      instruction, even though we aren't inserting one ourselves.  */
9600
9601   gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9602
9603   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9604     return -1;
9605
9606   /* Make sure the remote is pointing at the right process, if
9607      necessary.  */
9608   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9609     set_general_process ();
9610
9611   rs = get_remote_state ();
9612   p = rs->buf;
9613   endbuf = rs->buf + get_remote_packet_size ();
9614
9615   *(p++) = 'Z';
9616   *(p++) = '1';
9617   *(p++) = ',';
9618
9619   addr = remote_address_masked (addr);
9620   p += hexnumstr (p, (ULONGEST) addr);
9621   xsnprintf (p, endbuf - p, ",%x", bpsize);
9622
9623   if (remote_supports_cond_breakpoints (self))
9624     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9625
9626   if (remote_can_run_breakpoint_commands (self))
9627     remote_add_target_side_commands (gdbarch, bp_tgt, p);
9628
9629   putpkt (rs->buf);
9630   getpkt (&rs->buf, &rs->buf_size, 0);
9631
9632   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9633     {
9634     case PACKET_ERROR:
9635       if (rs->buf[1] == '.')
9636         {
9637           message = strchr (rs->buf + 2, '.');
9638           if (message)
9639             error (_("Remote failure reply: %s"), message + 1);
9640         }
9641       return -1;
9642     case PACKET_UNKNOWN:
9643       return -1;
9644     case PACKET_OK:
9645       bp_tgt->placed_address = addr;
9646       bp_tgt->placed_size = bpsize;
9647       return 0;
9648     }
9649   internal_error (__FILE__, __LINE__,
9650                   _("remote_insert_hw_breakpoint: reached end of function"));
9651 }
9652
9653
9654 static int
9655 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9656                              struct bp_target_info *bp_tgt)
9657 {
9658   CORE_ADDR addr;
9659   struct remote_state *rs = get_remote_state ();
9660   char *p = rs->buf;
9661   char *endbuf = rs->buf + get_remote_packet_size ();
9662
9663   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9664     return -1;
9665
9666   /* Make sure the remote is pointing at the right process, if
9667      necessary.  */
9668   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9669     set_general_process ();
9670
9671   *(p++) = 'z';
9672   *(p++) = '1';
9673   *(p++) = ',';
9674
9675   addr = remote_address_masked (bp_tgt->placed_address);
9676   p += hexnumstr (p, (ULONGEST) addr);
9677   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);
9678
9679   putpkt (rs->buf);
9680   getpkt (&rs->buf, &rs->buf_size, 0);
9681
9682   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9683     {
9684     case PACKET_ERROR:
9685     case PACKET_UNKNOWN:
9686       return -1;
9687     case PACKET_OK:
9688       return 0;
9689     }
9690   internal_error (__FILE__, __LINE__,
9691                   _("remote_remove_hw_breakpoint: reached end of function"));
9692 }
9693
9694 /* Verify memory using the "qCRC:" request.  */
9695
9696 static int
9697 remote_verify_memory (struct target_ops *ops,
9698                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9699 {
9700   struct remote_state *rs = get_remote_state ();
9701   unsigned long host_crc, target_crc;
9702   char *tmp;
9703
9704   /* It doesn't make sense to use qCRC if the remote target is
9705      connected but not running.  */
9706   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9707     {
9708       enum packet_result result;
9709
9710       /* Make sure the remote is pointing at the right process.  */
9711       set_general_process ();
9712
9713       /* FIXME: assumes lma can fit into long.  */
9714       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9715                  (long) lma, (long) size);
9716       putpkt (rs->buf);
9717
9718       /* Be clever; compute the host_crc before waiting for target
9719          reply.  */
9720       host_crc = xcrc32 (data, size, 0xffffffff);
9721
9722       getpkt (&rs->buf, &rs->buf_size, 0);
9723
9724       result = packet_ok (rs->buf,
9725                           &remote_protocol_packets[PACKET_qCRC]);
9726       if (result == PACKET_ERROR)
9727         return -1;
9728       else if (result == PACKET_OK)
9729         {
9730           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9731             target_crc = target_crc * 16 + fromhex (*tmp);
9732
9733           return (host_crc == target_crc);
9734         }
9735     }
9736
9737   return simple_verify_memory (ops, data, lma, size);
9738 }
9739
9740 /* compare-sections command
9741
9742    With no arguments, compares each loadable section in the exec bfd
9743    with the same memory range on the target, and reports mismatches.
9744    Useful for verifying the image on the target against the exec file.  */
9745
9746 static void
9747 compare_sections_command (char *args, int from_tty)
9748 {
9749   asection *s;
9750   struct cleanup *old_chain;
9751   gdb_byte *sectdata;
9752   const char *sectname;
9753   bfd_size_type size;
9754   bfd_vma lma;
9755   int matched = 0;
9756   int mismatched = 0;
9757   int res;
9758   int read_only = 0;
9759
9760   if (!exec_bfd)
9761     error (_("command cannot be used without an exec file"));
9762
9763   /* Make sure the remote is pointing at the right process.  */
9764   set_general_process ();
9765
9766   if (args != NULL && strcmp (args, "-r") == 0)
9767     {
9768       read_only = 1;
9769       args = NULL;
9770     }
9771
9772   for (s = exec_bfd->sections; s; s = s->next)
9773     {
9774       if (!(s->flags & SEC_LOAD))
9775         continue;               /* Skip non-loadable section.  */
9776
9777       if (read_only && (s->flags & SEC_READONLY) == 0)
9778         continue;               /* Skip writeable sections */
9779
9780       size = bfd_get_section_size (s);
9781       if (size == 0)
9782         continue;               /* Skip zero-length section.  */
9783
9784       sectname = bfd_get_section_name (exec_bfd, s);
9785       if (args && strcmp (args, sectname) != 0)
9786         continue;               /* Not the section selected by user.  */
9787
9788       matched = 1;              /* Do this section.  */
9789       lma = s->lma;
9790
9791       sectdata = (gdb_byte *) xmalloc (size);
9792       old_chain = make_cleanup (xfree, sectdata);
9793       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9794
9795       res = target_verify_memory (sectdata, lma, size);
9796
9797       if (res == -1)
9798         error (_("target memory fault, section %s, range %s -- %s"), sectname,
9799                paddress (target_gdbarch (), lma),
9800                paddress (target_gdbarch (), lma + size));
9801
9802       printf_filtered ("Section %s, range %s -- %s: ", sectname,
9803                        paddress (target_gdbarch (), lma),
9804                        paddress (target_gdbarch (), lma + size));
9805       if (res)
9806         printf_filtered ("matched.\n");
9807       else
9808         {
9809           printf_filtered ("MIS-MATCHED!\n");
9810           mismatched++;
9811         }
9812
9813       do_cleanups (old_chain);
9814     }
9815   if (mismatched > 0)
9816     warning (_("One or more sections of the target image does not match\n\
9817 the loaded file\n"));
9818   if (args && !matched)
9819     printf_filtered (_("No loaded section named '%s'.\n"), args);
9820 }
9821
9822 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9823    into remote target.  The number of bytes written to the remote
9824    target is returned, or -1 for error.  */
9825
9826 static enum target_xfer_status
9827 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9828                     const char *annex, const gdb_byte *writebuf, 
9829                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9830                     struct packet_config *packet)
9831 {
9832   int i, buf_len;
9833   ULONGEST n;
9834   struct remote_state *rs = get_remote_state ();
9835   int max_size = get_memory_write_packet_size (); 
9836
9837   if (packet->support == PACKET_DISABLE)
9838     return TARGET_XFER_E_IO;
9839
9840   /* Insert header.  */
9841   i = snprintf (rs->buf, max_size, 
9842                 "qXfer:%s:write:%s:%s:",
9843                 object_name, annex ? annex : "",
9844                 phex_nz (offset, sizeof offset));
9845   max_size -= (i + 1);
9846
9847   /* Escape as much data as fits into rs->buf.  */
9848   buf_len = remote_escape_output 
9849     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9850
9851   if (putpkt_binary (rs->buf, i + buf_len) < 0
9852       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9853       || packet_ok (rs->buf, packet) != PACKET_OK)
9854     return TARGET_XFER_E_IO;
9855
9856   unpack_varlen_hex (rs->buf, &n);
9857
9858   *xfered_len = n;
9859   return TARGET_XFER_OK;
9860 }
9861
9862 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9863    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9864    number of bytes read is returned, or 0 for EOF, or -1 for error.
9865    The number of bytes read may be less than LEN without indicating an
9866    EOF.  PACKET is checked and updated to indicate whether the remote
9867    target supports this object.  */
9868
9869 static enum target_xfer_status
9870 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9871                    const char *annex,
9872                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9873                    ULONGEST *xfered_len,
9874                    struct packet_config *packet)
9875 {
9876   struct remote_state *rs = get_remote_state ();
9877   LONGEST i, n, packet_len;
9878
9879   if (packet->support == PACKET_DISABLE)
9880     return TARGET_XFER_E_IO;
9881
9882   /* Check whether we've cached an end-of-object packet that matches
9883      this request.  */
9884   if (rs->finished_object)
9885     {
9886       if (strcmp (object_name, rs->finished_object) == 0
9887           && strcmp (annex ? annex : "", rs->finished_annex) == 0
9888           && offset == rs->finished_offset)
9889         return TARGET_XFER_EOF;
9890
9891
9892       /* Otherwise, we're now reading something different.  Discard
9893          the cache.  */
9894       xfree (rs->finished_object);
9895       xfree (rs->finished_annex);
9896       rs->finished_object = NULL;
9897       rs->finished_annex = NULL;
9898     }
9899
9900   /* Request only enough to fit in a single packet.  The actual data
9901      may not, since we don't know how much of it will need to be escaped;
9902      the target is free to respond with slightly less data.  We subtract
9903      five to account for the response type and the protocol frame.  */
9904   n = min (get_remote_packet_size () - 5, len);
9905   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9906             object_name, annex ? annex : "",
9907             phex_nz (offset, sizeof offset),
9908             phex_nz (n, sizeof n));
9909   i = putpkt (rs->buf);
9910   if (i < 0)
9911     return TARGET_XFER_E_IO;
9912
9913   rs->buf[0] = '\0';
9914   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9915   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9916     return TARGET_XFER_E_IO;
9917
9918   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9919     error (_("Unknown remote qXfer reply: %s"), rs->buf);
9920
9921   /* 'm' means there is (or at least might be) more data after this
9922      batch.  That does not make sense unless there's at least one byte
9923      of data in this reply.  */
9924   if (rs->buf[0] == 'm' && packet_len == 1)
9925     error (_("Remote qXfer reply contained no data."));
9926
9927   /* Got some data.  */
9928   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9929                              packet_len - 1, readbuf, n);
9930
9931   /* 'l' is an EOF marker, possibly including a final block of data,
9932      or possibly empty.  If we have the final block of a non-empty
9933      object, record this fact to bypass a subsequent partial read.  */
9934   if (rs->buf[0] == 'l' && offset + i > 0)
9935     {
9936       rs->finished_object = xstrdup (object_name);
9937       rs->finished_annex = xstrdup (annex ? annex : "");
9938       rs->finished_offset = offset + i;
9939     }
9940
9941   if (i == 0)
9942     return TARGET_XFER_EOF;
9943   else
9944     {
9945       *xfered_len = i;
9946       return TARGET_XFER_OK;
9947     }
9948 }
9949
9950 static enum target_xfer_status
9951 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9952                      const char *annex, gdb_byte *readbuf,
9953                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9954                      ULONGEST *xfered_len)
9955 {
9956   struct remote_state *rs;
9957   int i;
9958   char *p2;
9959   char query_type;
9960   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9961
9962   set_remote_traceframe ();
9963   set_general_thread (inferior_ptid);
9964
9965   rs = get_remote_state ();
9966
9967   /* Handle memory using the standard memory routines.  */
9968   if (object == TARGET_OBJECT_MEMORY)
9969     {
9970       /* If the remote target is connected but not running, we should
9971          pass this request down to a lower stratum (e.g. the executable
9972          file).  */
9973       if (!target_has_execution)
9974         return TARGET_XFER_EOF;
9975
9976       if (writebuf != NULL)
9977         return remote_write_bytes (offset, writebuf, len, unit_size,
9978                                    xfered_len);
9979       else
9980         return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9981                                   xfered_len);
9982     }
9983
9984   /* Handle SPU memory using qxfer packets.  */
9985   if (object == TARGET_OBJECT_SPU)
9986     {
9987       if (readbuf)
9988         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9989                                   xfered_len, &remote_protocol_packets
9990                                   [PACKET_qXfer_spu_read]);
9991       else
9992         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9993                                    xfered_len, &remote_protocol_packets
9994                                    [PACKET_qXfer_spu_write]);
9995     }
9996
9997   /* Handle extra signal info using qxfer packets.  */
9998   if (object == TARGET_OBJECT_SIGNAL_INFO)
9999     {
10000       if (readbuf)
10001         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10002                                   xfered_len, &remote_protocol_packets
10003                                   [PACKET_qXfer_siginfo_read]);
10004       else
10005         return remote_write_qxfer (ops, "siginfo", annex,
10006                                    writebuf, offset, len, xfered_len,
10007                                    &remote_protocol_packets
10008                                    [PACKET_qXfer_siginfo_write]);
10009     }
10010
10011   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10012     {
10013       if (readbuf)
10014         return remote_read_qxfer (ops, "statictrace", annex,
10015                                   readbuf, offset, len, xfered_len,
10016                                   &remote_protocol_packets
10017                                   [PACKET_qXfer_statictrace_read]);
10018       else
10019         return TARGET_XFER_E_IO;
10020     }
10021
10022   /* Only handle flash writes.  */
10023   if (writebuf != NULL)
10024     {
10025       switch (object)
10026         {
10027         case TARGET_OBJECT_FLASH:
10028           return remote_flash_write (ops, offset, len, xfered_len,
10029                                      writebuf);
10030
10031         default:
10032           return TARGET_XFER_E_IO;
10033         }
10034     }
10035
10036   /* Map pre-existing objects onto letters.  DO NOT do this for new
10037      objects!!!  Instead specify new query packets.  */
10038   switch (object)
10039     {
10040     case TARGET_OBJECT_AVR:
10041       query_type = 'R';
10042       break;
10043
10044     case TARGET_OBJECT_AUXV:
10045       gdb_assert (annex == NULL);
10046       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10047                                 xfered_len,
10048                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10049
10050     case TARGET_OBJECT_AVAILABLE_FEATURES:
10051       return remote_read_qxfer
10052         (ops, "features", annex, readbuf, offset, len, xfered_len,
10053          &remote_protocol_packets[PACKET_qXfer_features]);
10054
10055     case TARGET_OBJECT_LIBRARIES:
10056       return remote_read_qxfer
10057         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10058          &remote_protocol_packets[PACKET_qXfer_libraries]);
10059
10060     case TARGET_OBJECT_LIBRARIES_SVR4:
10061       return remote_read_qxfer
10062         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10063          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10064
10065     case TARGET_OBJECT_MEMORY_MAP:
10066       gdb_assert (annex == NULL);
10067       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10068                                  xfered_len,
10069                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10070
10071     case TARGET_OBJECT_OSDATA:
10072       /* Should only get here if we're connected.  */
10073       gdb_assert (rs->remote_desc);
10074       return remote_read_qxfer
10075         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10076         &remote_protocol_packets[PACKET_qXfer_osdata]);
10077
10078     case TARGET_OBJECT_THREADS:
10079       gdb_assert (annex == NULL);
10080       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10081                                 xfered_len,
10082                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10083
10084     case TARGET_OBJECT_TRACEFRAME_INFO:
10085       gdb_assert (annex == NULL);
10086       return remote_read_qxfer
10087         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10088          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10089
10090     case TARGET_OBJECT_FDPIC:
10091       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10092                                 xfered_len,
10093                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10094
10095     case TARGET_OBJECT_OPENVMS_UIB:
10096       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10097                                 xfered_len,
10098                                 &remote_protocol_packets[PACKET_qXfer_uib]);
10099
10100     case TARGET_OBJECT_BTRACE:
10101       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10102                                 xfered_len,
10103         &remote_protocol_packets[PACKET_qXfer_btrace]);
10104
10105     case TARGET_OBJECT_BTRACE_CONF:
10106       return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10107                                 len, xfered_len,
10108         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10109
10110     case TARGET_OBJECT_EXEC_FILE:
10111       return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10112                                 len, xfered_len,
10113         &remote_protocol_packets[PACKET_qXfer_exec_file]);
10114
10115     default:
10116       return TARGET_XFER_E_IO;
10117     }
10118
10119   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
10120      large enough let the caller deal with it.  */
10121   if (len < get_remote_packet_size ())
10122     return TARGET_XFER_E_IO;
10123   len = get_remote_packet_size ();
10124
10125   /* Except for querying the minimum buffer size, target must be open.  */
10126   if (!rs->remote_desc)
10127     error (_("remote query is only available after target open"));
10128
10129   gdb_assert (annex != NULL);
10130   gdb_assert (readbuf != NULL);
10131
10132   p2 = rs->buf;
10133   *p2++ = 'q';
10134   *p2++ = query_type;
10135
10136   /* We used one buffer char for the remote protocol q command and
10137      another for the query type.  As the remote protocol encapsulation
10138      uses 4 chars plus one extra in case we are debugging
10139      (remote_debug), we have PBUFZIZ - 7 left to pack the query
10140      string.  */
10141   i = 0;
10142   while (annex[i] && (i < (get_remote_packet_size () - 8)))
10143     {
10144       /* Bad caller may have sent forbidden characters.  */
10145       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10146       *p2++ = annex[i];
10147       i++;
10148     }
10149   *p2 = '\0';
10150   gdb_assert (annex[i] == '\0');
10151
10152   i = putpkt (rs->buf);
10153   if (i < 0)
10154     return TARGET_XFER_E_IO;
10155
10156   getpkt (&rs->buf, &rs->buf_size, 0);
10157   strcpy ((char *) readbuf, rs->buf);
10158
10159   *xfered_len = strlen ((char *) readbuf);
10160   return TARGET_XFER_OK;
10161 }
10162
10163 /* Implementation of to_get_memory_xfer_limit.  */
10164
10165 static ULONGEST
10166 remote_get_memory_xfer_limit (struct target_ops *ops)
10167 {
10168   return get_memory_write_packet_size ();
10169 }
10170
10171 static int
10172 remote_search_memory (struct target_ops* ops,
10173                       CORE_ADDR start_addr, ULONGEST search_space_len,
10174                       const gdb_byte *pattern, ULONGEST pattern_len,
10175                       CORE_ADDR *found_addrp)
10176 {
10177   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10178   struct remote_state *rs = get_remote_state ();
10179   int max_size = get_memory_write_packet_size ();
10180   struct packet_config *packet =
10181     &remote_protocol_packets[PACKET_qSearch_memory];
10182   /* Number of packet bytes used to encode the pattern;
10183      this could be more than PATTERN_LEN due to escape characters.  */
10184   int escaped_pattern_len;
10185   /* Amount of pattern that was encodable in the packet.  */
10186   int used_pattern_len;
10187   int i;
10188   int found;
10189   ULONGEST found_addr;
10190
10191   /* Don't go to the target if we don't have to.
10192      This is done before checking packet->support to avoid the possibility that
10193      a success for this edge case means the facility works in general.  */
10194   if (pattern_len > search_space_len)
10195     return 0;
10196   if (pattern_len == 0)
10197     {
10198       *found_addrp = start_addr;
10199       return 1;
10200     }
10201
10202   /* If we already know the packet isn't supported, fall back to the simple
10203      way of searching memory.  */
10204
10205   if (packet_config_support (packet) == PACKET_DISABLE)
10206     {
10207       /* Target doesn't provided special support, fall back and use the
10208          standard support (copy memory and do the search here).  */
10209       return simple_search_memory (ops, start_addr, search_space_len,
10210                                    pattern, pattern_len, found_addrp);
10211     }
10212
10213   /* Make sure the remote is pointing at the right process.  */
10214   set_general_process ();
10215
10216   /* Insert header.  */
10217   i = snprintf (rs->buf, max_size, 
10218                 "qSearch:memory:%s;%s;",
10219                 phex_nz (start_addr, addr_size),
10220                 phex_nz (search_space_len, sizeof (search_space_len)));
10221   max_size -= (i + 1);
10222
10223   /* Escape as much data as fits into rs->buf.  */
10224   escaped_pattern_len =
10225     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10226                           &used_pattern_len, max_size);
10227
10228   /* Bail if the pattern is too large.  */
10229   if (used_pattern_len != pattern_len)
10230     error (_("Pattern is too large to transmit to remote target."));
10231
10232   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10233       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10234       || packet_ok (rs->buf, packet) != PACKET_OK)
10235     {
10236       /* The request may not have worked because the command is not
10237          supported.  If so, fall back to the simple way.  */
10238       if (packet->support == PACKET_DISABLE)
10239         {
10240           return simple_search_memory (ops, start_addr, search_space_len,
10241                                        pattern, pattern_len, found_addrp);
10242         }
10243       return -1;
10244     }
10245
10246   if (rs->buf[0] == '0')
10247     found = 0;
10248   else if (rs->buf[0] == '1')
10249     {
10250       found = 1;
10251       if (rs->buf[1] != ',')
10252         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10253       unpack_varlen_hex (rs->buf + 2, &found_addr);
10254       *found_addrp = found_addr;
10255     }
10256   else
10257     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10258
10259   return found;
10260 }
10261
10262 static void
10263 remote_rcmd (struct target_ops *self, const char *command,
10264              struct ui_file *outbuf)
10265 {
10266   struct remote_state *rs = get_remote_state ();
10267   char *p = rs->buf;
10268
10269   if (!rs->remote_desc)
10270     error (_("remote rcmd is only available after target open"));
10271
10272   /* Send a NULL command across as an empty command.  */
10273   if (command == NULL)
10274     command = "";
10275
10276   /* The query prefix.  */
10277   strcpy (rs->buf, "qRcmd,");
10278   p = strchr (rs->buf, '\0');
10279
10280   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10281       > get_remote_packet_size ())
10282     error (_("\"monitor\" command ``%s'' is too long."), command);
10283
10284   /* Encode the actual command.  */
10285   bin2hex ((const gdb_byte *) command, p, strlen (command));
10286
10287   if (putpkt (rs->buf) < 0)
10288     error (_("Communication problem with target."));
10289
10290   /* get/display the response */
10291   while (1)
10292     {
10293       char *buf;
10294
10295       /* XXX - see also remote_get_noisy_reply().  */
10296       QUIT;                     /* Allow user to bail out with ^C.  */
10297       rs->buf[0] = '\0';
10298       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10299         { 
10300           /* Timeout.  Continue to (try to) read responses.
10301              This is better than stopping with an error, assuming the stub
10302              is still executing the (long) monitor command.
10303              If needed, the user can interrupt gdb using C-c, obtaining
10304              an effect similar to stop on timeout.  */
10305           continue;
10306         }
10307       buf = rs->buf;
10308       if (buf[0] == '\0')
10309         error (_("Target does not support this command."));
10310       if (buf[0] == 'O' && buf[1] != 'K')
10311         {
10312           remote_console_output (buf + 1); /* 'O' message from stub.  */
10313           continue;
10314         }
10315       if (strcmp (buf, "OK") == 0)
10316         break;
10317       if (strlen (buf) == 3 && buf[0] == 'E'
10318           && isdigit (buf[1]) && isdigit (buf[2]))
10319         {
10320           error (_("Protocol error with Rcmd"));
10321         }
10322       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10323         {
10324           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10325
10326           fputc_unfiltered (c, outbuf);
10327         }
10328       break;
10329     }
10330 }
10331
10332 static VEC(mem_region_s) *
10333 remote_memory_map (struct target_ops *ops)
10334 {
10335   VEC(mem_region_s) *result = NULL;
10336   char *text = target_read_stralloc (&current_target,
10337                                      TARGET_OBJECT_MEMORY_MAP, NULL);
10338
10339   if (text)
10340     {
10341       struct cleanup *back_to = make_cleanup (xfree, text);
10342
10343       result = parse_memory_map (text);
10344       do_cleanups (back_to);
10345     }
10346
10347   return result;
10348 }
10349
10350 static void
10351 packet_command (char *args, int from_tty)
10352 {
10353   struct remote_state *rs = get_remote_state ();
10354
10355   if (!rs->remote_desc)
10356     error (_("command can only be used with remote target"));
10357
10358   if (!args)
10359     error (_("remote-packet command requires packet text as argument"));
10360
10361   puts_filtered ("sending: ");
10362   print_packet (args);
10363   puts_filtered ("\n");
10364   putpkt (args);
10365
10366   getpkt (&rs->buf, &rs->buf_size, 0);
10367   puts_filtered ("received: ");
10368   print_packet (rs->buf);
10369   puts_filtered ("\n");
10370 }
10371
10372 #if 0
10373 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10374
10375 static void display_thread_info (struct gdb_ext_thread_info *info);
10376
10377 static void threadset_test_cmd (char *cmd, int tty);
10378
10379 static void threadalive_test (char *cmd, int tty);
10380
10381 static void threadlist_test_cmd (char *cmd, int tty);
10382
10383 int get_and_display_threadinfo (threadref *ref);
10384
10385 static void threadinfo_test_cmd (char *cmd, int tty);
10386
10387 static int thread_display_step (threadref *ref, void *context);
10388
10389 static void threadlist_update_test_cmd (char *cmd, int tty);
10390
10391 static void init_remote_threadtests (void);
10392
10393 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
10394
10395 static void
10396 threadset_test_cmd (char *cmd, int tty)
10397 {
10398   int sample_thread = SAMPLE_THREAD;
10399
10400   printf_filtered (_("Remote threadset test\n"));
10401   set_general_thread (sample_thread);
10402 }
10403
10404
10405 static void
10406 threadalive_test (char *cmd, int tty)
10407 {
10408   int sample_thread = SAMPLE_THREAD;
10409   int pid = ptid_get_pid (inferior_ptid);
10410   ptid_t ptid = ptid_build (pid, sample_thread, 0);
10411
10412   if (remote_thread_alive (ptid))
10413     printf_filtered ("PASS: Thread alive test\n");
10414   else
10415     printf_filtered ("FAIL: Thread alive test\n");
10416 }
10417
10418 void output_threadid (char *title, threadref *ref);
10419
10420 void
10421 output_threadid (char *title, threadref *ref)
10422 {
10423   char hexid[20];
10424
10425   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
10426   hexid[16] = 0;
10427   printf_filtered ("%s  %s\n", title, (&hexid[0]));
10428 }
10429
10430 static void
10431 threadlist_test_cmd (char *cmd, int tty)
10432 {
10433   int startflag = 1;
10434   threadref nextthread;
10435   int done, result_count;
10436   threadref threadlist[3];
10437
10438   printf_filtered ("Remote Threadlist test\n");
10439   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10440                               &result_count, &threadlist[0]))
10441     printf_filtered ("FAIL: threadlist test\n");
10442   else
10443     {
10444       threadref *scan = threadlist;
10445       threadref *limit = scan + result_count;
10446
10447       while (scan < limit)
10448         output_threadid (" thread ", scan++);
10449     }
10450 }
10451
10452 void
10453 display_thread_info (struct gdb_ext_thread_info *info)
10454 {
10455   output_threadid ("Threadid: ", &info->threadid);
10456   printf_filtered ("Name: %s\n ", info->shortname);
10457   printf_filtered ("State: %s\n", info->display);
10458   printf_filtered ("other: %s\n\n", info->more_display);
10459 }
10460
10461 int
10462 get_and_display_threadinfo (threadref *ref)
10463 {
10464   int result;
10465   int set;
10466   struct gdb_ext_thread_info threadinfo;
10467
10468   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10469     | TAG_MOREDISPLAY | TAG_DISPLAY;
10470   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10471     display_thread_info (&threadinfo);
10472   return result;
10473 }
10474
10475 static void
10476 threadinfo_test_cmd (char *cmd, int tty)
10477 {
10478   int athread = SAMPLE_THREAD;
10479   threadref thread;
10480   int set;
10481
10482   int_to_threadref (&thread, athread);
10483   printf_filtered ("Remote Threadinfo test\n");
10484   if (!get_and_display_threadinfo (&thread))
10485     printf_filtered ("FAIL cannot get thread info\n");
10486 }
10487
10488 static int
10489 thread_display_step (threadref *ref, void *context)
10490 {
10491   /* output_threadid(" threadstep ",ref); *//* simple test */
10492   return get_and_display_threadinfo (ref);
10493 }
10494
10495 static void
10496 threadlist_update_test_cmd (char *cmd, int tty)
10497 {
10498   printf_filtered ("Remote Threadlist update test\n");
10499   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10500 }
10501
10502 static void
10503 init_remote_threadtests (void)
10504 {
10505   add_com ("tlist", class_obscure, threadlist_test_cmd,
10506            _("Fetch and print the remote list of "
10507              "thread identifiers, one pkt only"));
10508   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10509            _("Fetch and display info about one thread"));
10510   add_com ("tset", class_obscure, threadset_test_cmd,
10511            _("Test setting to a different thread"));
10512   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10513            _("Iterate through updating all remote thread info"));
10514   add_com ("talive", class_obscure, threadalive_test,
10515            _(" Remote thread alive test "));
10516 }
10517
10518 #endif /* 0 */
10519
10520 /* Convert a thread ID to a string.  Returns the string in a static
10521    buffer.  */
10522
10523 static char *
10524 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10525 {
10526   static char buf[64];
10527   struct remote_state *rs = get_remote_state ();
10528
10529   if (ptid_equal (ptid, null_ptid))
10530     return normal_pid_to_str (ptid);
10531   else if (ptid_is_pid (ptid))
10532     {
10533       /* Printing an inferior target id.  */
10534
10535       /* When multi-process extensions are off, there's no way in the
10536          remote protocol to know the remote process id, if there's any
10537          at all.  There's one exception --- when we're connected with
10538          target extended-remote, and we manually attached to a process
10539          with "attach PID".  We don't record anywhere a flag that
10540          allows us to distinguish that case from the case of
10541          connecting with extended-remote and the stub already being
10542          attached to a process, and reporting yes to qAttached, hence
10543          no smart special casing here.  */
10544       if (!remote_multi_process_p (rs))
10545         {
10546           xsnprintf (buf, sizeof buf, "Remote target");
10547           return buf;
10548         }
10549
10550       return normal_pid_to_str (ptid);
10551     }
10552   else
10553     {
10554       if (ptid_equal (magic_null_ptid, ptid))
10555         xsnprintf (buf, sizeof buf, "Thread <main>");
10556       else if (remote_multi_process_p (rs))
10557         if (ptid_get_lwp (ptid) == 0)
10558           return normal_pid_to_str (ptid);
10559         else
10560           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10561                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
10562       else
10563         xsnprintf (buf, sizeof buf, "Thread %ld",
10564                    ptid_get_lwp (ptid));
10565       return buf;
10566     }
10567 }
10568
10569 /* Get the address of the thread local variable in OBJFILE which is
10570    stored at OFFSET within the thread local storage for thread PTID.  */
10571
10572 static CORE_ADDR
10573 remote_get_thread_local_address (struct target_ops *ops,
10574                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10575 {
10576   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10577     {
10578       struct remote_state *rs = get_remote_state ();
10579       char *p = rs->buf;
10580       char *endp = rs->buf + get_remote_packet_size ();
10581       enum packet_result result;
10582
10583       strcpy (p, "qGetTLSAddr:");
10584       p += strlen (p);
10585       p = write_ptid (p, endp, ptid);
10586       *p++ = ',';
10587       p += hexnumstr (p, offset);
10588       *p++ = ',';
10589       p += hexnumstr (p, lm);
10590       *p++ = '\0';
10591
10592       putpkt (rs->buf);
10593       getpkt (&rs->buf, &rs->buf_size, 0);
10594       result = packet_ok (rs->buf,
10595                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
10596       if (result == PACKET_OK)
10597         {
10598           ULONGEST result;
10599
10600           unpack_varlen_hex (rs->buf, &result);
10601           return result;
10602         }
10603       else if (result == PACKET_UNKNOWN)
10604         throw_error (TLS_GENERIC_ERROR,
10605                      _("Remote target doesn't support qGetTLSAddr packet"));
10606       else
10607         throw_error (TLS_GENERIC_ERROR,
10608                      _("Remote target failed to process qGetTLSAddr request"));
10609     }
10610   else
10611     throw_error (TLS_GENERIC_ERROR,
10612                  _("TLS not supported or disabled on this target"));
10613   /* Not reached.  */
10614   return 0;
10615 }
10616
10617 /* Provide thread local base, i.e. Thread Information Block address.
10618    Returns 1 if ptid is found and thread_local_base is non zero.  */
10619
10620 static int
10621 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10622 {
10623   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10624     {
10625       struct remote_state *rs = get_remote_state ();
10626       char *p = rs->buf;
10627       char *endp = rs->buf + get_remote_packet_size ();
10628       enum packet_result result;
10629
10630       strcpy (p, "qGetTIBAddr:");
10631       p += strlen (p);
10632       p = write_ptid (p, endp, ptid);
10633       *p++ = '\0';
10634
10635       putpkt (rs->buf);
10636       getpkt (&rs->buf, &rs->buf_size, 0);
10637       result = packet_ok (rs->buf,
10638                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
10639       if (result == PACKET_OK)
10640         {
10641           ULONGEST result;
10642
10643           unpack_varlen_hex (rs->buf, &result);
10644           if (addr)
10645             *addr = (CORE_ADDR) result;
10646           return 1;
10647         }
10648       else if (result == PACKET_UNKNOWN)
10649         error (_("Remote target doesn't support qGetTIBAddr packet"));
10650       else
10651         error (_("Remote target failed to process qGetTIBAddr request"));
10652     }
10653   else
10654     error (_("qGetTIBAddr not supported or disabled on this target"));
10655   /* Not reached.  */
10656   return 0;
10657 }
10658
10659 /* Support for inferring a target description based on the current
10660    architecture and the size of a 'g' packet.  While the 'g' packet
10661    can have any size (since optional registers can be left off the
10662    end), some sizes are easily recognizable given knowledge of the
10663    approximate architecture.  */
10664
10665 struct remote_g_packet_guess
10666 {
10667   int bytes;
10668   const struct target_desc *tdesc;
10669 };
10670 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10671 DEF_VEC_O(remote_g_packet_guess_s);
10672
10673 struct remote_g_packet_data
10674 {
10675   VEC(remote_g_packet_guess_s) *guesses;
10676 };
10677
10678 static struct gdbarch_data *remote_g_packet_data_handle;
10679
10680 static void *
10681 remote_g_packet_data_init (struct obstack *obstack)
10682 {
10683   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10684 }
10685
10686 void
10687 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10688                                 const struct target_desc *tdesc)
10689 {
10690   struct remote_g_packet_data *data
10691     = ((struct remote_g_packet_data *)
10692        gdbarch_data (gdbarch, remote_g_packet_data_handle));
10693   struct remote_g_packet_guess new_guess, *guess;
10694   int ix;
10695
10696   gdb_assert (tdesc != NULL);
10697
10698   for (ix = 0;
10699        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10700        ix++)
10701     if (guess->bytes == bytes)
10702       internal_error (__FILE__, __LINE__,
10703                       _("Duplicate g packet description added for size %d"),
10704                       bytes);
10705
10706   new_guess.bytes = bytes;
10707   new_guess.tdesc = tdesc;
10708   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10709 }
10710
10711 /* Return 1 if remote_read_description would do anything on this target
10712    and architecture, 0 otherwise.  */
10713
10714 static int
10715 remote_read_description_p (struct target_ops *target)
10716 {
10717   struct remote_g_packet_data *data
10718     = ((struct remote_g_packet_data *)
10719        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10720
10721   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10722     return 1;
10723
10724   return 0;
10725 }
10726
10727 static const struct target_desc *
10728 remote_read_description (struct target_ops *target)
10729 {
10730   struct remote_g_packet_data *data
10731     = ((struct remote_g_packet_data *)
10732        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10733
10734   /* Do not try this during initial connection, when we do not know
10735      whether there is a running but stopped thread.  */
10736   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10737     return target->beneath->to_read_description (target->beneath);
10738
10739   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10740     {
10741       struct remote_g_packet_guess *guess;
10742       int ix;
10743       int bytes = send_g_packet ();
10744
10745       for (ix = 0;
10746            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10747            ix++)
10748         if (guess->bytes == bytes)
10749           return guess->tdesc;
10750
10751       /* We discard the g packet.  A minor optimization would be to
10752          hold on to it, and fill the register cache once we have selected
10753          an architecture, but it's too tricky to do safely.  */
10754     }
10755
10756   return target->beneath->to_read_description (target->beneath);
10757 }
10758
10759 /* Remote file transfer support.  This is host-initiated I/O, not
10760    target-initiated; for target-initiated, see remote-fileio.c.  */
10761
10762 /* If *LEFT is at least the length of STRING, copy STRING to
10763    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10764    decrease *LEFT.  Otherwise raise an error.  */
10765
10766 static void
10767 remote_buffer_add_string (char **buffer, int *left, char *string)
10768 {
10769   int len = strlen (string);
10770
10771   if (len > *left)
10772     error (_("Packet too long for target."));
10773
10774   memcpy (*buffer, string, len);
10775   *buffer += len;
10776   *left -= len;
10777
10778   /* NUL-terminate the buffer as a convenience, if there is
10779      room.  */
10780   if (*left)
10781     **buffer = '\0';
10782 }
10783
10784 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10785    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10786    decrease *LEFT.  Otherwise raise an error.  */
10787
10788 static void
10789 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10790                          int len)
10791 {
10792   if (2 * len > *left)
10793     error (_("Packet too long for target."));
10794
10795   bin2hex (bytes, *buffer, len);
10796   *buffer += 2 * len;
10797   *left -= 2 * len;
10798
10799   /* NUL-terminate the buffer as a convenience, if there is
10800      room.  */
10801   if (*left)
10802     **buffer = '\0';
10803 }
10804
10805 /* If *LEFT is large enough, convert VALUE to hex and add it to
10806    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10807    decrease *LEFT.  Otherwise raise an error.  */
10808
10809 static void
10810 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10811 {
10812   int len = hexnumlen (value);
10813
10814   if (len > *left)
10815     error (_("Packet too long for target."));
10816
10817   hexnumstr (*buffer, value);
10818   *buffer += len;
10819   *left -= len;
10820
10821   /* NUL-terminate the buffer as a convenience, if there is
10822      room.  */
10823   if (*left)
10824     **buffer = '\0';
10825 }
10826
10827 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
10828    value, *REMOTE_ERRNO to the remote error number or zero if none
10829    was included, and *ATTACHMENT to point to the start of the annex
10830    if any.  The length of the packet isn't needed here; there may
10831    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10832
10833    Return 0 if the packet could be parsed, -1 if it could not.  If
10834    -1 is returned, the other variables may not be initialized.  */
10835
10836 static int
10837 remote_hostio_parse_result (char *buffer, int *retcode,
10838                             int *remote_errno, char **attachment)
10839 {
10840   char *p, *p2;
10841
10842   *remote_errno = 0;
10843   *attachment = NULL;
10844
10845   if (buffer[0] != 'F')
10846     return -1;
10847
10848   errno = 0;
10849   *retcode = strtol (&buffer[1], &p, 16);
10850   if (errno != 0 || p == &buffer[1])
10851     return -1;
10852
10853   /* Check for ",errno".  */
10854   if (*p == ',')
10855     {
10856       errno = 0;
10857       *remote_errno = strtol (p + 1, &p2, 16);
10858       if (errno != 0 || p + 1 == p2)
10859         return -1;
10860       p = p2;
10861     }
10862
10863   /* Check for ";attachment".  If there is no attachment, the
10864      packet should end here.  */
10865   if (*p == ';')
10866     {
10867       *attachment = p + 1;
10868       return 0;
10869     }
10870   else if (*p == '\0')
10871     return 0;
10872   else
10873     return -1;
10874 }
10875
10876 /* Send a prepared I/O packet to the target and read its response.
10877    The prepared packet is in the global RS->BUF before this function
10878    is called, and the answer is there when we return.
10879
10880    COMMAND_BYTES is the length of the request to send, which may include
10881    binary data.  WHICH_PACKET is the packet configuration to check
10882    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
10883    is set to the error number and -1 is returned.  Otherwise the value
10884    returned by the function is returned.
10885
10886    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10887    attachment is expected; an error will be reported if there's a
10888    mismatch.  If one is found, *ATTACHMENT will be set to point into
10889    the packet buffer and *ATTACHMENT_LEN will be set to the
10890    attachment's length.  */
10891
10892 static int
10893 remote_hostio_send_command (int command_bytes, int which_packet,
10894                             int *remote_errno, char **attachment,
10895                             int *attachment_len)
10896 {
10897   struct remote_state *rs = get_remote_state ();
10898   int ret, bytes_read;
10899   char *attachment_tmp;
10900
10901   if (!rs->remote_desc
10902       || packet_support (which_packet) == PACKET_DISABLE)
10903     {
10904       *remote_errno = FILEIO_ENOSYS;
10905       return -1;
10906     }
10907
10908   putpkt_binary (rs->buf, command_bytes);
10909   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10910
10911   /* If it timed out, something is wrong.  Don't try to parse the
10912      buffer.  */
10913   if (bytes_read < 0)
10914     {
10915       *remote_errno = FILEIO_EINVAL;
10916       return -1;
10917     }
10918
10919   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10920     {
10921     case PACKET_ERROR:
10922       *remote_errno = FILEIO_EINVAL;
10923       return -1;
10924     case PACKET_UNKNOWN:
10925       *remote_errno = FILEIO_ENOSYS;
10926       return -1;
10927     case PACKET_OK:
10928       break;
10929     }
10930
10931   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10932                                   &attachment_tmp))
10933     {
10934       *remote_errno = FILEIO_EINVAL;
10935       return -1;
10936     }
10937
10938   /* Make sure we saw an attachment if and only if we expected one.  */
10939   if ((attachment_tmp == NULL && attachment != NULL)
10940       || (attachment_tmp != NULL && attachment == NULL))
10941     {
10942       *remote_errno = FILEIO_EINVAL;
10943       return -1;
10944     }
10945
10946   /* If an attachment was found, it must point into the packet buffer;
10947      work out how many bytes there were.  */
10948   if (attachment_tmp != NULL)
10949     {
10950       *attachment = attachment_tmp;
10951       *attachment_len = bytes_read - (*attachment - rs->buf);
10952     }
10953
10954   return ret;
10955 }
10956
10957 /* Invalidate the readahead cache.  */
10958
10959 static void
10960 readahead_cache_invalidate (void)
10961 {
10962   struct remote_state *rs = get_remote_state ();
10963
10964   rs->readahead_cache.fd = -1;
10965 }
10966
10967 /* Invalidate the readahead cache if it is holding data for FD.  */
10968
10969 static void
10970 readahead_cache_invalidate_fd (int fd)
10971 {
10972   struct remote_state *rs = get_remote_state ();
10973
10974   if (rs->readahead_cache.fd == fd)
10975     rs->readahead_cache.fd = -1;
10976 }
10977
10978 /* Set the filesystem remote_hostio functions that take FILENAME
10979    arguments will use.  Return 0 on success, or -1 if an error
10980    occurs (and set *REMOTE_ERRNO).  */
10981
10982 static int
10983 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10984 {
10985   struct remote_state *rs = get_remote_state ();
10986   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10987   char *p = rs->buf;
10988   int left = get_remote_packet_size () - 1;
10989   char arg[9];
10990   int ret;
10991
10992   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10993     return 0;
10994
10995   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10996     return 0;
10997
10998   remote_buffer_add_string (&p, &left, "vFile:setfs:");
10999
11000   xsnprintf (arg, sizeof (arg), "%x", required_pid);
11001   remote_buffer_add_string (&p, &left, arg);
11002
11003   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11004                                     remote_errno, NULL, NULL);
11005
11006   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11007     return 0;
11008
11009   if (ret == 0)
11010     rs->fs_pid = required_pid;
11011
11012   return ret;
11013 }
11014
11015 /* Implementation of to_fileio_open.  */
11016
11017 static int
11018 remote_hostio_open (struct target_ops *self,
11019                     struct inferior *inf, const char *filename,
11020                     int flags, int mode, int warn_if_slow,
11021                     int *remote_errno)
11022 {
11023   struct remote_state *rs = get_remote_state ();
11024   char *p = rs->buf;
11025   int left = get_remote_packet_size () - 1;
11026
11027   if (warn_if_slow)
11028     {
11029       static int warning_issued = 0;
11030
11031       printf_unfiltered (_("Reading %s from remote target...\n"),
11032                          filename);
11033
11034       if (!warning_issued)
11035         {
11036           warning (_("File transfers from remote targets can be slow."
11037                      " Use \"set sysroot\" to access files locally"
11038                      " instead."));
11039           warning_issued = 1;
11040         }
11041     }
11042
11043   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11044     return -1;
11045
11046   remote_buffer_add_string (&p, &left, "vFile:open:");
11047
11048   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11049                            strlen (filename));
11050   remote_buffer_add_string (&p, &left, ",");
11051
11052   remote_buffer_add_int (&p, &left, flags);
11053   remote_buffer_add_string (&p, &left, ",");
11054
11055   remote_buffer_add_int (&p, &left, mode);
11056
11057   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11058                                      remote_errno, NULL, NULL);
11059 }
11060
11061 /* Implementation of to_fileio_pwrite.  */
11062
11063 static int
11064 remote_hostio_pwrite (struct target_ops *self,
11065                       int fd, const gdb_byte *write_buf, int len,
11066                       ULONGEST offset, int *remote_errno)
11067 {
11068   struct remote_state *rs = get_remote_state ();
11069   char *p = rs->buf;
11070   int left = get_remote_packet_size ();
11071   int out_len;
11072
11073   readahead_cache_invalidate_fd (fd);
11074
11075   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11076
11077   remote_buffer_add_int (&p, &left, fd);
11078   remote_buffer_add_string (&p, &left, ",");
11079
11080   remote_buffer_add_int (&p, &left, offset);
11081   remote_buffer_add_string (&p, &left, ",");
11082
11083   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11084                              get_remote_packet_size () - (p - rs->buf));
11085
11086   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11087                                      remote_errno, NULL, NULL);
11088 }
11089
11090 /* Helper for the implementation of to_fileio_pread.  Read the file
11091    from the remote side with vFile:pread.  */
11092
11093 static int
11094 remote_hostio_pread_vFile (struct target_ops *self,
11095                            int fd, gdb_byte *read_buf, int len,
11096                            ULONGEST offset, int *remote_errno)
11097 {
11098   struct remote_state *rs = get_remote_state ();
11099   char *p = rs->buf;
11100   char *attachment;
11101   int left = get_remote_packet_size ();
11102   int ret, attachment_len;
11103   int read_len;
11104
11105   remote_buffer_add_string (&p, &left, "vFile:pread:");
11106
11107   remote_buffer_add_int (&p, &left, fd);
11108   remote_buffer_add_string (&p, &left, ",");
11109
11110   remote_buffer_add_int (&p, &left, len);
11111   remote_buffer_add_string (&p, &left, ",");
11112
11113   remote_buffer_add_int (&p, &left, offset);
11114
11115   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11116                                     remote_errno, &attachment,
11117                                     &attachment_len);
11118
11119   if (ret < 0)
11120     return ret;
11121
11122   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11123                                     read_buf, len);
11124   if (read_len != ret)
11125     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11126
11127   return ret;
11128 }
11129
11130 /* Serve pread from the readahead cache.  Returns number of bytes
11131    read, or 0 if the request can't be served from the cache.  */
11132
11133 static int
11134 remote_hostio_pread_from_cache (struct remote_state *rs,
11135                                 int fd, gdb_byte *read_buf, size_t len,
11136                                 ULONGEST offset)
11137 {
11138   struct readahead_cache *cache = &rs->readahead_cache;
11139
11140   if (cache->fd == fd
11141       && cache->offset <= offset
11142       && offset < cache->offset + cache->bufsize)
11143     {
11144       ULONGEST max = cache->offset + cache->bufsize;
11145
11146       if (offset + len > max)
11147         len = max - offset;
11148
11149       memcpy (read_buf, cache->buf + offset - cache->offset, len);
11150       return len;
11151     }
11152
11153   return 0;
11154 }
11155
11156 /* Implementation of to_fileio_pread.  */
11157
11158 static int
11159 remote_hostio_pread (struct target_ops *self,
11160                      int fd, gdb_byte *read_buf, int len,
11161                      ULONGEST offset, int *remote_errno)
11162 {
11163   int ret;
11164   struct remote_state *rs = get_remote_state ();
11165   struct readahead_cache *cache = &rs->readahead_cache;
11166
11167   ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11168   if (ret > 0)
11169     {
11170       cache->hit_count++;
11171
11172       if (remote_debug)
11173         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11174                             pulongest (cache->hit_count));
11175       return ret;
11176     }
11177
11178   cache->miss_count++;
11179   if (remote_debug)
11180     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11181                         pulongest (cache->miss_count));
11182
11183   cache->fd = fd;
11184   cache->offset = offset;
11185   cache->bufsize = get_remote_packet_size ();
11186   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11187
11188   ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11189                                    cache->offset, remote_errno);
11190   if (ret <= 0)
11191     {
11192       readahead_cache_invalidate_fd (fd);
11193       return ret;
11194     }
11195
11196   cache->bufsize = ret;
11197   return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11198 }
11199
11200 /* Implementation of to_fileio_close.  */
11201
11202 static int
11203 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11204 {
11205   struct remote_state *rs = get_remote_state ();
11206   char *p = rs->buf;
11207   int left = get_remote_packet_size () - 1;
11208
11209   readahead_cache_invalidate_fd (fd);
11210
11211   remote_buffer_add_string (&p, &left, "vFile:close:");
11212
11213   remote_buffer_add_int (&p, &left, fd);
11214
11215   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11216                                      remote_errno, NULL, NULL);
11217 }
11218
11219 /* Implementation of to_fileio_unlink.  */
11220
11221 static int
11222 remote_hostio_unlink (struct target_ops *self,
11223                       struct inferior *inf, const char *filename,
11224                       int *remote_errno)
11225 {
11226   struct remote_state *rs = get_remote_state ();
11227   char *p = rs->buf;
11228   int left = get_remote_packet_size () - 1;
11229
11230   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11231     return -1;
11232
11233   remote_buffer_add_string (&p, &left, "vFile:unlink:");
11234
11235   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11236                            strlen (filename));
11237
11238   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11239                                      remote_errno, NULL, NULL);
11240 }
11241
11242 /* Implementation of to_fileio_readlink.  */
11243
11244 static char *
11245 remote_hostio_readlink (struct target_ops *self,
11246                         struct inferior *inf, const char *filename,
11247                         int *remote_errno)
11248 {
11249   struct remote_state *rs = get_remote_state ();
11250   char *p = rs->buf;
11251   char *attachment;
11252   int left = get_remote_packet_size ();
11253   int len, attachment_len;
11254   int read_len;
11255   char *ret;
11256
11257   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11258     return NULL;
11259
11260   remote_buffer_add_string (&p, &left, "vFile:readlink:");
11261
11262   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11263                            strlen (filename));
11264
11265   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11266                                     remote_errno, &attachment,
11267                                     &attachment_len);
11268
11269   if (len < 0)
11270     return NULL;
11271
11272   ret = (char *) xmalloc (len + 1);
11273
11274   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11275                                     (gdb_byte *) ret, len);
11276   if (read_len != len)
11277     error (_("Readlink returned %d, but %d bytes."), len, read_len);
11278
11279   ret[len] = '\0';
11280   return ret;
11281 }
11282
11283 /* Implementation of to_fileio_fstat.  */
11284
11285 static int
11286 remote_hostio_fstat (struct target_ops *self,
11287                      int fd, struct stat *st,
11288                      int *remote_errno)
11289 {
11290   struct remote_state *rs = get_remote_state ();
11291   char *p = rs->buf;
11292   int left = get_remote_packet_size ();
11293   int attachment_len, ret;
11294   char *attachment;
11295   struct fio_stat fst;
11296   int read_len;
11297
11298   remote_buffer_add_string (&p, &left, "vFile:fstat:");
11299
11300   remote_buffer_add_int (&p, &left, fd);
11301
11302   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11303                                     remote_errno, &attachment,
11304                                     &attachment_len);
11305   if (ret < 0)
11306     {
11307       if (*remote_errno != FILEIO_ENOSYS)
11308         return ret;
11309
11310       /* Strictly we should return -1, ENOSYS here, but when
11311          "set sysroot remote:" was implemented in August 2008
11312          BFD's need for a stat function was sidestepped with
11313          this hack.  This was not remedied until March 2015
11314          so we retain the previous behavior to avoid breaking
11315          compatibility.
11316
11317          Note that the memset is a March 2015 addition; older
11318          GDBs set st_size *and nothing else* so the structure
11319          would have garbage in all other fields.  This might
11320          break something but retaining the previous behavior
11321          here would be just too wrong.  */
11322
11323       memset (st, 0, sizeof (struct stat));
11324       st->st_size = INT_MAX;
11325       return 0;
11326     }
11327
11328   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11329                                     (gdb_byte *) &fst, sizeof (fst));
11330
11331   if (read_len != ret)
11332     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11333
11334   if (read_len != sizeof (fst))
11335     error (_("vFile:fstat returned %d bytes, but expecting %d."),
11336            read_len, (int) sizeof (fst));
11337
11338   remote_fileio_to_host_stat (&fst, st);
11339
11340   return 0;
11341 }
11342
11343 /* Implementation of to_filesystem_is_local.  */
11344
11345 static int
11346 remote_filesystem_is_local (struct target_ops *self)
11347 {
11348   /* Valgrind GDB presents itself as a remote target but works
11349      on the local filesystem: it does not implement remote get
11350      and users are not expected to set a sysroot.  To handle
11351      this case we treat the remote filesystem as local if the
11352      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11353      does not support vFile:open.  */
11354   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11355     {
11356       enum packet_support ps = packet_support (PACKET_vFile_open);
11357
11358       if (ps == PACKET_SUPPORT_UNKNOWN)
11359         {
11360           int fd, remote_errno;
11361
11362           /* Try opening a file to probe support.  The supplied
11363              filename is irrelevant, we only care about whether
11364              the stub recognizes the packet or not.  */
11365           fd = remote_hostio_open (self, NULL, "just probing",
11366                                    FILEIO_O_RDONLY, 0700, 0,
11367                                    &remote_errno);
11368
11369           if (fd >= 0)
11370             remote_hostio_close (self, fd, &remote_errno);
11371
11372           ps = packet_support (PACKET_vFile_open);
11373         }
11374
11375       if (ps == PACKET_DISABLE)
11376         {
11377           static int warning_issued = 0;
11378
11379           if (!warning_issued)
11380             {
11381               warning (_("remote target does not support file"
11382                          " transfer, attempting to access files"
11383                          " from local filesystem."));
11384               warning_issued = 1;
11385             }
11386
11387           return 1;
11388         }
11389     }
11390
11391   return 0;
11392 }
11393
11394 static int
11395 remote_fileio_errno_to_host (int errnum)
11396 {
11397   switch (errnum)
11398     {
11399       case FILEIO_EPERM:
11400         return EPERM;
11401       case FILEIO_ENOENT:
11402         return ENOENT;
11403       case FILEIO_EINTR:
11404         return EINTR;
11405       case FILEIO_EIO:
11406         return EIO;
11407       case FILEIO_EBADF:
11408         return EBADF;
11409       case FILEIO_EACCES:
11410         return EACCES;
11411       case FILEIO_EFAULT:
11412         return EFAULT;
11413       case FILEIO_EBUSY:
11414         return EBUSY;
11415       case FILEIO_EEXIST:
11416         return EEXIST;
11417       case FILEIO_ENODEV:
11418         return ENODEV;
11419       case FILEIO_ENOTDIR:
11420         return ENOTDIR;
11421       case FILEIO_EISDIR:
11422         return EISDIR;
11423       case FILEIO_EINVAL:
11424         return EINVAL;
11425       case FILEIO_ENFILE:
11426         return ENFILE;
11427       case FILEIO_EMFILE:
11428         return EMFILE;
11429       case FILEIO_EFBIG:
11430         return EFBIG;
11431       case FILEIO_ENOSPC:
11432         return ENOSPC;
11433       case FILEIO_ESPIPE:
11434         return ESPIPE;
11435       case FILEIO_EROFS:
11436         return EROFS;
11437       case FILEIO_ENOSYS:
11438         return ENOSYS;
11439       case FILEIO_ENAMETOOLONG:
11440         return ENAMETOOLONG;
11441     }
11442   return -1;
11443 }
11444
11445 static char *
11446 remote_hostio_error (int errnum)
11447 {
11448   int host_error = remote_fileio_errno_to_host (errnum);
11449
11450   if (host_error == -1)
11451     error (_("Unknown remote I/O error %d"), errnum);
11452   else
11453     error (_("Remote I/O error: %s"), safe_strerror (host_error));
11454 }
11455
11456 static void
11457 remote_hostio_close_cleanup (void *opaque)
11458 {
11459   int fd = *(int *) opaque;
11460   int remote_errno;
11461
11462   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11463 }
11464
11465 void
11466 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11467 {
11468   struct cleanup *back_to, *close_cleanup;
11469   int retcode, fd, remote_errno, bytes, io_size;
11470   FILE *file;
11471   gdb_byte *buffer;
11472   int bytes_in_buffer;
11473   int saw_eof;
11474   ULONGEST offset;
11475   struct remote_state *rs = get_remote_state ();
11476
11477   if (!rs->remote_desc)
11478     error (_("command can only be used with remote target"));
11479
11480   file = gdb_fopen_cloexec (local_file, "rb");
11481   if (file == NULL)
11482     perror_with_name (local_file);
11483   back_to = make_cleanup_fclose (file);
11484
11485   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11486                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11487                                          | FILEIO_O_TRUNC),
11488                            0700, 0, &remote_errno);
11489   if (fd == -1)
11490     remote_hostio_error (remote_errno);
11491
11492   /* Send up to this many bytes at once.  They won't all fit in the
11493      remote packet limit, so we'll transfer slightly fewer.  */
11494   io_size = get_remote_packet_size ();
11495   buffer = (gdb_byte *) xmalloc (io_size);
11496   make_cleanup (xfree, buffer);
11497
11498   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11499
11500   bytes_in_buffer = 0;
11501   saw_eof = 0;
11502   offset = 0;
11503   while (bytes_in_buffer || !saw_eof)
11504     {
11505       if (!saw_eof)
11506         {
11507           bytes = fread (buffer + bytes_in_buffer, 1,
11508                          io_size - bytes_in_buffer,
11509                          file);
11510           if (bytes == 0)
11511             {
11512               if (ferror (file))
11513                 error (_("Error reading %s."), local_file);
11514               else
11515                 {
11516                   /* EOF.  Unless there is something still in the
11517                      buffer from the last iteration, we are done.  */
11518                   saw_eof = 1;
11519                   if (bytes_in_buffer == 0)
11520                     break;
11521                 }
11522             }
11523         }
11524       else
11525         bytes = 0;
11526
11527       bytes += bytes_in_buffer;
11528       bytes_in_buffer = 0;
11529
11530       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11531                                       fd, buffer, bytes,
11532                                       offset, &remote_errno);
11533
11534       if (retcode < 0)
11535         remote_hostio_error (remote_errno);
11536       else if (retcode == 0)
11537         error (_("Remote write of %d bytes returned 0!"), bytes);
11538       else if (retcode < bytes)
11539         {
11540           /* Short write.  Save the rest of the read data for the next
11541              write.  */
11542           bytes_in_buffer = bytes - retcode;
11543           memmove (buffer, buffer + retcode, bytes_in_buffer);
11544         }
11545
11546       offset += retcode;
11547     }
11548
11549   discard_cleanups (close_cleanup);
11550   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11551     remote_hostio_error (remote_errno);
11552
11553   if (from_tty)
11554     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11555   do_cleanups (back_to);
11556 }
11557
11558 void
11559 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11560 {
11561   struct cleanup *back_to, *close_cleanup;
11562   int fd, remote_errno, bytes, io_size;
11563   FILE *file;
11564   gdb_byte *buffer;
11565   ULONGEST offset;
11566   struct remote_state *rs = get_remote_state ();
11567
11568   if (!rs->remote_desc)
11569     error (_("command can only be used with remote target"));
11570
11571   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11572                            remote_file, FILEIO_O_RDONLY, 0, 0,
11573                            &remote_errno);
11574   if (fd == -1)
11575     remote_hostio_error (remote_errno);
11576
11577   file = gdb_fopen_cloexec (local_file, "wb");
11578   if (file == NULL)
11579     perror_with_name (local_file);
11580   back_to = make_cleanup_fclose (file);
11581
11582   /* Send up to this many bytes at once.  They won't all fit in the
11583      remote packet limit, so we'll transfer slightly fewer.  */
11584   io_size = get_remote_packet_size ();
11585   buffer = (gdb_byte *) xmalloc (io_size);
11586   make_cleanup (xfree, buffer);
11587
11588   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11589
11590   offset = 0;
11591   while (1)
11592     {
11593       bytes = remote_hostio_pread (find_target_at (process_stratum),
11594                                    fd, buffer, io_size, offset, &remote_errno);
11595       if (bytes == 0)
11596         /* Success, but no bytes, means end-of-file.  */
11597         break;
11598       if (bytes == -1)
11599         remote_hostio_error (remote_errno);
11600
11601       offset += bytes;
11602
11603       bytes = fwrite (buffer, 1, bytes, file);
11604       if (bytes == 0)
11605         perror_with_name (local_file);
11606     }
11607
11608   discard_cleanups (close_cleanup);
11609   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11610     remote_hostio_error (remote_errno);
11611
11612   if (from_tty)
11613     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11614   do_cleanups (back_to);
11615 }
11616
11617 void
11618 remote_file_delete (const char *remote_file, int from_tty)
11619 {
11620   int retcode, remote_errno;
11621   struct remote_state *rs = get_remote_state ();
11622
11623   if (!rs->remote_desc)
11624     error (_("command can only be used with remote target"));
11625
11626   retcode = remote_hostio_unlink (find_target_at (process_stratum),
11627                                   NULL, remote_file, &remote_errno);
11628   if (retcode == -1)
11629     remote_hostio_error (remote_errno);
11630
11631   if (from_tty)
11632     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11633 }
11634
11635 static void
11636 remote_put_command (char *args, int from_tty)
11637 {
11638   struct cleanup *back_to;
11639   char **argv;
11640
11641   if (args == NULL)
11642     error_no_arg (_("file to put"));
11643
11644   argv = gdb_buildargv (args);
11645   back_to = make_cleanup_freeargv (argv);
11646   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11647     error (_("Invalid parameters to remote put"));
11648
11649   remote_file_put (argv[0], argv[1], from_tty);
11650
11651   do_cleanups (back_to);
11652 }
11653
11654 static void
11655 remote_get_command (char *args, int from_tty)
11656 {
11657   struct cleanup *back_to;
11658   char **argv;
11659
11660   if (args == NULL)
11661     error_no_arg (_("file to get"));
11662
11663   argv = gdb_buildargv (args);
11664   back_to = make_cleanup_freeargv (argv);
11665   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11666     error (_("Invalid parameters to remote get"));
11667
11668   remote_file_get (argv[0], argv[1], from_tty);
11669
11670   do_cleanups (back_to);
11671 }
11672
11673 static void
11674 remote_delete_command (char *args, int from_tty)
11675 {
11676   struct cleanup *back_to;
11677   char **argv;
11678
11679   if (args == NULL)
11680     error_no_arg (_("file to delete"));
11681
11682   argv = gdb_buildargv (args);
11683   back_to = make_cleanup_freeargv (argv);
11684   if (argv[0] == NULL || argv[1] != NULL)
11685     error (_("Invalid parameters to remote delete"));
11686
11687   remote_file_delete (argv[0], from_tty);
11688
11689   do_cleanups (back_to);
11690 }
11691
11692 static void
11693 remote_command (char *args, int from_tty)
11694 {
11695   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11696 }
11697
11698 static int
11699 remote_can_execute_reverse (struct target_ops *self)
11700 {
11701   if (packet_support (PACKET_bs) == PACKET_ENABLE
11702       || packet_support (PACKET_bc) == PACKET_ENABLE)
11703     return 1;
11704   else
11705     return 0;
11706 }
11707
11708 static int
11709 remote_supports_non_stop (struct target_ops *self)
11710 {
11711   return 1;
11712 }
11713
11714 static int
11715 remote_supports_disable_randomization (struct target_ops *self)
11716 {
11717   /* Only supported in extended mode.  */
11718   return 0;
11719 }
11720
11721 static int
11722 remote_supports_multi_process (struct target_ops *self)
11723 {
11724   struct remote_state *rs = get_remote_state ();
11725
11726   return remote_multi_process_p (rs);
11727 }
11728
11729 static int
11730 remote_supports_cond_tracepoints (void)
11731 {
11732   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11733 }
11734
11735 static int
11736 remote_supports_cond_breakpoints (struct target_ops *self)
11737 {
11738   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11739 }
11740
11741 static int
11742 remote_supports_fast_tracepoints (void)
11743 {
11744   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11745 }
11746
11747 static int
11748 remote_supports_static_tracepoints (void)
11749 {
11750   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11751 }
11752
11753 static int
11754 remote_supports_install_in_trace (void)
11755 {
11756   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11757 }
11758
11759 static int
11760 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11761 {
11762   return (packet_support (PACKET_EnableDisableTracepoints_feature)
11763           == PACKET_ENABLE);
11764 }
11765
11766 static int
11767 remote_supports_string_tracing (struct target_ops *self)
11768 {
11769   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11770 }
11771
11772 static int
11773 remote_can_run_breakpoint_commands (struct target_ops *self)
11774 {
11775   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11776 }
11777
11778 static void
11779 remote_trace_init (struct target_ops *self)
11780 {
11781   putpkt ("QTinit");
11782   remote_get_noisy_reply (&target_buf, &target_buf_size);
11783   if (strcmp (target_buf, "OK") != 0)
11784     error (_("Target does not support this command."));
11785 }
11786
11787 static void free_actions_list (char **actions_list);
11788 static void free_actions_list_cleanup_wrapper (void *);
11789 static void
11790 free_actions_list_cleanup_wrapper (void *al)
11791 {
11792   free_actions_list ((char **) al);
11793 }
11794
11795 static void
11796 free_actions_list (char **actions_list)
11797 {
11798   int ndx;
11799
11800   if (actions_list == 0)
11801     return;
11802
11803   for (ndx = 0; actions_list[ndx]; ndx++)
11804     xfree (actions_list[ndx]);
11805
11806   xfree (actions_list);
11807 }
11808
11809 /* Recursive routine to walk through command list including loops, and
11810    download packets for each command.  */
11811
11812 static void
11813 remote_download_command_source (int num, ULONGEST addr,
11814                                 struct command_line *cmds)
11815 {
11816   struct remote_state *rs = get_remote_state ();
11817   struct command_line *cmd;
11818
11819   for (cmd = cmds; cmd; cmd = cmd->next)
11820     {
11821       QUIT;     /* Allow user to bail out with ^C.  */
11822       strcpy (rs->buf, "QTDPsrc:");
11823       encode_source_string (num, addr, "cmd", cmd->line,
11824                             rs->buf + strlen (rs->buf),
11825                             rs->buf_size - strlen (rs->buf));
11826       putpkt (rs->buf);
11827       remote_get_noisy_reply (&target_buf, &target_buf_size);
11828       if (strcmp (target_buf, "OK"))
11829         warning (_("Target does not support source download."));
11830
11831       if (cmd->control_type == while_control
11832           || cmd->control_type == while_stepping_control)
11833         {
11834           remote_download_command_source (num, addr, *cmd->body_list);
11835
11836           QUIT; /* Allow user to bail out with ^C.  */
11837           strcpy (rs->buf, "QTDPsrc:");
11838           encode_source_string (num, addr, "cmd", "end",
11839                                 rs->buf + strlen (rs->buf),
11840                                 rs->buf_size - strlen (rs->buf));
11841           putpkt (rs->buf);
11842           remote_get_noisy_reply (&target_buf, &target_buf_size);
11843           if (strcmp (target_buf, "OK"))
11844             warning (_("Target does not support source download."));
11845         }
11846     }
11847 }
11848
11849 static void
11850 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11851 {
11852 #define BUF_SIZE 2048
11853
11854   CORE_ADDR tpaddr;
11855   char addrbuf[40];
11856   char buf[BUF_SIZE];
11857   char **tdp_actions;
11858   char **stepping_actions;
11859   int ndx;
11860   struct cleanup *old_chain = NULL;
11861   struct agent_expr *aexpr;
11862   struct cleanup *aexpr_chain = NULL;
11863   char *pkt;
11864   struct breakpoint *b = loc->owner;
11865   struct tracepoint *t = (struct tracepoint *) b;
11866
11867   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11868   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11869                             tdp_actions);
11870   (void) make_cleanup (free_actions_list_cleanup_wrapper,
11871                        stepping_actions);
11872
11873   tpaddr = loc->address;
11874   sprintf_vma (addrbuf, tpaddr);
11875   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11876              addrbuf, /* address */
11877              (b->enable_state == bp_enabled ? 'E' : 'D'),
11878              t->step_count, t->pass_count);
11879   /* Fast tracepoints are mostly handled by the target, but we can
11880      tell the target how big of an instruction block should be moved
11881      around.  */
11882   if (b->type == bp_fast_tracepoint)
11883     {
11884       /* Only test for support at download time; we may not know
11885          target capabilities at definition time.  */
11886       if (remote_supports_fast_tracepoints ())
11887         {
11888           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11889                                                 NULL))
11890             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11891                        gdb_insn_length (loc->gdbarch, tpaddr));
11892           else
11893             /* If it passed validation at definition but fails now,
11894                something is very wrong.  */
11895             internal_error (__FILE__, __LINE__,
11896                             _("Fast tracepoint not "
11897                               "valid during download"));
11898         }
11899       else
11900         /* Fast tracepoints are functionally identical to regular
11901            tracepoints, so don't take lack of support as a reason to
11902            give up on the trace run.  */
11903         warning (_("Target does not support fast tracepoints, "
11904                    "downloading %d as regular tracepoint"), b->number);
11905     }
11906   else if (b->type == bp_static_tracepoint)
11907     {
11908       /* Only test for support at download time; we may not know
11909          target capabilities at definition time.  */
11910       if (remote_supports_static_tracepoints ())
11911         {
11912           struct static_tracepoint_marker marker;
11913
11914           if (target_static_tracepoint_marker_at (tpaddr, &marker))
11915             strcat (buf, ":S");
11916           else
11917             error (_("Static tracepoint not valid during download"));
11918         }
11919       else
11920         /* Fast tracepoints are functionally identical to regular
11921            tracepoints, so don't take lack of support as a reason
11922            to give up on the trace run.  */
11923         error (_("Target does not support static tracepoints"));
11924     }
11925   /* If the tracepoint has a conditional, make it into an agent
11926      expression and append to the definition.  */
11927   if (loc->cond)
11928     {
11929       /* Only test support at download time, we may not know target
11930          capabilities at definition time.  */
11931       if (remote_supports_cond_tracepoints ())
11932         {
11933           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11934           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11935           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11936                      aexpr->len);
11937           pkt = buf + strlen (buf);
11938           for (ndx = 0; ndx < aexpr->len; ++ndx)
11939             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11940           *pkt = '\0';
11941           do_cleanups (aexpr_chain);
11942         }
11943       else
11944         warning (_("Target does not support conditional tracepoints, "
11945                    "ignoring tp %d cond"), b->number);
11946     }
11947
11948   if (b->commands || *default_collect)
11949     strcat (buf, "-");
11950   putpkt (buf);
11951   remote_get_noisy_reply (&target_buf, &target_buf_size);
11952   if (strcmp (target_buf, "OK"))
11953     error (_("Target does not support tracepoints."));
11954
11955   /* do_single_steps (t); */
11956   if (tdp_actions)
11957     {
11958       for (ndx = 0; tdp_actions[ndx]; ndx++)
11959         {
11960           QUIT; /* Allow user to bail out with ^C.  */
11961           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11962                      b->number, addrbuf, /* address */
11963                      tdp_actions[ndx],
11964                      ((tdp_actions[ndx + 1] || stepping_actions)
11965                       ? '-' : 0));
11966           putpkt (buf);
11967           remote_get_noisy_reply (&target_buf,
11968                                   &target_buf_size);
11969           if (strcmp (target_buf, "OK"))
11970             error (_("Error on target while setting tracepoints."));
11971         }
11972     }
11973   if (stepping_actions)
11974     {
11975       for (ndx = 0; stepping_actions[ndx]; ndx++)
11976         {
11977           QUIT; /* Allow user to bail out with ^C.  */
11978           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11979                      b->number, addrbuf, /* address */
11980                      ((ndx == 0) ? "S" : ""),
11981                      stepping_actions[ndx],
11982                      (stepping_actions[ndx + 1] ? "-" : ""));
11983           putpkt (buf);
11984           remote_get_noisy_reply (&target_buf,
11985                                   &target_buf_size);
11986           if (strcmp (target_buf, "OK"))
11987             error (_("Error on target while setting tracepoints."));
11988         }
11989     }
11990
11991   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11992     {
11993       if (b->location != NULL)
11994         {
11995           strcpy (buf, "QTDPsrc:");
11996           encode_source_string (b->number, loc->address, "at",
11997                                 event_location_to_string (b->location),
11998                                 buf + strlen (buf), 2048 - strlen (buf));
11999           putpkt (buf);
12000           remote_get_noisy_reply (&target_buf, &target_buf_size);
12001           if (strcmp (target_buf, "OK"))
12002             warning (_("Target does not support source download."));
12003         }
12004       if (b->cond_string)
12005         {
12006           strcpy (buf, "QTDPsrc:");
12007           encode_source_string (b->number, loc->address,
12008                                 "cond", b->cond_string, buf + strlen (buf),
12009                                 2048 - strlen (buf));
12010           putpkt (buf);
12011           remote_get_noisy_reply (&target_buf, &target_buf_size);
12012           if (strcmp (target_buf, "OK"))
12013             warning (_("Target does not support source download."));
12014         }
12015       remote_download_command_source (b->number, loc->address,
12016                                       breakpoint_commands (b));
12017     }
12018
12019   do_cleanups (old_chain);
12020 }
12021
12022 static int
12023 remote_can_download_tracepoint (struct target_ops *self)
12024 {
12025   struct remote_state *rs = get_remote_state ();
12026   struct trace_status *ts;
12027   int status;
12028
12029   /* Don't try to install tracepoints until we've relocated our
12030      symbols, and fetched and merged the target's tracepoint list with
12031      ours.  */
12032   if (rs->starting_up)
12033     return 0;
12034
12035   ts = current_trace_status ();
12036   status = remote_get_trace_status (self, ts);
12037
12038   if (status == -1 || !ts->running_known || !ts->running)
12039     return 0;
12040
12041   /* If we are in a tracing experiment, but remote stub doesn't support
12042      installing tracepoint in trace, we have to return.  */
12043   if (!remote_supports_install_in_trace ())
12044     return 0;
12045
12046   return 1;
12047 }
12048
12049
12050 static void
12051 remote_download_trace_state_variable (struct target_ops *self,
12052                                       struct trace_state_variable *tsv)
12053 {
12054   struct remote_state *rs = get_remote_state ();
12055   char *p;
12056
12057   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12058              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12059              tsv->builtin);
12060   p = rs->buf + strlen (rs->buf);
12061   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12062     error (_("Trace state variable name too long for tsv definition packet"));
12063   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12064   *p++ = '\0';
12065   putpkt (rs->buf);
12066   remote_get_noisy_reply (&target_buf, &target_buf_size);
12067   if (*target_buf == '\0')
12068     error (_("Target does not support this command."));
12069   if (strcmp (target_buf, "OK") != 0)
12070     error (_("Error on target while downloading trace state variable."));
12071 }
12072
12073 static void
12074 remote_enable_tracepoint (struct target_ops *self,
12075                           struct bp_location *location)
12076 {
12077   struct remote_state *rs = get_remote_state ();
12078   char addr_buf[40];
12079
12080   sprintf_vma (addr_buf, location->address);
12081   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12082              location->owner->number, addr_buf);
12083   putpkt (rs->buf);
12084   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12085   if (*rs->buf == '\0')
12086     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12087   if (strcmp (rs->buf, "OK") != 0)
12088     error (_("Error on target while enabling tracepoint."));
12089 }
12090
12091 static void
12092 remote_disable_tracepoint (struct target_ops *self,
12093                            struct bp_location *location)
12094 {
12095   struct remote_state *rs = get_remote_state ();
12096   char addr_buf[40];
12097
12098   sprintf_vma (addr_buf, location->address);
12099   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12100              location->owner->number, addr_buf);
12101   putpkt (rs->buf);
12102   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12103   if (*rs->buf == '\0')
12104     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12105   if (strcmp (rs->buf, "OK") != 0)
12106     error (_("Error on target while disabling tracepoint."));
12107 }
12108
12109 static void
12110 remote_trace_set_readonly_regions (struct target_ops *self)
12111 {
12112   asection *s;
12113   bfd *abfd = NULL;
12114   bfd_size_type size;
12115   bfd_vma vma;
12116   int anysecs = 0;
12117   int offset = 0;
12118
12119   if (!exec_bfd)
12120     return;                     /* No information to give.  */
12121
12122   strcpy (target_buf, "QTro");
12123   offset = strlen (target_buf);
12124   for (s = exec_bfd->sections; s; s = s->next)
12125     {
12126       char tmp1[40], tmp2[40];
12127       int sec_length;
12128
12129       if ((s->flags & SEC_LOAD) == 0 ||
12130       /*  (s->flags & SEC_CODE) == 0 || */
12131           (s->flags & SEC_READONLY) == 0)
12132         continue;
12133
12134       anysecs = 1;
12135       vma = bfd_get_section_vma (abfd, s);
12136       size = bfd_get_section_size (s);
12137       sprintf_vma (tmp1, vma);
12138       sprintf_vma (tmp2, vma + size);
12139       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12140       if (offset + sec_length + 1 > target_buf_size)
12141         {
12142           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12143             warning (_("\
12144 Too many sections for read-only sections definition packet."));
12145           break;
12146         }
12147       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12148                  tmp1, tmp2);
12149       offset += sec_length;
12150     }
12151   if (anysecs)
12152     {
12153       putpkt (target_buf);
12154       getpkt (&target_buf, &target_buf_size, 0);
12155     }
12156 }
12157
12158 static void
12159 remote_trace_start (struct target_ops *self)
12160 {
12161   putpkt ("QTStart");
12162   remote_get_noisy_reply (&target_buf, &target_buf_size);
12163   if (*target_buf == '\0')
12164     error (_("Target does not support this command."));
12165   if (strcmp (target_buf, "OK") != 0)
12166     error (_("Bogus reply from target: %s"), target_buf);
12167 }
12168
12169 static int
12170 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12171 {
12172   /* Initialize it just to avoid a GCC false warning.  */
12173   char *p = NULL;
12174   /* FIXME we need to get register block size some other way.  */
12175   extern int trace_regblock_size;
12176   enum packet_result result;
12177
12178   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12179     return -1;
12180
12181   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12182
12183   putpkt ("qTStatus");
12184
12185   TRY
12186     {
12187       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12188     }
12189   CATCH (ex, RETURN_MASK_ERROR)
12190     {
12191       if (ex.error != TARGET_CLOSE_ERROR)
12192         {
12193           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12194           return -1;
12195         }
12196       throw_exception (ex);
12197     }
12198   END_CATCH
12199
12200   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12201
12202   /* If the remote target doesn't do tracing, flag it.  */
12203   if (result == PACKET_UNKNOWN)
12204     return -1;
12205
12206   /* We're working with a live target.  */
12207   ts->filename = NULL;
12208
12209   if (*p++ != 'T')
12210     error (_("Bogus trace status reply from target: %s"), target_buf);
12211
12212   /* Function 'parse_trace_status' sets default value of each field of
12213      'ts' at first, so we don't have to do it here.  */
12214   parse_trace_status (p, ts);
12215
12216   return ts->running;
12217 }
12218
12219 static void
12220 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12221                               struct uploaded_tp *utp)
12222 {
12223   struct remote_state *rs = get_remote_state ();
12224   char *reply;
12225   struct bp_location *loc;
12226   struct tracepoint *tp = (struct tracepoint *) bp;
12227   size_t size = get_remote_packet_size ();
12228
12229   if (tp)
12230     {
12231       tp->base.hit_count = 0;
12232       tp->traceframe_usage = 0;
12233       for (loc = tp->base.loc; loc; loc = loc->next)
12234         {
12235           /* If the tracepoint was never downloaded, don't go asking for
12236              any status.  */
12237           if (tp->number_on_target == 0)
12238             continue;
12239           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12240                      phex_nz (loc->address, 0));
12241           putpkt (rs->buf);
12242           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12243           if (reply && *reply)
12244             {
12245               if (*reply == 'V')
12246                 parse_tracepoint_status (reply + 1, bp, utp);
12247             }
12248         }
12249     }
12250   else if (utp)
12251     {
12252       utp->hit_count = 0;
12253       utp->traceframe_usage = 0;
12254       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12255                  phex_nz (utp->addr, 0));
12256       putpkt (rs->buf);
12257       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12258       if (reply && *reply)
12259         {
12260           if (*reply == 'V')
12261             parse_tracepoint_status (reply + 1, bp, utp);
12262         }
12263     }
12264 }
12265
12266 static void
12267 remote_trace_stop (struct target_ops *self)
12268 {
12269   putpkt ("QTStop");
12270   remote_get_noisy_reply (&target_buf, &target_buf_size);
12271   if (*target_buf == '\0')
12272     error (_("Target does not support this command."));
12273   if (strcmp (target_buf, "OK") != 0)
12274     error (_("Bogus reply from target: %s"), target_buf);
12275 }
12276
12277 static int
12278 remote_trace_find (struct target_ops *self,
12279                    enum trace_find_type type, int num,
12280                    CORE_ADDR addr1, CORE_ADDR addr2,
12281                    int *tpp)
12282 {
12283   struct remote_state *rs = get_remote_state ();
12284   char *endbuf = rs->buf + get_remote_packet_size ();
12285   char *p, *reply;
12286   int target_frameno = -1, target_tracept = -1;
12287
12288   /* Lookups other than by absolute frame number depend on the current
12289      trace selected, so make sure it is correct on the remote end
12290      first.  */
12291   if (type != tfind_number)
12292     set_remote_traceframe ();
12293
12294   p = rs->buf;
12295   strcpy (p, "QTFrame:");
12296   p = strchr (p, '\0');
12297   switch (type)
12298     {
12299     case tfind_number:
12300       xsnprintf (p, endbuf - p, "%x", num);
12301       break;
12302     case tfind_pc:
12303       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12304       break;
12305     case tfind_tp:
12306       xsnprintf (p, endbuf - p, "tdp:%x", num);
12307       break;
12308     case tfind_range:
12309       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12310                  phex_nz (addr2, 0));
12311       break;
12312     case tfind_outside:
12313       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12314                  phex_nz (addr2, 0));
12315       break;
12316     default:
12317       error (_("Unknown trace find type %d"), type);
12318     }
12319
12320   putpkt (rs->buf);
12321   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12322   if (*reply == '\0')
12323     error (_("Target does not support this command."));
12324
12325   while (reply && *reply)
12326     switch (*reply)
12327       {
12328       case 'F':
12329         p = ++reply;
12330         target_frameno = (int) strtol (p, &reply, 16);
12331         if (reply == p)
12332           error (_("Unable to parse trace frame number"));
12333         /* Don't update our remote traceframe number cache on failure
12334            to select a remote traceframe.  */
12335         if (target_frameno == -1)
12336           return -1;
12337         break;
12338       case 'T':
12339         p = ++reply;
12340         target_tracept = (int) strtol (p, &reply, 16);
12341         if (reply == p)
12342           error (_("Unable to parse tracepoint number"));
12343         break;
12344       case 'O':         /* "OK"? */
12345         if (reply[1] == 'K' && reply[2] == '\0')
12346           reply += 2;
12347         else
12348           error (_("Bogus reply from target: %s"), reply);
12349         break;
12350       default:
12351         error (_("Bogus reply from target: %s"), reply);
12352       }
12353   if (tpp)
12354     *tpp = target_tracept;
12355
12356   rs->remote_traceframe_number = target_frameno;
12357   return target_frameno;
12358 }
12359
12360 static int
12361 remote_get_trace_state_variable_value (struct target_ops *self,
12362                                        int tsvnum, LONGEST *val)
12363 {
12364   struct remote_state *rs = get_remote_state ();
12365   char *reply;
12366   ULONGEST uval;
12367
12368   set_remote_traceframe ();
12369
12370   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12371   putpkt (rs->buf);
12372   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12373   if (reply && *reply)
12374     {
12375       if (*reply == 'V')
12376         {
12377           unpack_varlen_hex (reply + 1, &uval);
12378           *val = (LONGEST) uval;
12379           return 1;
12380         }
12381     }
12382   return 0;
12383 }
12384
12385 static int
12386 remote_save_trace_data (struct target_ops *self, const char *filename)
12387 {
12388   struct remote_state *rs = get_remote_state ();
12389   char *p, *reply;
12390
12391   p = rs->buf;
12392   strcpy (p, "QTSave:");
12393   p += strlen (p);
12394   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12395     error (_("Remote file name too long for trace save packet"));
12396   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12397   *p++ = '\0';
12398   putpkt (rs->buf);
12399   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12400   if (*reply == '\0')
12401     error (_("Target does not support this command."));
12402   if (strcmp (reply, "OK") != 0)
12403     error (_("Bogus reply from target: %s"), reply);
12404   return 0;
12405 }
12406
12407 /* This is basically a memory transfer, but needs to be its own packet
12408    because we don't know how the target actually organizes its trace
12409    memory, plus we want to be able to ask for as much as possible, but
12410    not be unhappy if we don't get as much as we ask for.  */
12411
12412 static LONGEST
12413 remote_get_raw_trace_data (struct target_ops *self,
12414                            gdb_byte *buf, ULONGEST offset, LONGEST len)
12415 {
12416   struct remote_state *rs = get_remote_state ();
12417   char *reply;
12418   char *p;
12419   int rslt;
12420
12421   p = rs->buf;
12422   strcpy (p, "qTBuffer:");
12423   p += strlen (p);
12424   p += hexnumstr (p, offset);
12425   *p++ = ',';
12426   p += hexnumstr (p, len);
12427   *p++ = '\0';
12428
12429   putpkt (rs->buf);
12430   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12431   if (reply && *reply)
12432     {
12433       /* 'l' by itself means we're at the end of the buffer and
12434          there is nothing more to get.  */
12435       if (*reply == 'l')
12436         return 0;
12437
12438       /* Convert the reply into binary.  Limit the number of bytes to
12439          convert according to our passed-in buffer size, rather than
12440          what was returned in the packet; if the target is
12441          unexpectedly generous and gives us a bigger reply than we
12442          asked for, we don't want to crash.  */
12443       rslt = hex2bin (target_buf, buf, len);
12444       return rslt;
12445     }
12446
12447   /* Something went wrong, flag as an error.  */
12448   return -1;
12449 }
12450
12451 static void
12452 remote_set_disconnected_tracing (struct target_ops *self, int val)
12453 {
12454   struct remote_state *rs = get_remote_state ();
12455
12456   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12457     {
12458       char *reply;
12459
12460       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12461       putpkt (rs->buf);
12462       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12463       if (*reply == '\0')
12464         error (_("Target does not support this command."));
12465       if (strcmp (reply, "OK") != 0)
12466         error (_("Bogus reply from target: %s"), reply);
12467     }
12468   else if (val)
12469     warning (_("Target does not support disconnected tracing."));
12470 }
12471
12472 static int
12473 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12474 {
12475   struct thread_info *info = find_thread_ptid (ptid);
12476
12477   if (info && info->priv)
12478     return info->priv->core;
12479   return -1;
12480 }
12481
12482 static void
12483 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12484 {
12485   struct remote_state *rs = get_remote_state ();
12486   char *reply;
12487
12488   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12489   putpkt (rs->buf);
12490   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12491   if (*reply == '\0')
12492     error (_("Target does not support this command."));
12493   if (strcmp (reply, "OK") != 0)
12494     error (_("Bogus reply from target: %s"), reply);
12495 }
12496
12497 static struct traceframe_info *
12498 remote_traceframe_info (struct target_ops *self)
12499 {
12500   char *text;
12501
12502   text = target_read_stralloc (&current_target,
12503                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12504   if (text != NULL)
12505     {
12506       struct traceframe_info *info;
12507       struct cleanup *back_to = make_cleanup (xfree, text);
12508
12509       info = parse_traceframe_info (text);
12510       do_cleanups (back_to);
12511       return info;
12512     }
12513
12514   return NULL;
12515 }
12516
12517 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
12518    instruction on which a fast tracepoint may be placed.  Returns -1
12519    if the packet is not supported, and 0 if the minimum instruction
12520    length is unknown.  */
12521
12522 static int
12523 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12524 {
12525   struct remote_state *rs = get_remote_state ();
12526   char *reply;
12527
12528   /* If we're not debugging a process yet, the IPA can't be
12529      loaded.  */
12530   if (!target_has_execution)
12531     return 0;
12532
12533   /* Make sure the remote is pointing at the right process.  */
12534   set_general_process ();
12535
12536   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12537   putpkt (rs->buf);
12538   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12539   if (*reply == '\0')
12540     return -1;
12541   else
12542     {
12543       ULONGEST min_insn_len;
12544
12545       unpack_varlen_hex (reply, &min_insn_len);
12546
12547       return (int) min_insn_len;
12548     }
12549 }
12550
12551 static void
12552 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12553 {
12554   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12555     {
12556       struct remote_state *rs = get_remote_state ();
12557       char *buf = rs->buf;
12558       char *endbuf = rs->buf + get_remote_packet_size ();
12559       enum packet_result result;
12560
12561       gdb_assert (val >= 0 || val == -1);
12562       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12563       /* Send -1 as literal "-1" to avoid host size dependency.  */
12564       if (val < 0)
12565         {
12566           *buf++ = '-';
12567           buf += hexnumstr (buf, (ULONGEST) -val);
12568         }
12569       else
12570         buf += hexnumstr (buf, (ULONGEST) val);
12571
12572       putpkt (rs->buf);
12573       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12574       result = packet_ok (rs->buf,
12575                   &remote_protocol_packets[PACKET_QTBuffer_size]);
12576
12577       if (result != PACKET_OK)
12578         warning (_("Bogus reply from target: %s"), rs->buf);
12579     }
12580 }
12581
12582 static int
12583 remote_set_trace_notes (struct target_ops *self,
12584                         const char *user, const char *notes,
12585                         const char *stop_notes)
12586 {
12587   struct remote_state *rs = get_remote_state ();
12588   char *reply;
12589   char *buf = rs->buf;
12590   char *endbuf = rs->buf + get_remote_packet_size ();
12591   int nbytes;
12592
12593   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12594   if (user)
12595     {
12596       buf += xsnprintf (buf, endbuf - buf, "user:");
12597       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12598       buf += 2 * nbytes;
12599       *buf++ = ';';
12600     }
12601   if (notes)
12602     {
12603       buf += xsnprintf (buf, endbuf - buf, "notes:");
12604       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12605       buf += 2 * nbytes;
12606       *buf++ = ';';
12607     }
12608   if (stop_notes)
12609     {
12610       buf += xsnprintf (buf, endbuf - buf, "tstop:");
12611       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12612       buf += 2 * nbytes;
12613       *buf++ = ';';
12614     }
12615   /* Ensure the buffer is terminated.  */
12616   *buf = '\0';
12617
12618   putpkt (rs->buf);
12619   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12620   if (*reply == '\0')
12621     return 0;
12622
12623   if (strcmp (reply, "OK") != 0)
12624     error (_("Bogus reply from target: %s"), reply);
12625
12626   return 1;
12627 }
12628
12629 static int
12630 remote_use_agent (struct target_ops *self, int use)
12631 {
12632   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12633     {
12634       struct remote_state *rs = get_remote_state ();
12635
12636       /* If the stub supports QAgent.  */
12637       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12638       putpkt (rs->buf);
12639       getpkt (&rs->buf, &rs->buf_size, 0);
12640
12641       if (strcmp (rs->buf, "OK") == 0)
12642         {
12643           use_agent = use;
12644           return 1;
12645         }
12646     }
12647
12648   return 0;
12649 }
12650
12651 static int
12652 remote_can_use_agent (struct target_ops *self)
12653 {
12654   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12655 }
12656
12657 struct btrace_target_info
12658 {
12659   /* The ptid of the traced thread.  */
12660   ptid_t ptid;
12661
12662   /* The obtained branch trace configuration.  */
12663   struct btrace_config conf;
12664 };
12665
12666 /* Reset our idea of our target's btrace configuration.  */
12667
12668 static void
12669 remote_btrace_reset (void)
12670 {
12671   struct remote_state *rs = get_remote_state ();
12672
12673   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12674 }
12675
12676 /* Check whether the target supports branch tracing.  */
12677
12678 static int
12679 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12680 {
12681   if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12682     return 0;
12683   if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12684     return 0;
12685
12686   switch (format)
12687     {
12688       case BTRACE_FORMAT_NONE:
12689         return 0;
12690
12691       case BTRACE_FORMAT_BTS:
12692         return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12693
12694       case BTRACE_FORMAT_PT:
12695         /* The trace is decoded on the host.  Even if our target supports it,
12696            we still need to have libipt to decode the trace.  */
12697 #if defined (HAVE_LIBIPT)
12698         return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12699 #else /* !defined (HAVE_LIBIPT)  */
12700         return 0;
12701 #endif /* !defined (HAVE_LIBIPT)  */
12702     }
12703
12704   internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12705 }
12706
12707 /* Synchronize the configuration with the target.  */
12708
12709 static void
12710 btrace_sync_conf (const struct btrace_config *conf)
12711 {
12712   struct packet_config *packet;
12713   struct remote_state *rs;
12714   char *buf, *pos, *endbuf;
12715
12716   rs = get_remote_state ();
12717   buf = rs->buf;
12718   endbuf = buf + get_remote_packet_size ();
12719
12720   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12721   if (packet_config_support (packet) == PACKET_ENABLE
12722       && conf->bts.size != rs->btrace_config.bts.size)
12723     {
12724       pos = buf;
12725       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12726                         conf->bts.size);
12727
12728       putpkt (buf);
12729       getpkt (&buf, &rs->buf_size, 0);
12730
12731       if (packet_ok (buf, packet) == PACKET_ERROR)
12732         {
12733           if (buf[0] == 'E' && buf[1] == '.')
12734             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12735           else
12736             error (_("Failed to configure the BTS buffer size."));
12737         }
12738
12739       rs->btrace_config.bts.size = conf->bts.size;
12740     }
12741
12742   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12743   if (packet_config_support (packet) == PACKET_ENABLE
12744       && conf->pt.size != rs->btrace_config.pt.size)
12745     {
12746       pos = buf;
12747       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12748                         conf->pt.size);
12749
12750       putpkt (buf);
12751       getpkt (&buf, &rs->buf_size, 0);
12752
12753       if (packet_ok (buf, packet) == PACKET_ERROR)
12754         {
12755           if (buf[0] == 'E' && buf[1] == '.')
12756             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12757           else
12758             error (_("Failed to configure the trace buffer size."));
12759         }
12760
12761       rs->btrace_config.pt.size = conf->pt.size;
12762     }
12763 }
12764
12765 /* Read the current thread's btrace configuration from the target and
12766    store it into CONF.  */
12767
12768 static void
12769 btrace_read_config (struct btrace_config *conf)
12770 {
12771   char *xml;
12772
12773   xml = target_read_stralloc (&current_target,
12774                               TARGET_OBJECT_BTRACE_CONF, "");
12775   if (xml != NULL)
12776     {
12777       struct cleanup *cleanup;
12778
12779       cleanup = make_cleanup (xfree, xml);
12780       parse_xml_btrace_conf (conf, xml);
12781       do_cleanups (cleanup);
12782     }
12783 }
12784
12785 /* Maybe reopen target btrace.  */
12786
12787 static void
12788 remote_btrace_maybe_reopen (void)
12789 {
12790   struct remote_state *rs = get_remote_state ();
12791   struct cleanup *cleanup;
12792   struct thread_info *tp;
12793   int btrace_target_pushed = 0;
12794   int warned = 0;
12795
12796   cleanup = make_cleanup_restore_current_thread ();
12797   ALL_NON_EXITED_THREADS (tp)
12798     {
12799       set_general_thread (tp->ptid);
12800
12801       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
12802       btrace_read_config (&rs->btrace_config);
12803
12804       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
12805         continue;
12806
12807 #if !defined (HAVE_LIBIPT)
12808       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
12809         {
12810           if (!warned)
12811             {
12812               warned = 1;
12813               warning (_("GDB does not support Intel Processor Trace. "
12814                          "\"record\" will not work in this session."));
12815             }
12816
12817           continue;
12818         }
12819 #endif /* !defined (HAVE_LIBIPT) */
12820
12821       /* Push target, once, but before anything else happens.  This way our
12822          changes to the threads will be cleaned up by unpushing the target
12823          in case btrace_read_config () throws.  */
12824       if (!btrace_target_pushed)
12825         {
12826           btrace_target_pushed = 1;
12827           record_btrace_push_target ();
12828           printf_filtered (_("Target is recording using %s.\n"),
12829                            btrace_format_string (rs->btrace_config.format));
12830         }
12831
12832       tp->btrace.target = XCNEW (struct btrace_target_info);
12833       tp->btrace.target->ptid = tp->ptid;
12834       tp->btrace.target->conf = rs->btrace_config;
12835     }
12836   do_cleanups (cleanup);
12837 }
12838
12839 /* Enable branch tracing.  */
12840
12841 static struct btrace_target_info *
12842 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12843                       const struct btrace_config *conf)
12844 {
12845   struct btrace_target_info *tinfo = NULL;
12846   struct packet_config *packet = NULL;
12847   struct remote_state *rs = get_remote_state ();
12848   char *buf = rs->buf;
12849   char *endbuf = rs->buf + get_remote_packet_size ();
12850
12851   switch (conf->format)
12852     {
12853       case BTRACE_FORMAT_BTS:
12854         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12855         break;
12856
12857       case BTRACE_FORMAT_PT:
12858         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12859         break;
12860     }
12861
12862   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12863     error (_("Target does not support branch tracing."));
12864
12865   btrace_sync_conf (conf);
12866
12867   set_general_thread (ptid);
12868
12869   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12870   putpkt (rs->buf);
12871   getpkt (&rs->buf, &rs->buf_size, 0);
12872
12873   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12874     {
12875       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12876         error (_("Could not enable branch tracing for %s: %s"),
12877                target_pid_to_str (ptid), rs->buf + 2);
12878       else
12879         error (_("Could not enable branch tracing for %s."),
12880                target_pid_to_str (ptid));
12881     }
12882
12883   tinfo = XCNEW (struct btrace_target_info);
12884   tinfo->ptid = ptid;
12885
12886   /* If we fail to read the configuration, we lose some information, but the
12887      tracing itself is not impacted.  */
12888   TRY
12889     {
12890       btrace_read_config (&tinfo->conf);
12891     }
12892   CATCH (err, RETURN_MASK_ERROR)
12893     {
12894       if (err.message != NULL)
12895         warning ("%s", err.message);
12896     }
12897   END_CATCH
12898
12899   return tinfo;
12900 }
12901
12902 /* Disable branch tracing.  */
12903
12904 static void
12905 remote_disable_btrace (struct target_ops *self,
12906                        struct btrace_target_info *tinfo)
12907 {
12908   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12909   struct remote_state *rs = get_remote_state ();
12910   char *buf = rs->buf;
12911   char *endbuf = rs->buf + get_remote_packet_size ();
12912
12913   if (packet_config_support (packet) != PACKET_ENABLE)
12914     error (_("Target does not support branch tracing."));
12915
12916   set_general_thread (tinfo->ptid);
12917
12918   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12919   putpkt (rs->buf);
12920   getpkt (&rs->buf, &rs->buf_size, 0);
12921
12922   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12923     {
12924       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12925         error (_("Could not disable branch tracing for %s: %s"),
12926                target_pid_to_str (tinfo->ptid), rs->buf + 2);
12927       else
12928         error (_("Could not disable branch tracing for %s."),
12929                target_pid_to_str (tinfo->ptid));
12930     }
12931
12932   xfree (tinfo);
12933 }
12934
12935 /* Teardown branch tracing.  */
12936
12937 static void
12938 remote_teardown_btrace (struct target_ops *self,
12939                         struct btrace_target_info *tinfo)
12940 {
12941   /* We must not talk to the target during teardown.  */
12942   xfree (tinfo);
12943 }
12944
12945 /* Read the branch trace.  */
12946
12947 static enum btrace_error
12948 remote_read_btrace (struct target_ops *self,
12949                     struct btrace_data *btrace,
12950                     struct btrace_target_info *tinfo,
12951                     enum btrace_read_type type)
12952 {
12953   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12954   struct cleanup *cleanup;
12955   const char *annex;
12956   char *xml;
12957
12958   if (packet_config_support (packet) != PACKET_ENABLE)
12959     error (_("Target does not support branch tracing."));
12960
12961 #if !defined(HAVE_LIBEXPAT)
12962   error (_("Cannot process branch tracing result. XML parsing not supported."));
12963 #endif
12964
12965   switch (type)
12966     {
12967     case BTRACE_READ_ALL:
12968       annex = "all";
12969       break;
12970     case BTRACE_READ_NEW:
12971       annex = "new";
12972       break;
12973     case BTRACE_READ_DELTA:
12974       annex = "delta";
12975       break;
12976     default:
12977       internal_error (__FILE__, __LINE__,
12978                       _("Bad branch tracing read type: %u."),
12979                       (unsigned int) type);
12980     }
12981
12982   xml = target_read_stralloc (&current_target,
12983                               TARGET_OBJECT_BTRACE, annex);
12984   if (xml == NULL)
12985     return BTRACE_ERR_UNKNOWN;
12986
12987   cleanup = make_cleanup (xfree, xml);
12988   parse_xml_btrace (btrace, xml);
12989   do_cleanups (cleanup);
12990
12991   return BTRACE_ERR_NONE;
12992 }
12993
12994 static const struct btrace_config *
12995 remote_btrace_conf (struct target_ops *self,
12996                     const struct btrace_target_info *tinfo)
12997 {
12998   return &tinfo->conf;
12999 }
13000
13001 static int
13002 remote_augmented_libraries_svr4_read (struct target_ops *self)
13003 {
13004   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13005           == PACKET_ENABLE);
13006 }
13007
13008 /* Implementation of to_load.  */
13009
13010 static void
13011 remote_load (struct target_ops *self, const char *name, int from_tty)
13012 {
13013   generic_load (name, from_tty);
13014 }
13015
13016 /* Accepts an integer PID; returns a string representing a file that
13017    can be opened on the remote side to get the symbols for the child
13018    process.  Returns NULL if the operation is not supported.  */
13019
13020 static char *
13021 remote_pid_to_exec_file (struct target_ops *self, int pid)
13022 {
13023   static char *filename = NULL;
13024   struct inferior *inf;
13025   char *annex = NULL;
13026
13027   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13028     return NULL;
13029
13030   if (filename != NULL)
13031     xfree (filename);
13032
13033   inf = find_inferior_pid (pid);
13034   if (inf == NULL)
13035     internal_error (__FILE__, __LINE__,
13036                     _("not currently attached to process %d"), pid);
13037
13038   if (!inf->fake_pid_p)
13039     {
13040       const int annex_size = 9;
13041
13042       annex = (char *) alloca (annex_size);
13043       xsnprintf (annex, annex_size, "%x", pid);
13044     }
13045
13046   filename = target_read_stralloc (&current_target,
13047                                    TARGET_OBJECT_EXEC_FILE, annex);
13048
13049   return filename;
13050 }
13051
13052 /* Implement the to_can_do_single_step target_ops method.  */
13053
13054 static int
13055 remote_can_do_single_step (struct target_ops *ops)
13056 {
13057   /* We can only tell whether target supports single step or not by
13058      supported s and S vCont actions if the stub supports vContSupported
13059      feature.  If the stub doesn't support vContSupported feature,
13060      we have conservatively to think target doesn't supports single
13061      step.  */
13062   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13063     {
13064       struct remote_state *rs = get_remote_state ();
13065
13066       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13067         remote_vcont_probe (rs);
13068
13069       return rs->supports_vCont.s && rs->supports_vCont.S;
13070     }
13071   else
13072     return 0;
13073 }
13074
13075 /* Implementation of the to_execution_direction method for the remote
13076    target.  */
13077
13078 static enum exec_direction_kind
13079 remote_execution_direction (struct target_ops *self)
13080 {
13081   struct remote_state *rs = get_remote_state ();
13082
13083   return rs->last_resume_exec_dir;
13084 }
13085
13086 static void
13087 init_remote_ops (void)
13088 {
13089   remote_ops.to_shortname = "remote";
13090   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13091   remote_ops.to_doc =
13092     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13093 Specify the serial device it is connected to\n\
13094 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13095   remote_ops.to_open = remote_open;
13096   remote_ops.to_close = remote_close;
13097   remote_ops.to_detach = remote_detach;
13098   remote_ops.to_disconnect = remote_disconnect;
13099   remote_ops.to_resume = remote_resume;
13100   remote_ops.to_wait = remote_wait;
13101   remote_ops.to_fetch_registers = remote_fetch_registers;
13102   remote_ops.to_store_registers = remote_store_registers;
13103   remote_ops.to_prepare_to_store = remote_prepare_to_store;
13104   remote_ops.to_files_info = remote_files_info;
13105   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13106   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13107   remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13108   remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13109   remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13110   remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13111   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13112   remote_ops.to_stopped_data_address = remote_stopped_data_address;
13113   remote_ops.to_watchpoint_addr_within_range =
13114     remote_watchpoint_addr_within_range;
13115   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13116   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13117   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13118   remote_ops.to_region_ok_for_hw_watchpoint
13119      = remote_region_ok_for_hw_watchpoint;
13120   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13121   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13122   remote_ops.to_kill = remote_kill;
13123   remote_ops.to_load = remote_load;
13124   remote_ops.to_mourn_inferior = remote_mourn;
13125   remote_ops.to_pass_signals = remote_pass_signals;
13126   remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13127   remote_ops.to_program_signals = remote_program_signals;
13128   remote_ops.to_thread_alive = remote_thread_alive;
13129   remote_ops.to_thread_name = remote_thread_name;
13130   remote_ops.to_update_thread_list = remote_update_thread_list;
13131   remote_ops.to_pid_to_str = remote_pid_to_str;
13132   remote_ops.to_extra_thread_info = remote_threads_extra_info;
13133   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13134   remote_ops.to_stop = remote_stop;
13135   remote_ops.to_interrupt = remote_interrupt;
13136   remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
13137   remote_ops.to_xfer_partial = remote_xfer_partial;
13138   remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
13139   remote_ops.to_rcmd = remote_rcmd;
13140   remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13141   remote_ops.to_log_command = serial_log_command;
13142   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13143   remote_ops.to_stratum = process_stratum;
13144   remote_ops.to_has_all_memory = default_child_has_all_memory;
13145   remote_ops.to_has_memory = default_child_has_memory;
13146   remote_ops.to_has_stack = default_child_has_stack;
13147   remote_ops.to_has_registers = default_child_has_registers;
13148   remote_ops.to_has_execution = default_child_has_execution;
13149   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
13150   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13151   remote_ops.to_magic = OPS_MAGIC;
13152   remote_ops.to_memory_map = remote_memory_map;
13153   remote_ops.to_flash_erase = remote_flash_erase;
13154   remote_ops.to_flash_done = remote_flash_done;
13155   remote_ops.to_read_description = remote_read_description;
13156   remote_ops.to_search_memory = remote_search_memory;
13157   remote_ops.to_can_async_p = remote_can_async_p;
13158   remote_ops.to_is_async_p = remote_is_async_p;
13159   remote_ops.to_async = remote_async;
13160   remote_ops.to_thread_events = remote_thread_events;
13161   remote_ops.to_can_do_single_step = remote_can_do_single_step;
13162   remote_ops.to_terminal_inferior = remote_terminal_inferior;
13163   remote_ops.to_terminal_ours = remote_terminal_ours;
13164   remote_ops.to_supports_non_stop = remote_supports_non_stop;
13165   remote_ops.to_supports_multi_process = remote_supports_multi_process;
13166   remote_ops.to_supports_disable_randomization
13167     = remote_supports_disable_randomization;
13168   remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13169   remote_ops.to_fileio_open = remote_hostio_open;
13170   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13171   remote_ops.to_fileio_pread = remote_hostio_pread;
13172   remote_ops.to_fileio_fstat = remote_hostio_fstat;
13173   remote_ops.to_fileio_close = remote_hostio_close;
13174   remote_ops.to_fileio_unlink = remote_hostio_unlink;
13175   remote_ops.to_fileio_readlink = remote_hostio_readlink;
13176   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13177   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13178   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13179   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13180   remote_ops.to_trace_init = remote_trace_init;
13181   remote_ops.to_download_tracepoint = remote_download_tracepoint;
13182   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13183   remote_ops.to_download_trace_state_variable
13184     = remote_download_trace_state_variable;
13185   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13186   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13187   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13188   remote_ops.to_trace_start = remote_trace_start;
13189   remote_ops.to_get_trace_status = remote_get_trace_status;
13190   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13191   remote_ops.to_trace_stop = remote_trace_stop;
13192   remote_ops.to_trace_find = remote_trace_find;
13193   remote_ops.to_get_trace_state_variable_value
13194     = remote_get_trace_state_variable_value;
13195   remote_ops.to_save_trace_data = remote_save_trace_data;
13196   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13197   remote_ops.to_upload_trace_state_variables
13198     = remote_upload_trace_state_variables;
13199   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13200   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13201   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13202   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13203   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13204   remote_ops.to_set_trace_notes = remote_set_trace_notes;
13205   remote_ops.to_core_of_thread = remote_core_of_thread;
13206   remote_ops.to_verify_memory = remote_verify_memory;
13207   remote_ops.to_get_tib_address = remote_get_tib_address;
13208   remote_ops.to_set_permissions = remote_set_permissions;
13209   remote_ops.to_static_tracepoint_marker_at
13210     = remote_static_tracepoint_marker_at;
13211   remote_ops.to_static_tracepoint_markers_by_strid
13212     = remote_static_tracepoint_markers_by_strid;
13213   remote_ops.to_traceframe_info = remote_traceframe_info;
13214   remote_ops.to_use_agent = remote_use_agent;
13215   remote_ops.to_can_use_agent = remote_can_use_agent;
13216   remote_ops.to_supports_btrace = remote_supports_btrace;
13217   remote_ops.to_enable_btrace = remote_enable_btrace;
13218   remote_ops.to_disable_btrace = remote_disable_btrace;
13219   remote_ops.to_teardown_btrace = remote_teardown_btrace;
13220   remote_ops.to_read_btrace = remote_read_btrace;
13221   remote_ops.to_btrace_conf = remote_btrace_conf;
13222   remote_ops.to_augmented_libraries_svr4_read =
13223     remote_augmented_libraries_svr4_read;
13224   remote_ops.to_follow_fork = remote_follow_fork;
13225   remote_ops.to_follow_exec = remote_follow_exec;
13226   remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13227   remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13228   remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13229   remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13230   remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13231   remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13232   remote_ops.to_execution_direction = remote_execution_direction;
13233 }
13234
13235 /* Set up the extended remote vector by making a copy of the standard
13236    remote vector and adding to it.  */
13237
13238 static void
13239 init_extended_remote_ops (void)
13240 {
13241   extended_remote_ops = remote_ops;
13242
13243   extended_remote_ops.to_shortname = "extended-remote";
13244   extended_remote_ops.to_longname =
13245     "Extended remote serial target in gdb-specific protocol";
13246   extended_remote_ops.to_doc =
13247     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13248 Specify the serial device it is connected to (e.g. /dev/ttya).";
13249   extended_remote_ops.to_open = extended_remote_open;
13250   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13251   extended_remote_ops.to_detach = extended_remote_detach;
13252   extended_remote_ops.to_attach = extended_remote_attach;
13253   extended_remote_ops.to_post_attach = extended_remote_post_attach;
13254   extended_remote_ops.to_supports_disable_randomization
13255     = extended_remote_supports_disable_randomization;
13256 }
13257
13258 static int
13259 remote_can_async_p (struct target_ops *ops)
13260 {
13261   struct remote_state *rs = get_remote_state ();
13262
13263   if (!target_async_permitted)
13264     /* We only enable async when the user specifically asks for it.  */
13265     return 0;
13266
13267   /* We're async whenever the serial device is.  */
13268   return serial_can_async_p (rs->remote_desc);
13269 }
13270
13271 static int
13272 remote_is_async_p (struct target_ops *ops)
13273 {
13274   struct remote_state *rs = get_remote_state ();
13275
13276   if (!target_async_permitted)
13277     /* We only enable async when the user specifically asks for it.  */
13278     return 0;
13279
13280   /* We're async whenever the serial device is.  */
13281   return serial_is_async_p (rs->remote_desc);
13282 }
13283
13284 /* Pass the SERIAL event on and up to the client.  One day this code
13285    will be able to delay notifying the client of an event until the
13286    point where an entire packet has been received.  */
13287
13288 static serial_event_ftype remote_async_serial_handler;
13289
13290 static void
13291 remote_async_serial_handler (struct serial *scb, void *context)
13292 {
13293   /* Don't propogate error information up to the client.  Instead let
13294      the client find out about the error by querying the target.  */
13295   inferior_event_handler (INF_REG_EVENT, NULL);
13296 }
13297
13298 static void
13299 remote_async_inferior_event_handler (gdb_client_data data)
13300 {
13301   inferior_event_handler (INF_REG_EVENT, NULL);
13302 }
13303
13304 static void
13305 remote_async (struct target_ops *ops, int enable)
13306 {
13307   struct remote_state *rs = get_remote_state ();
13308
13309   if (enable)
13310     {
13311       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13312
13313       /* If there are pending events in the stop reply queue tell the
13314          event loop to process them.  */
13315       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13316         mark_async_event_handler (remote_async_inferior_event_token);
13317       /* For simplicity, below we clear the pending events token
13318          without remembering whether it is marked, so here we always
13319          mark it.  If there's actually no pending notification to
13320          process, this ends up being a no-op (other than a spurious
13321          event-loop wakeup).  */
13322       if (target_is_non_stop_p ())
13323         mark_async_event_handler (rs->notif_state->get_pending_events_token);
13324     }
13325   else
13326     {
13327       serial_async (rs->remote_desc, NULL, NULL);
13328       /* If the core is disabling async, it doesn't want to be
13329          disturbed with target events.  Clear all async event sources
13330          too.  */
13331       clear_async_event_handler (remote_async_inferior_event_token);
13332       if (target_is_non_stop_p ())
13333         clear_async_event_handler (rs->notif_state->get_pending_events_token);
13334     }
13335 }
13336
13337 /* Implementation of the to_thread_events method.  */
13338
13339 static void
13340 remote_thread_events (struct target_ops *ops, int enable)
13341 {
13342   struct remote_state *rs = get_remote_state ();
13343   size_t size = get_remote_packet_size ();
13344
13345   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13346     return;
13347
13348   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13349   putpkt (rs->buf);
13350   getpkt (&rs->buf, &rs->buf_size, 0);
13351
13352   switch (packet_ok (rs->buf,
13353                      &remote_protocol_packets[PACKET_QThreadEvents]))
13354     {
13355     case PACKET_OK:
13356       if (strcmp (rs->buf, "OK") != 0)
13357         error (_("Remote refused setting thread events: %s"), rs->buf);
13358       break;
13359     case PACKET_ERROR:
13360       warning (_("Remote failure reply: %s"), rs->buf);
13361       break;
13362     case PACKET_UNKNOWN:
13363       break;
13364     }
13365 }
13366
13367 static void
13368 set_remote_cmd (char *args, int from_tty)
13369 {
13370   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13371 }
13372
13373 static void
13374 show_remote_cmd (char *args, int from_tty)
13375 {
13376   /* We can't just use cmd_show_list here, because we want to skip
13377      the redundant "show remote Z-packet" and the legacy aliases.  */
13378   struct cleanup *showlist_chain;
13379   struct cmd_list_element *list = remote_show_cmdlist;
13380   struct ui_out *uiout = current_uiout;
13381
13382   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13383   for (; list != NULL; list = list->next)
13384     if (strcmp (list->name, "Z-packet") == 0)
13385       continue;
13386     else if (list->type == not_set_cmd)
13387       /* Alias commands are exactly like the original, except they
13388          don't have the normal type.  */
13389       continue;
13390     else
13391       {
13392         struct cleanup *option_chain
13393           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13394
13395         ui_out_field_string (uiout, "name", list->name);
13396         ui_out_text (uiout, ":  ");
13397         if (list->type == show_cmd)
13398           do_show_command (NULL, from_tty, list);
13399         else
13400           cmd_func (list, NULL, from_tty);
13401         /* Close the tuple.  */
13402         do_cleanups (option_chain);
13403       }
13404
13405   /* Close the tuple.  */
13406   do_cleanups (showlist_chain);
13407 }
13408
13409
13410 /* Function to be called whenever a new objfile (shlib) is detected.  */
13411 static void
13412 remote_new_objfile (struct objfile *objfile)
13413 {
13414   struct remote_state *rs = get_remote_state ();
13415
13416   if (rs->remote_desc != 0)             /* Have a remote connection.  */
13417     remote_check_symbols ();
13418 }
13419
13420 /* Pull all the tracepoints defined on the target and create local
13421    data structures representing them.  We don't want to create real
13422    tracepoints yet, we don't want to mess up the user's existing
13423    collection.  */
13424   
13425 static int
13426 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13427 {
13428   struct remote_state *rs = get_remote_state ();
13429   char *p;
13430
13431   /* Ask for a first packet of tracepoint definition.  */
13432   putpkt ("qTfP");
13433   getpkt (&rs->buf, &rs->buf_size, 0);
13434   p = rs->buf;
13435   while (*p && *p != 'l')
13436     {
13437       parse_tracepoint_definition (p, utpp);
13438       /* Ask for another packet of tracepoint definition.  */
13439       putpkt ("qTsP");
13440       getpkt (&rs->buf, &rs->buf_size, 0);
13441       p = rs->buf;
13442     }
13443   return 0;
13444 }
13445
13446 static int
13447 remote_upload_trace_state_variables (struct target_ops *self,
13448                                      struct uploaded_tsv **utsvp)
13449 {
13450   struct remote_state *rs = get_remote_state ();
13451   char *p;
13452
13453   /* Ask for a first packet of variable definition.  */
13454   putpkt ("qTfV");
13455   getpkt (&rs->buf, &rs->buf_size, 0);
13456   p = rs->buf;
13457   while (*p && *p != 'l')
13458     {
13459       parse_tsv_definition (p, utsvp);
13460       /* Ask for another packet of variable definition.  */
13461       putpkt ("qTsV");
13462       getpkt (&rs->buf, &rs->buf_size, 0);
13463       p = rs->buf;
13464     }
13465   return 0;
13466 }
13467
13468 /* The "set/show range-stepping" show hook.  */
13469
13470 static void
13471 show_range_stepping (struct ui_file *file, int from_tty,
13472                      struct cmd_list_element *c,
13473                      const char *value)
13474 {
13475   fprintf_filtered (file,
13476                     _("Debugger's willingness to use range stepping "
13477                       "is %s.\n"), value);
13478 }
13479
13480 /* The "set/show range-stepping" set hook.  */
13481
13482 static void
13483 set_range_stepping (char *ignore_args, int from_tty,
13484                     struct cmd_list_element *c)
13485 {
13486   struct remote_state *rs = get_remote_state ();
13487
13488   /* Whene enabling, check whether range stepping is actually
13489      supported by the target, and warn if not.  */
13490   if (use_range_stepping)
13491     {
13492       if (rs->remote_desc != NULL)
13493         {
13494           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13495             remote_vcont_probe (rs);
13496
13497           if (packet_support (PACKET_vCont) == PACKET_ENABLE
13498               && rs->supports_vCont.r)
13499             return;
13500         }
13501
13502       warning (_("Range stepping is not supported by the current target"));
13503     }
13504 }
13505
13506 void
13507 _initialize_remote (void)
13508 {
13509   struct cmd_list_element *cmd;
13510   const char *cmd_name;
13511
13512   /* architecture specific data */
13513   remote_gdbarch_data_handle =
13514     gdbarch_data_register_post_init (init_remote_state);
13515   remote_g_packet_data_handle =
13516     gdbarch_data_register_pre_init (remote_g_packet_data_init);
13517
13518   remote_pspace_data
13519     = register_program_space_data_with_cleanup (NULL,
13520                                                 remote_pspace_data_cleanup);
13521
13522   /* Initialize the per-target state.  At the moment there is only one
13523      of these, not one per target.  Only one target is active at a
13524      time.  */
13525   remote_state = new_remote_state ();
13526
13527   init_remote_ops ();
13528   add_target (&remote_ops);
13529
13530   init_extended_remote_ops ();
13531   add_target (&extended_remote_ops);
13532
13533   /* Hook into new objfile notification.  */
13534   observer_attach_new_objfile (remote_new_objfile);
13535   /* We're no longer interested in notification events of an inferior
13536      when it exits.  */
13537   observer_attach_inferior_exit (discard_pending_stop_replies);
13538
13539 #if 0
13540   init_remote_threadtests ();
13541 #endif
13542
13543   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13544   /* set/show remote ...  */
13545
13546   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13547 Remote protocol specific variables\n\
13548 Configure various remote-protocol specific variables such as\n\
13549 the packets being used"),
13550                   &remote_set_cmdlist, "set remote ",
13551                   0 /* allow-unknown */, &setlist);
13552   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13553 Remote protocol specific variables\n\
13554 Configure various remote-protocol specific variables such as\n\
13555 the packets being used"),
13556                   &remote_show_cmdlist, "show remote ",
13557                   0 /* allow-unknown */, &showlist);
13558
13559   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13560 Compare section data on target to the exec file.\n\
13561 Argument is a single section name (default: all loaded sections).\n\
13562 To compare only read-only loaded sections, specify the -r option."),
13563            &cmdlist);
13564
13565   add_cmd ("packet", class_maintenance, packet_command, _("\
13566 Send an arbitrary packet to a remote target.\n\
13567    maintenance packet TEXT\n\
13568 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13569 this command sends the string TEXT to the inferior, and displays the\n\
13570 response packet.  GDB supplies the initial `$' character, and the\n\
13571 terminating `#' character and checksum."),
13572            &maintenancelist);
13573
13574   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13575 Set whether to send break if interrupted."), _("\
13576 Show whether to send break if interrupted."), _("\
13577 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13578                            set_remotebreak, show_remotebreak,
13579                            &setlist, &showlist);
13580   cmd_name = "remotebreak";
13581   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13582   deprecate_cmd (cmd, "set remote interrupt-sequence");
13583   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13584   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13585   deprecate_cmd (cmd, "show remote interrupt-sequence");
13586
13587   add_setshow_enum_cmd ("interrupt-sequence", class_support,
13588                         interrupt_sequence_modes, &interrupt_sequence_mode,
13589                         _("\
13590 Set interrupt sequence to remote target."), _("\
13591 Show interrupt sequence to remote target."), _("\
13592 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13593                         NULL, show_interrupt_sequence,
13594                         &remote_set_cmdlist,
13595                         &remote_show_cmdlist);
13596
13597   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13598                            &interrupt_on_connect, _("\
13599 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
13600 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
13601 If set, interrupt sequence is sent to remote target."),
13602                            NULL, NULL,
13603                            &remote_set_cmdlist, &remote_show_cmdlist);
13604
13605   /* Install commands for configuring memory read/write packets.  */
13606
13607   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13608 Set the maximum number of bytes per memory write packet (deprecated)."),
13609            &setlist);
13610   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13611 Show the maximum number of bytes per memory write packet (deprecated)."),
13612            &showlist);
13613   add_cmd ("memory-write-packet-size", no_class,
13614            set_memory_write_packet_size, _("\
13615 Set the maximum number of bytes per memory-write packet.\n\
13616 Specify the number of bytes in a packet or 0 (zero) for the\n\
13617 default packet size.  The actual limit is further reduced\n\
13618 dependent on the target.  Specify ``fixed'' to disable the\n\
13619 further restriction and ``limit'' to enable that restriction."),
13620            &remote_set_cmdlist);
13621   add_cmd ("memory-read-packet-size", no_class,
13622            set_memory_read_packet_size, _("\
13623 Set the maximum number of bytes per memory-read packet.\n\
13624 Specify the number of bytes in a packet or 0 (zero) for the\n\
13625 default packet size.  The actual limit is further reduced\n\
13626 dependent on the target.  Specify ``fixed'' to disable the\n\
13627 further restriction and ``limit'' to enable that restriction."),
13628            &remote_set_cmdlist);
13629   add_cmd ("memory-write-packet-size", no_class,
13630            show_memory_write_packet_size,
13631            _("Show the maximum number of bytes per memory-write packet."),
13632            &remote_show_cmdlist);
13633   add_cmd ("memory-read-packet-size", no_class,
13634            show_memory_read_packet_size,
13635            _("Show the maximum number of bytes per memory-read packet."),
13636            &remote_show_cmdlist);
13637
13638   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13639                             &remote_hw_watchpoint_limit, _("\
13640 Set the maximum number of target hardware watchpoints."), _("\
13641 Show the maximum number of target hardware watchpoints."), _("\
13642 Specify a negative limit for unlimited."),
13643                             NULL, NULL, /* FIXME: i18n: The maximum
13644                                            number of target hardware
13645                                            watchpoints is %s.  */
13646                             &remote_set_cmdlist, &remote_show_cmdlist);
13647   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13648                             &remote_hw_watchpoint_length_limit, _("\
13649 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13650 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13651 Specify a negative limit for unlimited."),
13652                             NULL, NULL, /* FIXME: i18n: The maximum
13653                                            length (in bytes) of a target
13654                                            hardware watchpoint is %s.  */
13655                             &remote_set_cmdlist, &remote_show_cmdlist);
13656   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13657                             &remote_hw_breakpoint_limit, _("\
13658 Set the maximum number of target hardware breakpoints."), _("\
13659 Show the maximum number of target hardware breakpoints."), _("\
13660 Specify a negative limit for unlimited."),
13661                             NULL, NULL, /* FIXME: i18n: The maximum
13662                                            number of target hardware
13663                                            breakpoints is %s.  */
13664                             &remote_set_cmdlist, &remote_show_cmdlist);
13665
13666   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13667                              &remote_address_size, _("\
13668 Set the maximum size of the address (in bits) in a memory packet."), _("\
13669 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13670                              NULL,
13671                              NULL, /* FIXME: i18n: */
13672                              &setlist, &showlist);
13673
13674   init_all_packet_configs ();
13675
13676   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13677                          "X", "binary-download", 1);
13678
13679   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13680                          "vCont", "verbose-resume", 0);
13681
13682   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13683                          "QPassSignals", "pass-signals", 0);
13684
13685   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13686                          "QCatchSyscalls", "catch-syscalls", 0);
13687
13688   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13689                          "QProgramSignals", "program-signals", 0);
13690
13691   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13692                          "qSymbol", "symbol-lookup", 0);
13693
13694   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13695                          "P", "set-register", 1);
13696
13697   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13698                          "p", "fetch-register", 1);
13699
13700   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13701                          "Z0", "software-breakpoint", 0);
13702
13703   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13704                          "Z1", "hardware-breakpoint", 0);
13705
13706   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13707                          "Z2", "write-watchpoint", 0);
13708
13709   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13710                          "Z3", "read-watchpoint", 0);
13711
13712   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13713                          "Z4", "access-watchpoint", 0);
13714
13715   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13716                          "qXfer:auxv:read", "read-aux-vector", 0);
13717
13718   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13719                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
13720
13721   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13722                          "qXfer:features:read", "target-features", 0);
13723
13724   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13725                          "qXfer:libraries:read", "library-info", 0);
13726
13727   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13728                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13729
13730   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13731                          "qXfer:memory-map:read", "memory-map", 0);
13732
13733   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13734                          "qXfer:spu:read", "read-spu-object", 0);
13735
13736   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13737                          "qXfer:spu:write", "write-spu-object", 0);
13738
13739   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13740                         "qXfer:osdata:read", "osdata", 0);
13741
13742   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13743                          "qXfer:threads:read", "threads", 0);
13744
13745   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13746                          "qXfer:siginfo:read", "read-siginfo-object", 0);
13747
13748   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13749                          "qXfer:siginfo:write", "write-siginfo-object", 0);
13750
13751   add_packet_config_cmd
13752     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13753      "qXfer:traceframe-info:read", "traceframe-info", 0);
13754
13755   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13756                          "qXfer:uib:read", "unwind-info-block", 0);
13757
13758   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13759                          "qGetTLSAddr", "get-thread-local-storage-address",
13760                          0);
13761
13762   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13763                          "qGetTIBAddr", "get-thread-information-block-address",
13764                          0);
13765
13766   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13767                          "bc", "reverse-continue", 0);
13768
13769   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13770                          "bs", "reverse-step", 0);
13771
13772   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13773                          "qSupported", "supported-packets", 0);
13774
13775   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13776                          "qSearch:memory", "search-memory", 0);
13777
13778   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13779                          "qTStatus", "trace-status", 0);
13780
13781   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13782                          "vFile:setfs", "hostio-setfs", 0);
13783
13784   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13785                          "vFile:open", "hostio-open", 0);
13786
13787   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13788                          "vFile:pread", "hostio-pread", 0);
13789
13790   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13791                          "vFile:pwrite", "hostio-pwrite", 0);
13792
13793   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13794                          "vFile:close", "hostio-close", 0);
13795
13796   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13797                          "vFile:unlink", "hostio-unlink", 0);
13798
13799   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13800                          "vFile:readlink", "hostio-readlink", 0);
13801
13802   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13803                          "vFile:fstat", "hostio-fstat", 0);
13804
13805   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13806                          "vAttach", "attach", 0);
13807
13808   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13809                          "vRun", "run", 0);
13810
13811   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13812                          "QStartNoAckMode", "noack", 0);
13813
13814   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13815                          "vKill", "kill", 0);
13816
13817   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13818                          "qAttached", "query-attached", 0);
13819
13820   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13821                          "ConditionalTracepoints",
13822                          "conditional-tracepoints", 0);
13823
13824   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13825                          "ConditionalBreakpoints",
13826                          "conditional-breakpoints", 0);
13827
13828   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13829                          "BreakpointCommands",
13830                          "breakpoint-commands", 0);
13831
13832   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13833                          "FastTracepoints", "fast-tracepoints", 0);
13834
13835   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13836                          "TracepointSource", "TracepointSource", 0);
13837
13838   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13839                          "QAllow", "allow", 0);
13840
13841   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13842                          "StaticTracepoints", "static-tracepoints", 0);
13843
13844   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13845                          "InstallInTrace", "install-in-trace", 0);
13846
13847   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13848                          "qXfer:statictrace:read", "read-sdata-object", 0);
13849
13850   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13851                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13852
13853   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13854                          "QDisableRandomization", "disable-randomization", 0);
13855
13856   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13857                          "QAgent", "agent", 0);
13858
13859   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13860                          "QTBuffer:size", "trace-buffer-size", 0);
13861
13862   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13863        "Qbtrace:off", "disable-btrace", 0);
13864
13865   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13866        "Qbtrace:bts", "enable-btrace-bts", 0);
13867
13868   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13869        "Qbtrace:pt", "enable-btrace-pt", 0);
13870
13871   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13872        "qXfer:btrace", "read-btrace", 0);
13873
13874   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13875        "qXfer:btrace-conf", "read-btrace-conf", 0);
13876
13877   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13878        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13879
13880   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13881        "multiprocess-feature", "multiprocess-feature", 0);
13882
13883   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13884                          "swbreak-feature", "swbreak-feature", 0);
13885
13886   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13887                          "hwbreak-feature", "hwbreak-feature", 0);
13888
13889   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13890                          "fork-event-feature", "fork-event-feature", 0);
13891
13892   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13893                          "vfork-event-feature", "vfork-event-feature", 0);
13894
13895   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13896        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13897
13898   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13899                          "vContSupported", "verbose-resume-supported", 0);
13900
13901   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13902                          "exec-event-feature", "exec-event-feature", 0);
13903
13904   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13905                          "vCtrlC", "ctrl-c", 0);
13906
13907   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13908                          "QThreadEvents", "thread-events", 0);
13909
13910   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13911                          "N stop reply", "no-resumed-stop-reply", 0);
13912
13913   /* Assert that we've registered "set remote foo-packet" commands
13914      for all packet configs.  */
13915   {
13916     int i;
13917
13918     for (i = 0; i < PACKET_MAX; i++)
13919       {
13920         /* Ideally all configs would have a command associated.  Some
13921            still don't though.  */
13922         int excepted;
13923
13924         switch (i)
13925           {
13926           case PACKET_QNonStop:
13927           case PACKET_EnableDisableTracepoints_feature:
13928           case PACKET_tracenz_feature:
13929           case PACKET_DisconnectedTracing_feature:
13930           case PACKET_augmented_libraries_svr4_read_feature:
13931           case PACKET_qCRC:
13932             /* Additions to this list need to be well justified:
13933                pre-existing packets are OK; new packets are not.  */
13934             excepted = 1;
13935             break;
13936           default:
13937             excepted = 0;
13938             break;
13939           }
13940
13941         /* This catches both forgetting to add a config command, and
13942            forgetting to remove a packet from the exception list.  */
13943         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13944       }
13945   }
13946
13947   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
13948      Z sub-packet has its own set and show commands, but users may
13949      have sets to this variable in their .gdbinit files (or in their
13950      documentation).  */
13951   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13952                                 &remote_Z_packet_detect, _("\
13953 Set use of remote protocol `Z' packets"), _("\
13954 Show use of remote protocol `Z' packets "), _("\
13955 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13956 packets."),
13957                                 set_remote_protocol_Z_packet_cmd,
13958                                 show_remote_protocol_Z_packet_cmd,
13959                                 /* FIXME: i18n: Use of remote protocol
13960                                    `Z' packets is %s.  */
13961                                 &remote_set_cmdlist, &remote_show_cmdlist);
13962
13963   add_prefix_cmd ("remote", class_files, remote_command, _("\
13964 Manipulate files on the remote system\n\
13965 Transfer files to and from the remote target system."),
13966                   &remote_cmdlist, "remote ",
13967                   0 /* allow-unknown */, &cmdlist);
13968
13969   add_cmd ("put", class_files, remote_put_command,
13970            _("Copy a local file to the remote system."),
13971            &remote_cmdlist);
13972
13973   add_cmd ("get", class_files, remote_get_command,
13974            _("Copy a remote file to the local system."),
13975            &remote_cmdlist);
13976
13977   add_cmd ("delete", class_files, remote_delete_command,
13978            _("Delete a remote file."),
13979            &remote_cmdlist);
13980
13981   add_setshow_string_noescape_cmd ("exec-file", class_files,
13982                                    &remote_exec_file_var, _("\
13983 Set the remote pathname for \"run\""), _("\
13984 Show the remote pathname for \"run\""), NULL,
13985                                    set_remote_exec_file,
13986                                    show_remote_exec_file,
13987                                    &remote_set_cmdlist,
13988                                    &remote_show_cmdlist);
13989
13990   add_setshow_boolean_cmd ("range-stepping", class_run,
13991                            &use_range_stepping, _("\
13992 Enable or disable range stepping."), _("\
13993 Show whether target-assisted range stepping is enabled."), _("\
13994 If on, and the target supports it, when stepping a source line, GDB\n\
13995 tells the target to step the corresponding range of addresses itself instead\n\
13996 of issuing multiple single-steps.  This speeds up source level\n\
13997 stepping.  If off, GDB always issues single-steps, even if range\n\
13998 stepping is supported by the target.  The default is on."),
13999                            set_range_stepping,
14000                            show_range_stepping,
14001                            &setlist,
14002                            &showlist);
14003
14004   /* Eventually initialize fileio.  See fileio.c */
14005   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14006
14007   /* Take advantage of the fact that the TID field is not used, to tag
14008      special ptids with it set to != 0.  */
14009   magic_null_ptid = ptid_build (42000, -1, 1);
14010   not_sent_ptid = ptid_build (42000, -2, 1);
14011   any_thread_ptid = ptid_build (42000, 0, 1);
14012
14013   target_buf_size = 2048;
14014   target_buf = (char *) xmalloc (target_buf_size);
14015 }
14016