OSDN Git Service

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