OSDN Git Service

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