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