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