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