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