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