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