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