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