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