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