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