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