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