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