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