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