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