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