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