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