1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2013 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
23 #include "gdb_string.h"
29 #include "exceptions.h"
31 /*#include "terminal.h" */
34 #include "gdb-stabs.h"
35 #include "gdbthread.h"
37 #include "remote-notif.h"
40 #include "gdb_assert.h"
43 #include "cli/cli-decode.h"
44 #include "cli/cli-setshow.h"
45 #include "target-descriptions.h"
47 #include "filestuff.h"
52 #include "event-loop.h"
53 #include "event-top.h"
59 #include "gdbcore.h" /* for exec_bfd */
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
64 #include "xml-support.h"
66 #include "memory-map.h"
68 #include "tracepoint.h"
74 /* Temp hacks for tracepoint encoding migration. */
75 static char *target_buf;
76 static long target_buf_size;
78 /* The size to align memory write packets, when practical. The protocol
79 does not guarantee any alignment, and gdb will generate short
80 writes and unaligned writes, but even as a best-effort attempt this
81 can improve bulk transfers. For instance, if a write is misaligned
82 relative to the target's data bus, the stub may need to make an extra
83 round trip fetching data from the target. This doesn't make a
84 huge difference, but it's easy to do, so we try to be helpful.
86 The alignment chosen is arbitrary; usually data bus width is
87 important here, not the possibly larger cache line size. */
88 enum { REMOTE_ALIGN_WRITES = 16 };
90 /* Prototypes for local functions. */
91 static void cleanup_sigint_signal_handler (void *dummy);
92 static void initialize_sigint_signal_handler (void);
93 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
94 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
95 int forever, int *is_notif);
97 static void handle_remote_sigint (int);
98 static void handle_remote_sigint_twice (int);
99 static void async_remote_interrupt (gdb_client_data);
100 void async_remote_interrupt_twice (gdb_client_data);
102 static void remote_files_info (struct target_ops *ignore);
104 static void remote_prepare_to_store (struct regcache *regcache);
106 static void remote_open (char *name, int from_tty);
108 static void extended_remote_open (char *name, int from_tty);
110 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
112 static void remote_close (void);
114 static void remote_mourn (struct target_ops *ops);
116 static void extended_remote_restart (void);
118 static void extended_remote_mourn (struct target_ops *);
120 static void remote_mourn_1 (struct target_ops *);
122 static void remote_send (char **buf, long *sizeof_buf_p);
124 static int readchar (int timeout);
126 static void remote_serial_write (const char *str, int len);
128 static void remote_kill (struct target_ops *ops);
130 static int tohex (int nib);
132 static int remote_can_async_p (void);
134 static int remote_is_async_p (void);
136 static void remote_async (void (*callback) (enum inferior_event_type event_type,
137 void *context), void *context);
139 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
141 static void remote_interrupt (int signo);
143 static void remote_interrupt_twice (int signo);
145 static void interrupt_query (void);
147 static void set_general_thread (struct ptid ptid);
148 static void set_continue_thread (struct ptid ptid);
150 static void get_offsets (void);
152 static void skip_frame (void);
154 static long read_frame (char **buf_p, long *sizeof_buf);
156 static int hexnumlen (ULONGEST num);
158 static void init_remote_ops (void);
160 static void init_extended_remote_ops (void);
162 static void remote_stop (ptid_t);
164 static int ishex (int ch, int *val);
166 static int stubhex (int ch);
168 static int hexnumstr (char *, ULONGEST);
170 static int hexnumnstr (char *, ULONGEST, int);
172 static CORE_ADDR remote_address_masked (CORE_ADDR);
174 static void print_packet (char *);
176 static void compare_sections_command (char *, int);
178 static void packet_command (char *, int);
180 static int stub_unpack_int (char *buff, int fieldlength);
182 static ptid_t remote_current_thread (ptid_t oldptid);
184 static void remote_find_new_threads (void);
186 static void record_currthread (ptid_t currthread);
188 static int fromhex (int a);
190 static int putpkt_binary (char *buf, int cnt);
192 static void check_binary_download (CORE_ADDR addr);
194 struct packet_config;
196 static void show_packet_config_cmd (struct packet_config *config);
198 static void update_packet_config (struct packet_config *config);
200 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
201 struct cmd_list_element *c);
203 static void show_remote_protocol_packet_cmd (struct ui_file *file,
205 struct cmd_list_element *c,
208 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
209 static ptid_t read_ptid (char *buf, char **obuf);
211 static void remote_set_permissions (void);
214 static int remote_get_trace_status (struct trace_status *ts);
216 static int remote_upload_tracepoints (struct uploaded_tp **utpp);
218 static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
220 static void remote_query_supported (void);
222 static void remote_check_symbols (void);
224 void _initialize_remote (void);
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);
233 static void remote_async_inferior_event_handler (gdb_client_data);
235 static void remote_terminal_ours (void);
237 static int remote_read_description_p (struct target_ops *target);
239 static void remote_console_output (char *msg);
241 static int remote_supports_cond_breakpoints (void);
243 static int remote_can_run_breakpoint_commands (void);
247 static struct cmd_list_element *remote_cmdlist;
249 /* For "set remote" and "show remote". */
251 static struct cmd_list_element *remote_set_cmdlist;
252 static struct cmd_list_element *remote_show_cmdlist;
254 /* Stub vCont actions support.
256 Each field is a boolean flag indicating whether the stub reports
257 support for the corresponding action. */
259 struct vCont_action_support
268 /* Controls whether GDB is willing to use range stepping. */
270 static int use_range_stepping = 1;
272 /* Description of the remote protocol state for the currently
273 connected target. This is per-target state, and independent of the
274 selected architecture. */
278 /* A buffer to use for incoming packets, and its current size. The
279 buffer is grown dynamically for larger incoming packets.
280 Outgoing packets may also be constructed in this buffer.
281 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
282 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
287 /* True if we're going through initial connection setup (finding out
288 about the remote side's threads, relocating symbols, etc.). */
291 /* If we negotiated packet size explicitly (and thus can bypass
292 heuristics for the largest packet size that will not overflow
293 a buffer in the stub), this will be set to that packet size.
294 Otherwise zero, meaning to use the guessed size. */
295 long explicit_packet_size;
297 /* remote_wait is normally called when the target is running and
298 waits for a stop reply packet. But sometimes we need to call it
299 when the target is already stopped. We can send a "?" packet
300 and have remote_wait read the response. Or, if we already have
301 the response, we can stash it in BUF and tell remote_wait to
302 skip calling getpkt. This flag is set when BUF contains a
303 stop reply packet and the target is not waiting. */
304 int cached_wait_status;
306 /* True, if in no ack mode. That is, neither GDB nor the stub will
307 expect acks from each other. The connection is assumed to be
311 /* True if we're connected in extended remote mode. */
314 /* True if the stub reported support for multi-process
316 int multi_process_aware;
318 /* True if we resumed the target and we're waiting for the target to
319 stop. In the mean time, we can't start another command/query.
320 The remote server wouldn't be ready to process it, so we'd
321 timeout waiting for a reply that would never come and eventually
322 we'd close the connection. This can happen in asynchronous mode
323 because we allow GDB commands while the target is running. */
324 int waiting_for_stop_reply;
326 /* True if the stub reports support for non-stop mode. */
329 /* The status of the stub support for the various vCont actions. */
330 struct vCont_action_support supports_vCont;
332 /* True if the stub reports support for conditional tracepoints. */
333 int cond_tracepoints;
335 /* True if the stub reports support for target-side breakpoint
337 int cond_breakpoints;
339 /* True if the stub reports support for target-side breakpoint
341 int breakpoint_commands;
343 /* True if the stub reports support for fast tracepoints. */
344 int fast_tracepoints;
346 /* True if the stub reports support for static tracepoints. */
347 int static_tracepoints;
349 /* True if the stub reports support for installing tracepoint while
351 int install_in_trace;
353 /* True if the stub can continue running a trace while GDB is
355 int disconnected_tracing;
357 /* True if the stub reports support for enabling and disabling
358 tracepoints while a trace experiment is running. */
359 int enable_disable_tracepoints;
361 /* True if the stub can collect strings using tracenz bytecode. */
364 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
365 responded to that. */
369 /* Private data that we'll store in (struct thread_info)->private. */
370 struct private_thread_info
377 free_private_thread_info (struct private_thread_info *info)
383 /* Returns true if the multi-process extensions are in effect. */
385 remote_multi_process_p (struct remote_state *rs)
387 return rs->multi_process_aware;
390 /* This data could be associated with a target, but we do not always
391 have access to the current target when we need it, so for now it is
392 static. This will be fine for as long as only one target is in use
394 static struct remote_state remote_state;
396 static struct remote_state *
397 get_remote_state_raw (void)
399 return &remote_state;
402 /* Description of the remote protocol for a given architecture. */
406 long offset; /* Offset into G packet. */
407 long regnum; /* GDB's internal register number. */
408 LONGEST pnum; /* Remote protocol register number. */
409 int in_g_packet; /* Always part of G packet. */
410 /* long size in bytes; == register_size (target_gdbarch (), regnum);
412 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
416 struct remote_arch_state
418 /* Description of the remote protocol registers. */
419 long sizeof_g_packet;
421 /* Description of the remote protocol registers indexed by REGNUM
422 (making an array gdbarch_num_regs in size). */
423 struct packet_reg *regs;
425 /* This is the size (in chars) of the first response to the ``g''
426 packet. It is used as a heuristic when determining the maximum
427 size of memory-read and memory-write packets. A target will
428 typically only reserve a buffer large enough to hold the ``g''
429 packet. The size does not include packet overhead (headers and
431 long actual_register_packet_size;
433 /* This is the maximum size (in chars) of a non read/write packet.
434 It is also used as a cap on the size of read/write packets. */
435 long remote_packet_size;
438 long sizeof_pkt = 2000;
440 /* Utility: generate error from an incoming stub packet. */
442 trace_error (char *buf)
445 return; /* not an error msg */
448 case '1': /* malformed packet error */
449 if (*++buf == '0') /* general case: */
450 error (_("remote.c: error in outgoing packet."));
452 error (_("remote.c: error in outgoing packet at field #%ld."),
453 strtol (buf, NULL, 16));
455 error (_("Target returns error code '%s'."), buf);
459 /* Utility: wait for reply from stub, while accepting "O" packets. */
461 remote_get_noisy_reply (char **buf_p,
464 do /* Loop on reply from remote stub. */
468 QUIT; /* Allow user to bail out with ^C. */
469 getpkt (buf_p, sizeof_buf, 0);
473 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
476 CORE_ADDR from, to, org_to;
478 int adjusted_size = 0;
479 volatile struct gdb_exception ex;
481 p = buf + strlen ("qRelocInsn:");
482 pp = unpack_varlen_hex (p, &ul);
484 error (_("invalid qRelocInsn packet: %s"), buf);
488 unpack_varlen_hex (p, &ul);
493 TRY_CATCH (ex, RETURN_MASK_ALL)
495 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
499 adjusted_size = to - org_to;
501 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
504 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
506 /* Propagate memory errors silently back to the target.
507 The stub may have limited the range of addresses we
508 can write to, for example. */
513 /* Something unexpectedly bad happened. Be verbose so
514 we can tell what, and propagate the error back to the
515 stub, so it doesn't get stuck waiting for a
517 exception_fprintf (gdb_stderr, ex,
518 _("warning: relocating instruction: "));
522 else if (buf[0] == 'O' && buf[1] != 'K')
523 remote_console_output (buf + 1); /* 'O' message from stub */
525 return buf; /* Here's the actual reply. */
530 /* Handle for retreving the remote protocol data from gdbarch. */
531 static struct gdbarch_data *remote_gdbarch_data_handle;
533 static struct remote_arch_state *
534 get_remote_arch_state (void)
536 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
539 /* Fetch the global remote target state. */
541 static struct remote_state *
542 get_remote_state (void)
544 /* Make sure that the remote architecture state has been
545 initialized, because doing so might reallocate rs->buf. Any
546 function which calls getpkt also needs to be mindful of changes
547 to rs->buf, but this call limits the number of places which run
549 get_remote_arch_state ();
551 return get_remote_state_raw ();
555 compare_pnums (const void *lhs_, const void *rhs_)
557 const struct packet_reg * const *lhs = lhs_;
558 const struct packet_reg * const *rhs = rhs_;
560 if ((*lhs)->pnum < (*rhs)->pnum)
562 else if ((*lhs)->pnum == (*rhs)->pnum)
569 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
571 int regnum, num_remote_regs, offset;
572 struct packet_reg **remote_regs;
574 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
576 struct packet_reg *r = ®s[regnum];
578 if (register_size (gdbarch, regnum) == 0)
579 /* Do not try to fetch zero-sized (placeholder) registers. */
582 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
587 /* Define the g/G packet format as the contents of each register
588 with a remote protocol number, in order of ascending protocol
591 remote_regs = alloca (gdbarch_num_regs (gdbarch)
592 * sizeof (struct packet_reg *));
593 for (num_remote_regs = 0, regnum = 0;
594 regnum < gdbarch_num_regs (gdbarch);
596 if (regs[regnum].pnum != -1)
597 remote_regs[num_remote_regs++] = ®s[regnum];
599 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
602 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
604 remote_regs[regnum]->in_g_packet = 1;
605 remote_regs[regnum]->offset = offset;
606 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
612 /* Given the architecture described by GDBARCH, return the remote
613 protocol register's number and the register's offset in the g/G
614 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
615 If the target does not have a mapping for REGNUM, return false,
616 otherwise, return true. */
619 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
620 int *pnum, int *poffset)
623 struct packet_reg *regs;
624 struct cleanup *old_chain;
626 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
628 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
629 old_chain = make_cleanup (xfree, regs);
631 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
633 *pnum = regs[regnum].pnum;
634 *poffset = regs[regnum].offset;
636 do_cleanups (old_chain);
642 init_remote_state (struct gdbarch *gdbarch)
644 struct remote_state *rs = get_remote_state_raw ();
645 struct remote_arch_state *rsa;
647 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
649 /* Use the architecture to build a regnum<->pnum table, which will be
650 1:1 unless a feature set specifies otherwise. */
651 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
652 gdbarch_num_regs (gdbarch),
655 /* Record the maximum possible size of the g packet - it may turn out
657 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
659 /* Default maximum number of characters in a packet body. Many
660 remote stubs have a hardwired buffer size of 400 bytes
661 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
662 as the maximum packet-size to ensure that the packet and an extra
663 NUL character can always fit in the buffer. This stops GDB
664 trashing stubs that try to squeeze an extra NUL into what is
665 already a full buffer (As of 1999-12-04 that was most stubs). */
666 rsa->remote_packet_size = 400 - 1;
668 /* This one is filled in when a ``g'' packet is received. */
669 rsa->actual_register_packet_size = 0;
671 /* Should rsa->sizeof_g_packet needs more space than the
672 default, adjust the size accordingly. Remember that each byte is
673 encoded as two characters. 32 is the overhead for the packet
674 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
675 (``$NN:G...#NN'') is a better guess, the below has been padded a
677 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
678 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
680 /* Make sure that the packet buffer is plenty big enough for
681 this architecture. */
682 if (rs->buf_size < rsa->remote_packet_size)
684 rs->buf_size = 2 * rsa->remote_packet_size;
685 rs->buf = xrealloc (rs->buf, rs->buf_size);
691 /* Return the current allowed size of a remote packet. This is
692 inferred from the current architecture, and should be used to
693 limit the length of outgoing packets. */
695 get_remote_packet_size (void)
697 struct remote_state *rs = get_remote_state ();
698 struct remote_arch_state *rsa = get_remote_arch_state ();
700 if (rs->explicit_packet_size)
701 return rs->explicit_packet_size;
703 return rsa->remote_packet_size;
706 static struct packet_reg *
707 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
709 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
713 struct packet_reg *r = &rsa->regs[regnum];
715 gdb_assert (r->regnum == regnum);
720 static struct packet_reg *
721 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
725 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
727 struct packet_reg *r = &rsa->regs[i];
735 /* FIXME: graces/2002-08-08: These variables should eventually be
736 bound to an instance of the target object (as in gdbarch-tdep()),
737 when such a thing exists. */
739 /* This is set to the data address of the access causing the target
740 to stop for a watchpoint. */
741 static CORE_ADDR remote_watch_data_address;
743 /* This is non-zero if target stopped for a watchpoint. */
744 static int remote_stopped_by_watchpoint_p;
746 static struct target_ops remote_ops;
748 static struct target_ops extended_remote_ops;
750 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
751 ``forever'' still use the normal timeout mechanism. This is
752 currently used by the ASYNC code to guarentee that target reads
753 during the initial connect always time-out. Once getpkt has been
754 modified to return a timeout indication and, in turn
755 remote_wait()/wait_for_inferior() have gained a timeout parameter
757 static int wait_forever_enabled_p = 1;
759 /* Allow the user to specify what sequence to send to the remote
760 when he requests a program interruption: Although ^C is usually
761 what remote systems expect (this is the default, here), it is
762 sometimes preferable to send a break. On other systems such
763 as the Linux kernel, a break followed by g, which is Magic SysRq g
764 is required in order to interrupt the execution. */
765 const char interrupt_sequence_control_c[] = "Ctrl-C";
766 const char interrupt_sequence_break[] = "BREAK";
767 const char interrupt_sequence_break_g[] = "BREAK-g";
768 static const char *const interrupt_sequence_modes[] =
770 interrupt_sequence_control_c,
771 interrupt_sequence_break,
772 interrupt_sequence_break_g,
775 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
778 show_interrupt_sequence (struct ui_file *file, int from_tty,
779 struct cmd_list_element *c,
782 if (interrupt_sequence_mode == interrupt_sequence_control_c)
783 fprintf_filtered (file,
784 _("Send the ASCII ETX character (Ctrl-c) "
785 "to the remote target to interrupt the "
786 "execution of the program.\n"));
787 else if (interrupt_sequence_mode == interrupt_sequence_break)
788 fprintf_filtered (file,
789 _("send a break signal to the remote target "
790 "to interrupt the execution of the program.\n"));
791 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
792 fprintf_filtered (file,
793 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
794 "the remote target to interrupt the execution "
795 "of Linux kernel.\n"));
797 internal_error (__FILE__, __LINE__,
798 _("Invalid value for interrupt_sequence_mode: %s."),
799 interrupt_sequence_mode);
802 /* This boolean variable specifies whether interrupt_sequence is sent
803 to the remote target when gdb connects to it.
804 This is mostly needed when you debug the Linux kernel: The Linux kernel
805 expects BREAK g which is Magic SysRq g for connecting gdb. */
806 static int interrupt_on_connect = 0;
808 /* This variable is used to implement the "set/show remotebreak" commands.
809 Since these commands are now deprecated in favor of "set/show remote
810 interrupt-sequence", it no longer has any effect on the code. */
811 static int remote_break;
814 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
817 interrupt_sequence_mode = interrupt_sequence_break;
819 interrupt_sequence_mode = interrupt_sequence_control_c;
823 show_remotebreak (struct ui_file *file, int from_tty,
824 struct cmd_list_element *c,
829 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
830 remote_open knows that we don't have a file open when the program
832 static struct serial *remote_desc = NULL;
834 /* This variable sets the number of bits in an address that are to be
835 sent in a memory ("M" or "m") packet. Normally, after stripping
836 leading zeros, the entire address would be sent. This variable
837 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
838 initial implementation of remote.c restricted the address sent in
839 memory packets to ``host::sizeof long'' bytes - (typically 32
840 bits). Consequently, for 64 bit targets, the upper 32 bits of an
841 address was never sent. Since fixing this bug may cause a break in
842 some remote targets this variable is principly provided to
843 facilitate backward compatibility. */
845 static unsigned int remote_address_size;
847 /* Temporary to track who currently owns the terminal. See
848 remote_terminal_* for more details. */
850 static int remote_async_terminal_ours_p;
852 /* The executable file to use for "run" on the remote side. */
854 static char *remote_exec_file = "";
857 /* User configurable variables for the number of characters in a
858 memory read/write packet. MIN (rsa->remote_packet_size,
859 rsa->sizeof_g_packet) is the default. Some targets need smaller
860 values (fifo overruns, et.al.) and some users need larger values
861 (speed up transfers). The variables ``preferred_*'' (the user
862 request), ``current_*'' (what was actually set) and ``forced_*''
863 (Positive - a soft limit, negative - a hard limit). */
865 struct memory_packet_config
872 /* Compute the current size of a read/write packet. Since this makes
873 use of ``actual_register_packet_size'' the computation is dynamic. */
876 get_memory_packet_size (struct memory_packet_config *config)
878 struct remote_state *rs = get_remote_state ();
879 struct remote_arch_state *rsa = get_remote_arch_state ();
881 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
882 law?) that some hosts don't cope very well with large alloca()
883 calls. Eventually the alloca() code will be replaced by calls to
884 xmalloc() and make_cleanups() allowing this restriction to either
885 be lifted or removed. */
886 #ifndef MAX_REMOTE_PACKET_SIZE
887 #define MAX_REMOTE_PACKET_SIZE 16384
889 /* NOTE: 20 ensures we can write at least one byte. */
890 #ifndef MIN_REMOTE_PACKET_SIZE
891 #define MIN_REMOTE_PACKET_SIZE 20
896 if (config->size <= 0)
897 what_they_get = MAX_REMOTE_PACKET_SIZE;
899 what_they_get = config->size;
903 what_they_get = get_remote_packet_size ();
904 /* Limit the packet to the size specified by the user. */
906 && what_they_get > config->size)
907 what_they_get = config->size;
909 /* Limit it to the size of the targets ``g'' response unless we have
910 permission from the stub to use a larger packet size. */
911 if (rs->explicit_packet_size == 0
912 && rsa->actual_register_packet_size > 0
913 && what_they_get > rsa->actual_register_packet_size)
914 what_they_get = rsa->actual_register_packet_size;
916 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
917 what_they_get = MAX_REMOTE_PACKET_SIZE;
918 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
919 what_they_get = MIN_REMOTE_PACKET_SIZE;
921 /* Make sure there is room in the global buffer for this packet
922 (including its trailing NUL byte). */
923 if (rs->buf_size < what_they_get + 1)
925 rs->buf_size = 2 * what_they_get;
926 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
929 return what_they_get;
932 /* Update the size of a read/write packet. If they user wants
933 something really big then do a sanity check. */
936 set_memory_packet_size (char *args, struct memory_packet_config *config)
938 int fixed_p = config->fixed_p;
939 long size = config->size;
942 error (_("Argument required (integer, `fixed' or `limited')."));
943 else if (strcmp (args, "hard") == 0
944 || strcmp (args, "fixed") == 0)
946 else if (strcmp (args, "soft") == 0
947 || strcmp (args, "limit") == 0)
953 size = strtoul (args, &end, 0);
955 error (_("Invalid %s (bad syntax)."), config->name);
957 /* Instead of explicitly capping the size of a packet to
958 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
959 instead allowed to set the size to something arbitrarily
961 if (size > MAX_REMOTE_PACKET_SIZE)
962 error (_("Invalid %s (too large)."), config->name);
966 if (fixed_p && !config->fixed_p)
968 if (! query (_("The target may not be able to correctly handle a %s\n"
969 "of %ld bytes. Change the packet size? "),
971 error (_("Packet size not changed."));
973 /* Update the config. */
974 config->fixed_p = fixed_p;
979 show_memory_packet_size (struct memory_packet_config *config)
981 printf_filtered (_("The %s is %ld. "), config->name, config->size);
983 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
984 get_memory_packet_size (config));
986 printf_filtered (_("Packets are limited to %ld bytes.\n"),
987 get_memory_packet_size (config));
990 static struct memory_packet_config memory_write_packet_config =
992 "memory-write-packet-size",
996 set_memory_write_packet_size (char *args, int from_tty)
998 set_memory_packet_size (args, &memory_write_packet_config);
1002 show_memory_write_packet_size (char *args, int from_tty)
1004 show_memory_packet_size (&memory_write_packet_config);
1008 get_memory_write_packet_size (void)
1010 return get_memory_packet_size (&memory_write_packet_config);
1013 static struct memory_packet_config memory_read_packet_config =
1015 "memory-read-packet-size",
1019 set_memory_read_packet_size (char *args, int from_tty)
1021 set_memory_packet_size (args, &memory_read_packet_config);
1025 show_memory_read_packet_size (char *args, int from_tty)
1027 show_memory_packet_size (&memory_read_packet_config);
1031 get_memory_read_packet_size (void)
1033 long size = get_memory_packet_size (&memory_read_packet_config);
1035 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1036 extra buffer size argument before the memory read size can be
1037 increased beyond this. */
1038 if (size > get_remote_packet_size ())
1039 size = get_remote_packet_size ();
1044 /* Generic configuration support for packets the stub optionally
1045 supports. Allows the user to specify the use of the packet as well
1046 as allowing GDB to auto-detect support in the remote stub. */
1050 PACKET_SUPPORT_UNKNOWN = 0,
1055 struct packet_config
1059 enum auto_boolean detect;
1060 enum packet_support support;
1063 /* Analyze a packet's return value and update the packet config
1074 update_packet_config (struct packet_config *config)
1076 switch (config->detect)
1078 case AUTO_BOOLEAN_TRUE:
1079 config->support = PACKET_ENABLE;
1081 case AUTO_BOOLEAN_FALSE:
1082 config->support = PACKET_DISABLE;
1084 case AUTO_BOOLEAN_AUTO:
1085 config->support = PACKET_SUPPORT_UNKNOWN;
1091 show_packet_config_cmd (struct packet_config *config)
1093 char *support = "internal-error";
1095 switch (config->support)
1098 support = "enabled";
1100 case PACKET_DISABLE:
1101 support = "disabled";
1103 case PACKET_SUPPORT_UNKNOWN:
1104 support = "unknown";
1107 switch (config->detect)
1109 case AUTO_BOOLEAN_AUTO:
1110 printf_filtered (_("Support for the `%s' packet "
1111 "is auto-detected, currently %s.\n"),
1112 config->name, support);
1114 case AUTO_BOOLEAN_TRUE:
1115 case AUTO_BOOLEAN_FALSE:
1116 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1117 config->name, support);
1123 add_packet_config_cmd (struct packet_config *config, const char *name,
1124 const char *title, int legacy)
1130 config->name = name;
1131 config->title = title;
1132 config->detect = AUTO_BOOLEAN_AUTO;
1133 config->support = PACKET_SUPPORT_UNKNOWN;
1134 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1136 show_doc = xstrprintf ("Show current use of remote "
1137 "protocol `%s' (%s) packet",
1139 /* set/show TITLE-packet {auto,on,off} */
1140 cmd_name = xstrprintf ("%s-packet", title);
1141 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1142 &config->detect, set_doc,
1143 show_doc, NULL, /* help_doc */
1144 set_remote_protocol_packet_cmd,
1145 show_remote_protocol_packet_cmd,
1146 &remote_set_cmdlist, &remote_show_cmdlist);
1147 /* The command code copies the documentation strings. */
1150 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1155 legacy_name = xstrprintf ("%s-packet", name);
1156 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1157 &remote_set_cmdlist);
1158 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1159 &remote_show_cmdlist);
1163 static enum packet_result
1164 packet_check_result (const char *buf)
1168 /* The stub recognized the packet request. Check that the
1169 operation succeeded. */
1171 && isxdigit (buf[1]) && isxdigit (buf[2])
1173 /* "Enn" - definitly an error. */
1174 return PACKET_ERROR;
1176 /* Always treat "E." as an error. This will be used for
1177 more verbose error messages, such as E.memtypes. */
1178 if (buf[0] == 'E' && buf[1] == '.')
1179 return PACKET_ERROR;
1181 /* The packet may or may not be OK. Just assume it is. */
1185 /* The stub does not support the packet. */
1186 return PACKET_UNKNOWN;
1189 static enum packet_result
1190 packet_ok (const char *buf, struct packet_config *config)
1192 enum packet_result result;
1194 result = packet_check_result (buf);
1199 /* The stub recognized the packet request. */
1200 switch (config->support)
1202 case PACKET_SUPPORT_UNKNOWN:
1204 fprintf_unfiltered (gdb_stdlog,
1205 "Packet %s (%s) is supported\n",
1206 config->name, config->title);
1207 config->support = PACKET_ENABLE;
1209 case PACKET_DISABLE:
1210 internal_error (__FILE__, __LINE__,
1211 _("packet_ok: attempt to use a disabled packet"));
1217 case PACKET_UNKNOWN:
1218 /* The stub does not support the packet. */
1219 switch (config->support)
1222 if (config->detect == AUTO_BOOLEAN_AUTO)
1223 /* If the stub previously indicated that the packet was
1224 supported then there is a protocol error.. */
1225 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1226 config->name, config->title);
1228 /* The user set it wrong. */
1229 error (_("Enabled packet %s (%s) not recognized by stub"),
1230 config->name, config->title);
1232 case PACKET_SUPPORT_UNKNOWN:
1234 fprintf_unfiltered (gdb_stdlog,
1235 "Packet %s (%s) is NOT supported\n",
1236 config->name, config->title);
1237 config->support = PACKET_DISABLE;
1239 case PACKET_DISABLE:
1261 PACKET_vFile_pwrite,
1263 PACKET_vFile_unlink,
1264 PACKET_vFile_readlink,
1266 PACKET_qXfer_features,
1267 PACKET_qXfer_libraries,
1268 PACKET_qXfer_libraries_svr4,
1269 PACKET_qXfer_memory_map,
1270 PACKET_qXfer_spu_read,
1271 PACKET_qXfer_spu_write,
1272 PACKET_qXfer_osdata,
1273 PACKET_qXfer_threads,
1274 PACKET_qXfer_statictrace_read,
1275 PACKET_qXfer_traceframe_info,
1281 PACKET_QPassSignals,
1282 PACKET_QProgramSignals,
1283 PACKET_qSearch_memory,
1286 PACKET_QStartNoAckMode,
1288 PACKET_qXfer_siginfo_read,
1289 PACKET_qXfer_siginfo_write,
1291 PACKET_ConditionalTracepoints,
1292 PACKET_ConditionalBreakpoints,
1293 PACKET_BreakpointCommands,
1294 PACKET_FastTracepoints,
1295 PACKET_StaticTracepoints,
1296 PACKET_InstallInTrace,
1299 PACKET_TracepointSource,
1302 PACKET_QDisableRandomization,
1304 PACKET_QTBuffer_size,
1307 PACKET_qXfer_btrace,
1311 static struct packet_config remote_protocol_packets[PACKET_MAX];
1314 set_remote_protocol_packet_cmd (char *args, int from_tty,
1315 struct cmd_list_element *c)
1317 struct packet_config *packet;
1319 for (packet = remote_protocol_packets;
1320 packet < &remote_protocol_packets[PACKET_MAX];
1323 if (&packet->detect == c->var)
1325 update_packet_config (packet);
1329 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1334 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1335 struct cmd_list_element *c,
1338 struct packet_config *packet;
1340 for (packet = remote_protocol_packets;
1341 packet < &remote_protocol_packets[PACKET_MAX];
1344 if (&packet->detect == c->var)
1346 show_packet_config_cmd (packet);
1350 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1354 /* Should we try one of the 'Z' requests? */
1358 Z_PACKET_SOFTWARE_BP,
1359 Z_PACKET_HARDWARE_BP,
1366 /* For compatibility with older distributions. Provide a ``set remote
1367 Z-packet ...'' command that updates all the Z packet types. */
1369 static enum auto_boolean remote_Z_packet_detect;
1372 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1373 struct cmd_list_element *c)
1377 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1379 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1380 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1385 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1386 struct cmd_list_element *c,
1391 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1393 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1397 /* Should we try the 'ThreadInfo' query packet?
1399 This variable (NOT available to the user: auto-detect only!)
1400 determines whether GDB will use the new, simpler "ThreadInfo"
1401 query or the older, more complex syntax for thread queries.
1402 This is an auto-detect variable (set to true at each connect,
1403 and set to false when the target fails to recognize it). */
1405 static int use_threadinfo_query;
1406 static int use_threadextra_query;
1408 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1409 static struct async_signal_handler *sigint_remote_twice_token;
1410 static struct async_signal_handler *sigint_remote_token;
1413 /* Asynchronous signal handle registered as event loop source for
1414 when we have pending events ready to be passed to the core. */
1416 static struct async_event_handler *remote_async_inferior_event_token;
1420 static ptid_t magic_null_ptid;
1421 static ptid_t not_sent_ptid;
1422 static ptid_t any_thread_ptid;
1424 /* These are the threads which we last sent to the remote system. The
1425 TID member will be -1 for all or -2 for not sent yet. */
1427 static ptid_t general_thread;
1428 static ptid_t continue_thread;
1430 /* This is the traceframe which we last selected on the remote system.
1431 It will be -1 if no traceframe is selected. */
1432 static int remote_traceframe_number = -1;
1434 /* Find out if the stub attached to PID (and hence GDB should offer to
1435 detach instead of killing it when bailing out). */
1438 remote_query_attached (int pid)
1440 struct remote_state *rs = get_remote_state ();
1441 size_t size = get_remote_packet_size ();
1443 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1446 if (remote_multi_process_p (rs))
1447 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1449 xsnprintf (rs->buf, size, "qAttached");
1452 getpkt (&rs->buf, &rs->buf_size, 0);
1454 switch (packet_ok (rs->buf,
1455 &remote_protocol_packets[PACKET_qAttached]))
1458 if (strcmp (rs->buf, "1") == 0)
1462 warning (_("Remote failure reply: %s"), rs->buf);
1464 case PACKET_UNKNOWN:
1471 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1472 has been invented by GDB, instead of reported by the target. Since
1473 we can be connected to a remote system before before knowing about
1474 any inferior, mark the target with execution when we find the first
1475 inferior. If ATTACHED is 1, then we had just attached to this
1476 inferior. If it is 0, then we just created this inferior. If it
1477 is -1, then try querying the remote stub to find out if it had
1478 attached to the inferior or not. */
1480 static struct inferior *
1481 remote_add_inferior (int fake_pid_p, int pid, int attached)
1483 struct inferior *inf;
1485 /* Check whether this process we're learning about is to be
1486 considered attached, or if is to be considered to have been
1487 spawned by the stub. */
1489 attached = remote_query_attached (pid);
1491 if (gdbarch_has_global_solist (target_gdbarch ()))
1493 /* If the target shares code across all inferiors, then every
1494 attach adds a new inferior. */
1495 inf = add_inferior (pid);
1497 /* ... and every inferior is bound to the same program space.
1498 However, each inferior may still have its own address
1500 inf->aspace = maybe_new_address_space ();
1501 inf->pspace = current_program_space;
1505 /* In the traditional debugging scenario, there's a 1-1 match
1506 between program/address spaces. We simply bind the inferior
1507 to the program space's address space. */
1508 inf = current_inferior ();
1509 inferior_appeared (inf, pid);
1512 inf->attach_flag = attached;
1513 inf->fake_pid_p = fake_pid_p;
1518 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1519 according to RUNNING. */
1522 remote_add_thread (ptid_t ptid, int running)
1526 set_executing (ptid, running);
1527 set_running (ptid, running);
1530 /* Come here when we learn about a thread id from the remote target.
1531 It may be the first time we hear about such thread, so take the
1532 opportunity to add it to GDB's thread list. In case this is the
1533 first time we're noticing its corresponding inferior, add it to
1534 GDB's inferior list as well. */
1537 remote_notice_new_inferior (ptid_t currthread, int running)
1539 /* If this is a new thread, add it to GDB's thread list.
1540 If we leave it up to WFI to do this, bad things will happen. */
1542 if (in_thread_list (currthread) && is_exited (currthread))
1544 /* We're seeing an event on a thread id we knew had exited.
1545 This has to be a new thread reusing the old id. Add it. */
1546 remote_add_thread (currthread, running);
1550 if (!in_thread_list (currthread))
1552 struct inferior *inf = NULL;
1553 int pid = ptid_get_pid (currthread);
1555 if (ptid_is_pid (inferior_ptid)
1556 && pid == ptid_get_pid (inferior_ptid))
1558 /* inferior_ptid has no thread member yet. This can happen
1559 with the vAttach -> remote_wait,"TAAthread:" path if the
1560 stub doesn't support qC. This is the first stop reported
1561 after an attach, so this is the main thread. Update the
1562 ptid in the thread list. */
1563 if (in_thread_list (pid_to_ptid (pid)))
1564 thread_change_ptid (inferior_ptid, currthread);
1567 remote_add_thread (currthread, running);
1568 inferior_ptid = currthread;
1573 if (ptid_equal (magic_null_ptid, inferior_ptid))
1575 /* inferior_ptid is not set yet. This can happen with the
1576 vRun -> remote_wait,"TAAthread:" path if the stub
1577 doesn't support qC. This is the first stop reported
1578 after an attach, so this is the main thread. Update the
1579 ptid in the thread list. */
1580 thread_change_ptid (inferior_ptid, currthread);
1584 /* When connecting to a target remote, or to a target
1585 extended-remote which already was debugging an inferior, we
1586 may not know about it yet. Add it before adding its child
1587 thread, so notifications are emitted in a sensible order. */
1588 if (!in_inferior_list (ptid_get_pid (currthread)))
1590 struct remote_state *rs = get_remote_state ();
1591 int fake_pid_p = !remote_multi_process_p (rs);
1593 inf = remote_add_inferior (fake_pid_p,
1594 ptid_get_pid (currthread), -1);
1597 /* This is really a new thread. Add it. */
1598 remote_add_thread (currthread, running);
1600 /* If we found a new inferior, let the common code do whatever
1601 it needs to with it (e.g., read shared libraries, insert
1604 notice_new_inferior (currthread, running, 0);
1608 /* Return the private thread data, creating it if necessary. */
1610 static struct private_thread_info *
1611 demand_private_info (ptid_t ptid)
1613 struct thread_info *info = find_thread_ptid (ptid);
1619 info->private = xmalloc (sizeof (*(info->private)));
1620 info->private_dtor = free_private_thread_info;
1621 info->private->core = -1;
1622 info->private->extra = 0;
1625 return info->private;
1628 /* Call this function as a result of
1629 1) A halt indication (T packet) containing a thread id
1630 2) A direct query of currthread
1631 3) Successful execution of set thread */
1634 record_currthread (ptid_t currthread)
1636 general_thread = currthread;
1639 static char *last_pass_packet;
1641 /* If 'QPassSignals' is supported, tell the remote stub what signals
1642 it can simply pass through to the inferior without reporting. */
1645 remote_pass_signals (int numsigs, unsigned char *pass_signals)
1647 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1649 char *pass_packet, *p;
1652 gdb_assert (numsigs < 256);
1653 for (i = 0; i < numsigs; i++)
1655 if (pass_signals[i])
1658 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1659 strcpy (pass_packet, "QPassSignals:");
1660 p = pass_packet + strlen (pass_packet);
1661 for (i = 0; i < numsigs; i++)
1663 if (pass_signals[i])
1666 *p++ = tohex (i >> 4);
1667 *p++ = tohex (i & 15);
1676 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1678 struct remote_state *rs = get_remote_state ();
1679 char *buf = rs->buf;
1681 putpkt (pass_packet);
1682 getpkt (&rs->buf, &rs->buf_size, 0);
1683 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1684 if (last_pass_packet)
1685 xfree (last_pass_packet);
1686 last_pass_packet = pass_packet;
1689 xfree (pass_packet);
1693 /* The last QProgramSignals packet sent to the target. We bypass
1694 sending a new program signals list down to the target if the new
1695 packet is exactly the same as the last we sent. IOW, we only let
1696 the target know about program signals list changes. */
1698 static char *last_program_signals_packet;
1700 /* If 'QProgramSignals' is supported, tell the remote stub what
1701 signals it should pass through to the inferior when detaching. */
1704 remote_program_signals (int numsigs, unsigned char *signals)
1706 if (remote_protocol_packets[PACKET_QProgramSignals].support != PACKET_DISABLE)
1711 gdb_assert (numsigs < 256);
1712 for (i = 0; i < numsigs; i++)
1717 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1718 strcpy (packet, "QProgramSignals:");
1719 p = packet + strlen (packet);
1720 for (i = 0; i < numsigs; i++)
1722 if (signal_pass_state (i))
1725 *p++ = tohex (i >> 4);
1726 *p++ = tohex (i & 15);
1735 if (!last_program_signals_packet
1736 || strcmp (last_program_signals_packet, packet) != 0)
1738 struct remote_state *rs = get_remote_state ();
1739 char *buf = rs->buf;
1742 getpkt (&rs->buf, &rs->buf_size, 0);
1743 packet_ok (buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1744 xfree (last_program_signals_packet);
1745 last_program_signals_packet = packet;
1752 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1753 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1754 thread. If GEN is set, set the general thread, if not, then set
1755 the step/continue thread. */
1757 set_thread (struct ptid ptid, int gen)
1759 struct remote_state *rs = get_remote_state ();
1760 ptid_t state = gen ? general_thread : continue_thread;
1761 char *buf = rs->buf;
1762 char *endbuf = rs->buf + get_remote_packet_size ();
1764 if (ptid_equal (state, ptid))
1768 *buf++ = gen ? 'g' : 'c';
1769 if (ptid_equal (ptid, magic_null_ptid))
1770 xsnprintf (buf, endbuf - buf, "0");
1771 else if (ptid_equal (ptid, any_thread_ptid))
1772 xsnprintf (buf, endbuf - buf, "0");
1773 else if (ptid_equal (ptid, minus_one_ptid))
1774 xsnprintf (buf, endbuf - buf, "-1");
1776 write_ptid (buf, endbuf, ptid);
1778 getpkt (&rs->buf, &rs->buf_size, 0);
1780 general_thread = ptid;
1782 continue_thread = ptid;
1786 set_general_thread (struct ptid ptid)
1788 set_thread (ptid, 1);
1792 set_continue_thread (struct ptid ptid)
1794 set_thread (ptid, 0);
1797 /* Change the remote current process. Which thread within the process
1798 ends up selected isn't important, as long as it is the same process
1799 as what INFERIOR_PTID points to.
1801 This comes from that fact that there is no explicit notion of
1802 "selected process" in the protocol. The selected process for
1803 general operations is the process the selected general thread
1807 set_general_process (void)
1809 struct remote_state *rs = get_remote_state ();
1811 /* If the remote can't handle multiple processes, don't bother. */
1812 if (!rs->extended || !remote_multi_process_p (rs))
1815 /* We only need to change the remote current thread if it's pointing
1816 at some other process. */
1817 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1818 set_general_thread (inferior_ptid);
1822 /* Return nonzero if the thread PTID is still alive on the remote
1826 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1828 struct remote_state *rs = get_remote_state ();
1831 if (ptid_equal (ptid, magic_null_ptid))
1832 /* The main thread is always alive. */
1835 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1836 /* The main thread is always alive. This can happen after a
1837 vAttach, if the remote side doesn't support
1842 endp = rs->buf + get_remote_packet_size ();
1845 write_ptid (p, endp, ptid);
1848 getpkt (&rs->buf, &rs->buf_size, 0);
1849 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1852 /* About these extended threadlist and threadinfo packets. They are
1853 variable length packets but, the fields within them are often fixed
1854 length. They are redundent enough to send over UDP as is the
1855 remote protocol in general. There is a matching unit test module
1858 #define OPAQUETHREADBYTES 8
1860 /* a 64 bit opaque identifier */
1861 typedef unsigned char threadref[OPAQUETHREADBYTES];
1863 /* WARNING: This threadref data structure comes from the remote O.S.,
1864 libstub protocol encoding, and remote.c. It is not particularly
1867 /* Right now, the internal structure is int. We want it to be bigger.
1868 Plan to fix this. */
1870 typedef int gdb_threadref; /* Internal GDB thread reference. */
1872 /* gdb_ext_thread_info is an internal GDB data structure which is
1873 equivalent to the reply of the remote threadinfo packet. */
1875 struct gdb_ext_thread_info
1877 threadref threadid; /* External form of thread reference. */
1878 int active; /* Has state interesting to GDB?
1880 char display[256]; /* Brief state display, name,
1881 blocked/suspended. */
1882 char shortname[32]; /* To be used to name threads. */
1883 char more_display[256]; /* Long info, statistics, queue depth,
1887 /* The volume of remote transfers can be limited by submitting
1888 a mask containing bits specifying the desired information.
1889 Use a union of these values as the 'selection' parameter to
1890 get_thread_info. FIXME: Make these TAG names more thread specific. */
1892 #define TAG_THREADID 1
1893 #define TAG_EXISTS 2
1894 #define TAG_DISPLAY 4
1895 #define TAG_THREADNAME 8
1896 #define TAG_MOREDISPLAY 16
1898 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1900 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1902 static char *unpack_nibble (char *buf, int *val);
1904 static char *pack_nibble (char *buf, int nibble);
1906 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1908 static char *unpack_byte (char *buf, int *value);
1910 static char *pack_int (char *buf, int value);
1912 static char *unpack_int (char *buf, int *value);
1914 static char *unpack_string (char *src, char *dest, int length);
1916 static char *pack_threadid (char *pkt, threadref *id);
1918 static char *unpack_threadid (char *inbuf, threadref *id);
1920 void int_to_threadref (threadref *id, int value);
1922 static int threadref_to_int (threadref *ref);
1924 static void copy_threadref (threadref *dest, threadref *src);
1926 static int threadmatch (threadref *dest, threadref *src);
1928 static char *pack_threadinfo_request (char *pkt, int mode,
1931 static int remote_unpack_thread_info_response (char *pkt,
1932 threadref *expectedref,
1933 struct gdb_ext_thread_info
1937 static int remote_get_threadinfo (threadref *threadid,
1938 int fieldset, /*TAG mask */
1939 struct gdb_ext_thread_info *info);
1941 static char *pack_threadlist_request (char *pkt, int startflag,
1943 threadref *nextthread);
1945 static int parse_threadlist_response (char *pkt,
1947 threadref *original_echo,
1948 threadref *resultlist,
1951 static int remote_get_threadlist (int startflag,
1952 threadref *nextthread,
1956 threadref *threadlist);
1958 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1960 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1961 void *context, int looplimit);
1963 static int remote_newthread_step (threadref *ref, void *context);
1966 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1967 buffer we're allowed to write to. Returns
1968 BUF+CHARACTERS_WRITTEN. */
1971 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1974 struct remote_state *rs = get_remote_state ();
1976 if (remote_multi_process_p (rs))
1978 pid = ptid_get_pid (ptid);
1980 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1982 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1984 tid = ptid_get_tid (ptid);
1986 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1988 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1993 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1994 passed the last parsed char. Returns null_ptid on error. */
1997 read_ptid (char *buf, char **obuf)
2001 ULONGEST pid = 0, tid = 0;
2005 /* Multi-process ptid. */
2006 pp = unpack_varlen_hex (p + 1, &pid);
2008 error (_("invalid remote ptid: %s"), p);
2011 pp = unpack_varlen_hex (p + 1, &tid);
2014 return ptid_build (pid, 0, tid);
2017 /* No multi-process. Just a tid. */
2018 pp = unpack_varlen_hex (p, &tid);
2020 /* Since the stub is not sending a process id, then default to
2021 what's in inferior_ptid, unless it's null at this point. If so,
2022 then since there's no way to know the pid of the reported
2023 threads, use the magic number. */
2024 if (ptid_equal (inferior_ptid, null_ptid))
2025 pid = ptid_get_pid (magic_null_ptid);
2027 pid = ptid_get_pid (inferior_ptid);
2031 return ptid_build (pid, 0, tid);
2034 /* Encode 64 bits in 16 chars of hex. */
2036 static const char hexchars[] = "0123456789abcdef";
2039 ishex (int ch, int *val)
2041 if ((ch >= 'a') && (ch <= 'f'))
2043 *val = ch - 'a' + 10;
2046 if ((ch >= 'A') && (ch <= 'F'))
2048 *val = ch - 'A' + 10;
2051 if ((ch >= '0') && (ch <= '9'))
2062 if (ch >= 'a' && ch <= 'f')
2063 return ch - 'a' + 10;
2064 if (ch >= '0' && ch <= '9')
2066 if (ch >= 'A' && ch <= 'F')
2067 return ch - 'A' + 10;
2072 stub_unpack_int (char *buff, int fieldlength)
2079 nibble = stubhex (*buff++);
2083 retval = retval << 4;
2089 unpack_varlen_hex (char *buff, /* packet to parse */
2093 ULONGEST retval = 0;
2095 while (ishex (*buff, &nibble))
2098 retval = retval << 4;
2099 retval |= nibble & 0x0f;
2106 unpack_nibble (char *buf, int *val)
2108 *val = fromhex (*buf++);
2113 pack_nibble (char *buf, int nibble)
2115 *buf++ = hexchars[(nibble & 0x0f)];
2120 pack_hex_byte (char *pkt, int byte)
2122 *pkt++ = hexchars[(byte >> 4) & 0xf];
2123 *pkt++ = hexchars[(byte & 0xf)];
2128 unpack_byte (char *buf, int *value)
2130 *value = stub_unpack_int (buf, 2);
2135 pack_int (char *buf, int value)
2137 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2138 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2139 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2140 buf = pack_hex_byte (buf, (value & 0xff));
2145 unpack_int (char *buf, int *value)
2147 *value = stub_unpack_int (buf, 8);
2151 #if 0 /* Currently unused, uncomment when needed. */
2152 static char *pack_string (char *pkt, char *string);
2155 pack_string (char *pkt, char *string)
2160 len = strlen (string);
2162 len = 200; /* Bigger than most GDB packets, junk??? */
2163 pkt = pack_hex_byte (pkt, len);
2167 if ((ch == '\0') || (ch == '#'))
2168 ch = '*'; /* Protect encapsulation. */
2173 #endif /* 0 (unused) */
2176 unpack_string (char *src, char *dest, int length)
2185 pack_threadid (char *pkt, threadref *id)
2188 unsigned char *altid;
2190 altid = (unsigned char *) id;
2191 limit = pkt + BUF_THREAD_ID_SIZE;
2193 pkt = pack_hex_byte (pkt, *altid++);
2199 unpack_threadid (char *inbuf, threadref *id)
2202 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2205 altref = (char *) id;
2207 while (inbuf < limit)
2209 x = stubhex (*inbuf++);
2210 y = stubhex (*inbuf++);
2211 *altref++ = (x << 4) | y;
2216 /* Externally, threadrefs are 64 bits but internally, they are still
2217 ints. This is due to a mismatch of specifications. We would like
2218 to use 64bit thread references internally. This is an adapter
2222 int_to_threadref (threadref *id, int value)
2224 unsigned char *scan;
2226 scan = (unsigned char *) id;
2232 *scan++ = (value >> 24) & 0xff;
2233 *scan++ = (value >> 16) & 0xff;
2234 *scan++ = (value >> 8) & 0xff;
2235 *scan++ = (value & 0xff);
2239 threadref_to_int (threadref *ref)
2242 unsigned char *scan;
2248 value = (value << 8) | ((*scan++) & 0xff);
2253 copy_threadref (threadref *dest, threadref *src)
2256 unsigned char *csrc, *cdest;
2258 csrc = (unsigned char *) src;
2259 cdest = (unsigned char *) dest;
2266 threadmatch (threadref *dest, threadref *src)
2268 /* Things are broken right now, so just assume we got a match. */
2270 unsigned char *srcp, *destp;
2272 srcp = (char *) src;
2273 destp = (char *) dest;
2277 result &= (*srcp++ == *destp++) ? 1 : 0;
2284 threadid:1, # always request threadid
2291 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2294 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2296 *pkt++ = 'q'; /* Info Query */
2297 *pkt++ = 'P'; /* process or thread info */
2298 pkt = pack_int (pkt, mode); /* mode */
2299 pkt = pack_threadid (pkt, id); /* threadid */
2300 *pkt = '\0'; /* terminate */
2304 /* These values tag the fields in a thread info response packet. */
2305 /* Tagging the fields allows us to request specific fields and to
2306 add more fields as time goes by. */
2308 #define TAG_THREADID 1 /* Echo the thread identifier. */
2309 #define TAG_EXISTS 2 /* Is this process defined enough to
2310 fetch registers and its stack? */
2311 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2312 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2313 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2317 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2318 struct gdb_ext_thread_info *info)
2320 struct remote_state *rs = get_remote_state ();
2324 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2327 /* info->threadid = 0; FIXME: implement zero_threadref. */
2329 info->display[0] = '\0';
2330 info->shortname[0] = '\0';
2331 info->more_display[0] = '\0';
2333 /* Assume the characters indicating the packet type have been
2335 pkt = unpack_int (pkt, &mask); /* arg mask */
2336 pkt = unpack_threadid (pkt, &ref);
2339 warning (_("Incomplete response to threadinfo request."));
2340 if (!threadmatch (&ref, expectedref))
2341 { /* This is an answer to a different request. */
2342 warning (_("ERROR RMT Thread info mismatch."));
2345 copy_threadref (&info->threadid, &ref);
2347 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2349 /* Packets are terminated with nulls. */
2350 while ((pkt < limit) && mask && *pkt)
2352 pkt = unpack_int (pkt, &tag); /* tag */
2353 pkt = unpack_byte (pkt, &length); /* length */
2354 if (!(tag & mask)) /* Tags out of synch with mask. */
2356 warning (_("ERROR RMT: threadinfo tag mismatch."));
2360 if (tag == TAG_THREADID)
2364 warning (_("ERROR RMT: length of threadid is not 16."));
2368 pkt = unpack_threadid (pkt, &ref);
2369 mask = mask & ~TAG_THREADID;
2372 if (tag == TAG_EXISTS)
2374 info->active = stub_unpack_int (pkt, length);
2376 mask = mask & ~(TAG_EXISTS);
2379 warning (_("ERROR RMT: 'exists' length too long."));
2385 if (tag == TAG_THREADNAME)
2387 pkt = unpack_string (pkt, &info->shortname[0], length);
2388 mask = mask & ~TAG_THREADNAME;
2391 if (tag == TAG_DISPLAY)
2393 pkt = unpack_string (pkt, &info->display[0], length);
2394 mask = mask & ~TAG_DISPLAY;
2397 if (tag == TAG_MOREDISPLAY)
2399 pkt = unpack_string (pkt, &info->more_display[0], length);
2400 mask = mask & ~TAG_MOREDISPLAY;
2403 warning (_("ERROR RMT: unknown thread info tag."));
2404 break; /* Not a tag we know about. */
2410 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2411 struct gdb_ext_thread_info *info)
2413 struct remote_state *rs = get_remote_state ();
2416 pack_threadinfo_request (rs->buf, fieldset, threadid);
2418 getpkt (&rs->buf, &rs->buf_size, 0);
2420 if (rs->buf[0] == '\0')
2423 result = remote_unpack_thread_info_response (rs->buf + 2,
2428 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2431 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2432 threadref *nextthread)
2434 *pkt++ = 'q'; /* info query packet */
2435 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2436 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2437 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2438 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2443 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2446 parse_threadlist_response (char *pkt, int result_limit,
2447 threadref *original_echo, threadref *resultlist,
2450 struct remote_state *rs = get_remote_state ();
2452 int count, resultcount, done;
2455 /* Assume the 'q' and 'M chars have been stripped. */
2456 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2457 /* done parse past here */
2458 pkt = unpack_byte (pkt, &count); /* count field */
2459 pkt = unpack_nibble (pkt, &done);
2460 /* The first threadid is the argument threadid. */
2461 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2462 while ((count-- > 0) && (pkt < limit))
2464 pkt = unpack_threadid (pkt, resultlist++);
2465 if (resultcount++ >= result_limit)
2474 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2475 int *done, int *result_count, threadref *threadlist)
2477 struct remote_state *rs = get_remote_state ();
2478 static threadref echo_nextthread;
2481 /* Trancate result limit to be smaller than the packet size. */
2482 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2483 >= get_remote_packet_size ())
2484 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2486 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2488 getpkt (&rs->buf, &rs->buf_size, 0);
2490 if (*rs->buf == '\0')
2494 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2497 if (!threadmatch (&echo_nextthread, nextthread))
2499 /* FIXME: This is a good reason to drop the packet. */
2500 /* Possably, there is a duplicate response. */
2502 retransmit immediatly - race conditions
2503 retransmit after timeout - yes
2505 wait for packet, then exit
2507 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2508 return 0; /* I choose simply exiting. */
2510 if (*result_count <= 0)
2514 warning (_("RMT ERROR : failed to get remote thread list."));
2517 return result; /* break; */
2519 if (*result_count > result_limit)
2522 warning (_("RMT ERROR: threadlist response longer than requested."));
2528 /* This is the interface between remote and threads, remotes upper
2531 /* remote_find_new_threads retrieves the thread list and for each
2532 thread in the list, looks up the thread in GDB's internal list,
2533 adding the thread if it does not already exist. This involves
2534 getting partial thread lists from the remote target so, polling the
2535 quit_flag is required. */
2538 /* About this many threadisds fit in a packet. */
2540 #define MAXTHREADLISTRESULTS 32
2543 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2546 int done, i, result_count;
2550 static threadref nextthread;
2551 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2556 if (loopcount++ > looplimit)
2559 warning (_("Remote fetch threadlist -infinite loop-."));
2562 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2563 &done, &result_count, resultthreadlist))
2568 /* Clear for later iterations. */
2570 /* Setup to resume next batch of thread references, set nextthread. */
2571 if (result_count >= 1)
2572 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2574 while (result_count--)
2575 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2582 remote_newthread_step (threadref *ref, void *context)
2584 int pid = ptid_get_pid (inferior_ptid);
2585 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2587 if (!in_thread_list (ptid))
2589 return 1; /* continue iterator */
2592 #define CRAZY_MAX_THREADS 1000
2595 remote_current_thread (ptid_t oldpid)
2597 struct remote_state *rs = get_remote_state ();
2600 getpkt (&rs->buf, &rs->buf_size, 0);
2601 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2602 return read_ptid (&rs->buf[2], NULL);
2607 /* Find new threads for info threads command.
2608 * Original version, using John Metzler's thread protocol.
2612 remote_find_new_threads (void)
2614 remote_threadlist_iterator (remote_newthread_step, 0,
2618 #if defined(HAVE_LIBEXPAT)
2620 typedef struct thread_item
2626 DEF_VEC_O(thread_item_t);
2628 struct threads_parsing_context
2630 VEC (thread_item_t) *items;
2634 start_thread (struct gdb_xml_parser *parser,
2635 const struct gdb_xml_element *element,
2636 void *user_data, VEC(gdb_xml_value_s) *attributes)
2638 struct threads_parsing_context *data = user_data;
2640 struct thread_item item;
2642 struct gdb_xml_value *attr;
2644 id = xml_find_attribute (attributes, "id")->value;
2645 item.ptid = read_ptid (id, NULL);
2647 attr = xml_find_attribute (attributes, "core");
2649 item.core = *(ULONGEST *) attr->value;
2655 VEC_safe_push (thread_item_t, data->items, &item);
2659 end_thread (struct gdb_xml_parser *parser,
2660 const struct gdb_xml_element *element,
2661 void *user_data, const char *body_text)
2663 struct threads_parsing_context *data = user_data;
2665 if (body_text && *body_text)
2666 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2669 const struct gdb_xml_attribute thread_attributes[] = {
2670 { "id", GDB_XML_AF_NONE, NULL, NULL },
2671 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2672 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2675 const struct gdb_xml_element thread_children[] = {
2676 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2679 const struct gdb_xml_element threads_children[] = {
2680 { "thread", thread_attributes, thread_children,
2681 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2682 start_thread, end_thread },
2683 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2686 const struct gdb_xml_element threads_elements[] = {
2687 { "threads", NULL, threads_children,
2688 GDB_XML_EF_NONE, NULL, NULL },
2689 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2692 /* Discard the contents of the constructed thread info context. */
2695 clear_threads_parsing_context (void *p)
2697 struct threads_parsing_context *context = p;
2699 struct thread_item *item;
2701 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2702 xfree (item->extra);
2704 VEC_free (thread_item_t, context->items);
2710 * Find all threads for info threads command.
2711 * Uses new thread protocol contributed by Cisco.
2712 * Falls back and attempts to use the older method (above)
2713 * if the target doesn't respond to the new method.
2717 remote_threads_info (struct target_ops *ops)
2719 struct remote_state *rs = get_remote_state ();
2723 if (remote_desc == 0) /* paranoia */
2724 error (_("Command can only be used when connected to the remote target."));
2726 #if defined(HAVE_LIBEXPAT)
2727 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2729 char *xml = target_read_stralloc (¤t_target,
2730 TARGET_OBJECT_THREADS, NULL);
2732 struct cleanup *back_to = make_cleanup (xfree, xml);
2736 struct threads_parsing_context context;
2738 context.items = NULL;
2739 make_cleanup (clear_threads_parsing_context, &context);
2741 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2742 threads_elements, xml, &context) == 0)
2745 struct thread_item *item;
2748 VEC_iterate (thread_item_t, context.items, i, item);
2751 if (!ptid_equal (item->ptid, null_ptid))
2753 struct private_thread_info *info;
2754 /* In non-stop mode, we assume new found threads
2755 are running until proven otherwise with a
2756 stop reply. In all-stop, we can only get
2757 here if all threads are stopped. */
2758 int running = non_stop ? 1 : 0;
2760 remote_notice_new_inferior (item->ptid, running);
2762 info = demand_private_info (item->ptid);
2763 info->core = item->core;
2764 info->extra = item->extra;
2771 do_cleanups (back_to);
2776 if (use_threadinfo_query)
2778 putpkt ("qfThreadInfo");
2779 getpkt (&rs->buf, &rs->buf_size, 0);
2781 if (bufp[0] != '\0') /* q packet recognized */
2783 struct cleanup *old_chain;
2786 /* remote_notice_new_inferior (in the loop below) may make
2787 new RSP calls, which clobber rs->buf. Work with a
2789 bufp = saved_reply = xstrdup (rs->buf);
2790 old_chain = make_cleanup (free_current_contents, &saved_reply);
2792 while (*bufp++ == 'm') /* reply contains one or more TID */
2796 new_thread = read_ptid (bufp, &bufp);
2797 if (!ptid_equal (new_thread, null_ptid))
2799 /* In non-stop mode, we assume new found threads
2800 are running until proven otherwise with a
2801 stop reply. In all-stop, we can only get
2802 here if all threads are stopped. */
2803 int running = non_stop ? 1 : 0;
2805 remote_notice_new_inferior (new_thread, running);
2808 while (*bufp++ == ','); /* comma-separated list */
2809 free_current_contents (&saved_reply);
2810 putpkt ("qsThreadInfo");
2811 getpkt (&rs->buf, &rs->buf_size, 0);
2812 bufp = saved_reply = xstrdup (rs->buf);
2814 do_cleanups (old_chain);
2819 /* Only qfThreadInfo is supported in non-stop mode. */
2823 /* Else fall back to old method based on jmetzler protocol. */
2824 use_threadinfo_query = 0;
2825 remote_find_new_threads ();
2830 * Collect a descriptive string about the given thread.
2831 * The target may say anything it wants to about the thread
2832 * (typically info about its blocked / runnable state, name, etc.).
2833 * This string will appear in the info threads display.
2835 * Optional: targets are not required to implement this function.
2839 remote_threads_extra_info (struct thread_info *tp)
2841 struct remote_state *rs = get_remote_state ();
2845 struct gdb_ext_thread_info threadinfo;
2846 static char display_buf[100]; /* arbitrary... */
2847 int n = 0; /* position in display_buf */
2849 if (remote_desc == 0) /* paranoia */
2850 internal_error (__FILE__, __LINE__,
2851 _("remote_threads_extra_info"));
2853 if (ptid_equal (tp->ptid, magic_null_ptid)
2854 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2855 /* This is the main thread which was added by GDB. The remote
2856 server doesn't know about it. */
2859 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2861 struct thread_info *info = find_thread_ptid (tp->ptid);
2863 if (info && info->private)
2864 return info->private->extra;
2869 if (use_threadextra_query)
2872 char *endb = rs->buf + get_remote_packet_size ();
2874 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2876 write_ptid (b, endb, tp->ptid);
2879 getpkt (&rs->buf, &rs->buf_size, 0);
2880 if (rs->buf[0] != 0)
2882 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2883 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2884 display_buf [result] = '\0';
2889 /* If the above query fails, fall back to the old method. */
2890 use_threadextra_query = 0;
2891 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2892 | TAG_MOREDISPLAY | TAG_DISPLAY;
2893 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2894 if (remote_get_threadinfo (&id, set, &threadinfo))
2895 if (threadinfo.active)
2897 if (*threadinfo.shortname)
2898 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2899 " Name: %s,", threadinfo.shortname);
2900 if (*threadinfo.display)
2901 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2902 " State: %s,", threadinfo.display);
2903 if (*threadinfo.more_display)
2904 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2905 " Priority: %s", threadinfo.more_display);
2909 /* For purely cosmetic reasons, clear up trailing commas. */
2910 if (',' == display_buf[n-1])
2911 display_buf[n-1] = ' ';
2920 remote_static_tracepoint_marker_at (CORE_ADDR addr,
2921 struct static_tracepoint_marker *marker)
2923 struct remote_state *rs = get_remote_state ();
2926 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
2928 p += hexnumstr (p, addr);
2930 getpkt (&rs->buf, &rs->buf_size, 0);
2934 error (_("Remote failure reply: %s"), p);
2938 parse_static_tracepoint_marker_definition (p, &p, marker);
2945 static VEC(static_tracepoint_marker_p) *
2946 remote_static_tracepoint_markers_by_strid (const char *strid)
2948 struct remote_state *rs = get_remote_state ();
2949 VEC(static_tracepoint_marker_p) *markers = NULL;
2950 struct static_tracepoint_marker *marker = NULL;
2951 struct cleanup *old_chain;
2954 /* Ask for a first packet of static tracepoint marker
2957 getpkt (&rs->buf, &rs->buf_size, 0);
2960 error (_("Remote failure reply: %s"), p);
2962 old_chain = make_cleanup (free_current_marker, &marker);
2967 marker = XCNEW (struct static_tracepoint_marker);
2971 parse_static_tracepoint_marker_definition (p, &p, marker);
2973 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
2975 VEC_safe_push (static_tracepoint_marker_p,
2981 release_static_tracepoint_marker (marker);
2982 memset (marker, 0, sizeof (*marker));
2985 while (*p++ == ','); /* comma-separated list */
2986 /* Ask for another packet of static tracepoint definition. */
2988 getpkt (&rs->buf, &rs->buf_size, 0);
2992 do_cleanups (old_chain);
2997 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3000 remote_get_ada_task_ptid (long lwp, long thread)
3002 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
3006 /* Restart the remote side; this is an extended protocol operation. */
3009 extended_remote_restart (void)
3011 struct remote_state *rs = get_remote_state ();
3013 /* Send the restart command; for reasons I don't understand the
3014 remote side really expects a number after the "R". */
3015 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3018 remote_fileio_reset ();
3021 /* Clean up connection to a remote debugger. */
3026 if (remote_desc == NULL)
3027 return; /* already closed */
3029 /* Make sure we leave stdin registered in the event loop, and we
3030 don't leave the async SIGINT signal handler installed. */
3031 remote_terminal_ours ();
3033 serial_close (remote_desc);
3036 /* We don't have a connection to the remote stub anymore. Get rid
3037 of all the inferiors and their threads we were controlling.
3038 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3039 will be unable to find the thread corresponding to (pid, 0, 0). */
3040 inferior_ptid = null_ptid;
3041 discard_all_inferiors ();
3043 /* Stop replies may from inferiors which are still unknown to GDB.
3044 We are closing the remote target, so we should discard
3045 everything, including the stop replies from GDB-unknown
3047 discard_pending_stop_replies (NULL);
3049 if (remote_async_inferior_event_token)
3050 delete_async_event_handler (&remote_async_inferior_event_token);
3052 remote_notif_unregister_async_event_handler ();
3055 /* Query the remote side for the text, data and bss offsets. */
3060 struct remote_state *rs = get_remote_state ();
3063 int lose, num_segments = 0, do_sections, do_segments;
3064 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3065 struct section_offsets *offs;
3066 struct symfile_segment_data *data;
3068 if (symfile_objfile == NULL)
3071 putpkt ("qOffsets");
3072 getpkt (&rs->buf, &rs->buf_size, 0);
3075 if (buf[0] == '\000')
3076 return; /* Return silently. Stub doesn't support
3080 warning (_("Remote failure reply: %s"), buf);
3084 /* Pick up each field in turn. This used to be done with scanf, but
3085 scanf will make trouble if CORE_ADDR size doesn't match
3086 conversion directives correctly. The following code will work
3087 with any size of CORE_ADDR. */
3088 text_addr = data_addr = bss_addr = 0;
3092 if (strncmp (ptr, "Text=", 5) == 0)
3095 /* Don't use strtol, could lose on big values. */
3096 while (*ptr && *ptr != ';')
3097 text_addr = (text_addr << 4) + fromhex (*ptr++);
3099 if (strncmp (ptr, ";Data=", 6) == 0)
3102 while (*ptr && *ptr != ';')
3103 data_addr = (data_addr << 4) + fromhex (*ptr++);
3108 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3111 while (*ptr && *ptr != ';')
3112 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3114 if (bss_addr != data_addr)
3115 warning (_("Target reported unsupported offsets: %s"), buf);
3120 else if (strncmp (ptr, "TextSeg=", 8) == 0)
3123 /* Don't use strtol, could lose on big values. */
3124 while (*ptr && *ptr != ';')
3125 text_addr = (text_addr << 4) + fromhex (*ptr++);
3128 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3131 while (*ptr && *ptr != ';')
3132 data_addr = (data_addr << 4) + fromhex (*ptr++);
3140 error (_("Malformed response to offset query, %s"), buf);
3141 else if (*ptr != '\0')
3142 warning (_("Target reported unsupported offsets: %s"), buf);
3144 offs = ((struct section_offsets *)
3145 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3146 memcpy (offs, symfile_objfile->section_offsets,
3147 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3149 data = get_symfile_segment_data (symfile_objfile->obfd);
3150 do_segments = (data != NULL);
3151 do_sections = num_segments == 0;
3153 if (num_segments > 0)
3155 segments[0] = text_addr;
3156 segments[1] = data_addr;
3158 /* If we have two segments, we can still try to relocate everything
3159 by assuming that the .text and .data offsets apply to the whole
3160 text and data segments. Convert the offsets given in the packet
3161 to base addresses for symfile_map_offsets_to_segments. */
3162 else if (data && data->num_segments == 2)
3164 segments[0] = data->segment_bases[0] + text_addr;
3165 segments[1] = data->segment_bases[1] + data_addr;
3168 /* If the object file has only one segment, assume that it is text
3169 rather than data; main programs with no writable data are rare,
3170 but programs with no code are useless. Of course the code might
3171 have ended up in the data segment... to detect that we would need
3172 the permissions here. */
3173 else if (data && data->num_segments == 1)
3175 segments[0] = data->segment_bases[0] + text_addr;
3178 /* There's no way to relocate by segment. */
3184 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3185 offs, num_segments, segments);
3187 if (ret == 0 && !do_sections)
3188 error (_("Can not handle qOffsets TextSeg "
3189 "response with this symbol file"));
3196 free_symfile_segment_data (data);
3200 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3202 /* This is a temporary kludge to force data and bss to use the
3203 same offsets because that's what nlmconv does now. The real
3204 solution requires changes to the stub and remote.c that I
3205 don't have time to do right now. */
3207 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3208 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3211 objfile_relocate (symfile_objfile, offs);
3214 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3215 threads we know are stopped already. This is used during the
3216 initial remote connection in non-stop mode --- threads that are
3217 reported as already being stopped are left stopped. */
3220 set_stop_requested_callback (struct thread_info *thread, void *data)
3222 /* If we have a stop reply for this thread, it must be stopped. */
3223 if (peek_stop_reply (thread->ptid))
3224 set_stop_requested (thread->ptid, 1);
3229 /* Send interrupt_sequence to remote target. */
3231 send_interrupt_sequence (void)
3233 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3234 remote_serial_write ("\x03", 1);
3235 else if (interrupt_sequence_mode == interrupt_sequence_break)
3236 serial_send_break (remote_desc);
3237 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3239 serial_send_break (remote_desc);
3240 remote_serial_write ("g", 1);
3243 internal_error (__FILE__, __LINE__,
3244 _("Invalid value for interrupt_sequence_mode: %s."),
3245 interrupt_sequence_mode);
3249 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3250 and extract the PTID. Returns NULL_PTID if not found. */
3253 stop_reply_extract_thread (char *stop_reply)
3255 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3259 /* Txx r:val ; r:val (...) */
3262 /* Look for "register" named "thread". */
3267 p1 = strchr (p, ':');
3271 if (strncmp (p, "thread", p1 - p) == 0)
3272 return read_ptid (++p1, &p);
3274 p1 = strchr (p, ';');
3286 /* Query the remote target for which is the current thread/process,
3287 add it to our tables, and update INFERIOR_PTID. The caller is
3288 responsible for setting the state such that the remote end is ready
3289 to return the current thread.
3291 This function is called after handling the '?' or 'vRun' packets,
3292 whose response is a stop reply from which we can also try
3293 extracting the thread. If the target doesn't support the explicit
3294 qC query, we infer the current thread from that stop reply, passed
3295 in in WAIT_STATUS, which may be NULL. */
3298 add_current_inferior_and_thread (char *wait_status)
3300 struct remote_state *rs = get_remote_state ();
3302 ptid_t ptid = null_ptid;
3304 inferior_ptid = null_ptid;
3306 /* Now, if we have thread information, update inferior_ptid. First
3307 if we have a stop reply handy, maybe it's a T stop reply with a
3308 "thread" register we can extract the current thread from. If
3309 not, ask the remote which is the current thread, with qC. The
3310 former method avoids a roundtrip. Note we don't use
3311 remote_parse_stop_reply as that makes use of the target
3312 architecture, which we haven't yet fully determined at this
3314 if (wait_status != NULL)
3315 ptid = stop_reply_extract_thread (wait_status);
3316 if (ptid_equal (ptid, null_ptid))
3317 ptid = remote_current_thread (inferior_ptid);
3319 if (!ptid_equal (ptid, null_ptid))
3321 if (!remote_multi_process_p (rs))
3324 inferior_ptid = ptid;
3328 /* Without this, some commands which require an active target
3329 (such as kill) won't work. This variable serves (at least)
3330 double duty as both the pid of the target process (if it has
3331 such), and as a flag indicating that a target is active. */
3332 inferior_ptid = magic_null_ptid;
3336 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3338 /* Add the main thread. */
3339 add_thread_silent (inferior_ptid);
3343 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3345 struct remote_state *rs = get_remote_state ();
3346 struct packet_config *noack_config;
3347 char *wait_status = NULL;
3349 immediate_quit++; /* Allow user to interrupt it. */
3352 if (interrupt_on_connect)
3353 send_interrupt_sequence ();
3355 /* Ack any packet which the remote side has already sent. */
3356 serial_write (remote_desc, "+", 1);
3358 /* Signal other parts that we're going through the initial setup,
3359 and so things may not be stable yet. */
3360 rs->starting_up = 1;
3362 /* The first packet we send to the target is the optional "supported
3363 packets" request. If the target can answer this, it will tell us
3364 which later probes to skip. */
3365 remote_query_supported ();
3367 /* If the stub wants to get a QAllow, compose one and send it. */
3368 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
3369 remote_set_permissions ();
3371 /* Next, we possibly activate noack mode.
3373 If the QStartNoAckMode packet configuration is set to AUTO,
3374 enable noack mode if the stub reported a wish for it with
3377 If set to TRUE, then enable noack mode even if the stub didn't
3378 report it in qSupported. If the stub doesn't reply OK, the
3379 session ends with an error.
3381 If FALSE, then don't activate noack mode, regardless of what the
3382 stub claimed should be the default with qSupported. */
3384 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3386 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3387 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3388 && noack_config->support == PACKET_ENABLE))
3390 putpkt ("QStartNoAckMode");
3391 getpkt (&rs->buf, &rs->buf_size, 0);
3392 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3398 /* Tell the remote that we are using the extended protocol. */
3400 getpkt (&rs->buf, &rs->buf_size, 0);
3403 /* Let the target know which signals it is allowed to pass down to
3405 update_signals_program_target ();
3407 /* Next, if the target can specify a description, read it. We do
3408 this before anything involving memory or registers. */
3409 target_find_description ();
3411 /* Next, now that we know something about the target, update the
3412 address spaces in the program spaces. */
3413 update_address_spaces ();
3415 /* On OSs where the list of libraries is global to all
3416 processes, we fetch them early. */
3417 if (gdbarch_has_global_solist (target_gdbarch ()))
3418 solib_add (NULL, from_tty, target, auto_solib_add);
3422 if (!rs->non_stop_aware)
3423 error (_("Non-stop mode requested, but remote "
3424 "does not support non-stop"));
3426 putpkt ("QNonStop:1");
3427 getpkt (&rs->buf, &rs->buf_size, 0);
3429 if (strcmp (rs->buf, "OK") != 0)
3430 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3432 /* Find about threads and processes the stub is already
3433 controlling. We default to adding them in the running state.
3434 The '?' query below will then tell us about which threads are
3436 remote_threads_info (target);
3438 else if (rs->non_stop_aware)
3440 /* Don't assume that the stub can operate in all-stop mode.
3441 Request it explicitly. */
3442 putpkt ("QNonStop:0");
3443 getpkt (&rs->buf, &rs->buf_size, 0);
3445 if (strcmp (rs->buf, "OK") != 0)
3446 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3449 /* Check whether the target is running now. */
3451 getpkt (&rs->buf, &rs->buf_size, 0);
3457 struct inferior *inf;
3459 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3462 error (_("The target is not running (try extended-remote?)"));
3464 /* We're connected, but not running. Drop out before we
3465 call start_remote. */
3466 rs->starting_up = 0;
3471 /* Save the reply for later. */
3472 wait_status = alloca (strlen (rs->buf) + 1);
3473 strcpy (wait_status, rs->buf);
3476 /* Let the stub know that we want it to return the thread. */
3477 set_continue_thread (minus_one_ptid);
3479 add_current_inferior_and_thread (wait_status);
3481 /* init_wait_for_inferior should be called before get_offsets in order
3482 to manage `inserted' flag in bp loc in a correct state.
3483 breakpoint_init_inferior, called from init_wait_for_inferior, set
3484 `inserted' flag to 0, while before breakpoint_re_set, called from
3485 start_remote, set `inserted' flag to 1. In the initialization of
3486 inferior, breakpoint_init_inferior should be called first, and then
3487 breakpoint_re_set can be called. If this order is broken, state of
3488 `inserted' flag is wrong, and cause some problems on breakpoint
3490 init_wait_for_inferior ();
3492 get_offsets (); /* Get text, data & bss offsets. */
3494 /* If we could not find a description using qXfer, and we know
3495 how to do it some other way, try again. This is not
3496 supported for non-stop; it could be, but it is tricky if
3497 there are no stopped threads when we connect. */
3498 if (remote_read_description_p (target)
3499 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3501 target_clear_description ();
3502 target_find_description ();
3505 /* Use the previously fetched status. */
3506 gdb_assert (wait_status != NULL);
3507 strcpy (rs->buf, wait_status);
3508 rs->cached_wait_status = 1;
3511 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3515 /* Clear WFI global state. Do this before finding about new
3516 threads and inferiors, and setting the current inferior.
3517 Otherwise we would clear the proceed status of the current
3518 inferior when we want its stop_soon state to be preserved
3519 (see notice_new_inferior). */
3520 init_wait_for_inferior ();
3522 /* In non-stop, we will either get an "OK", meaning that there
3523 are no stopped threads at this time; or, a regular stop
3524 reply. In the latter case, there may be more than one thread
3525 stopped --- we pull them all out using the vStopped
3527 if (strcmp (rs->buf, "OK") != 0)
3529 struct notif_client *notif = ¬if_client_stop;
3531 /* remote_notif_get_pending_replies acks this one, and gets
3533 notif_client_stop.pending_event
3534 = remote_notif_parse (notif, rs->buf);
3535 remote_notif_get_pending_events (notif);
3537 /* Make sure that threads that were stopped remain
3539 iterate_over_threads (set_stop_requested_callback, NULL);
3542 if (target_can_async_p ())
3543 target_async (inferior_event_handler, 0);
3545 if (thread_count () == 0)
3548 error (_("The target is not running (try extended-remote?)"));
3550 /* We're connected, but not running. Drop out before we
3551 call start_remote. */
3552 rs->starting_up = 0;
3556 /* Let the stub know that we want it to return the thread. */
3558 /* Force the stub to choose a thread. */
3559 set_general_thread (null_ptid);
3562 inferior_ptid = remote_current_thread (minus_one_ptid);
3563 if (ptid_equal (inferior_ptid, minus_one_ptid))
3564 error (_("remote didn't report the current thread in non-stop mode"));
3566 get_offsets (); /* Get text, data & bss offsets. */
3568 /* In non-stop mode, any cached wait status will be stored in
3569 the stop reply queue. */
3570 gdb_assert (wait_status == NULL);
3572 /* Report all signals during attach/startup. */
3573 remote_pass_signals (0, NULL);
3576 /* If we connected to a live target, do some additional setup. */
3577 if (target_has_execution)
3579 if (exec_bfd) /* No use without an exec file. */
3580 remote_check_symbols ();
3583 /* Possibly the target has been engaged in a trace run started
3584 previously; find out where things are at. */
3585 if (remote_get_trace_status (current_trace_status ()) != -1)
3587 struct uploaded_tp *uploaded_tps = NULL;
3588 struct uploaded_tsv *uploaded_tsvs = NULL;
3590 if (current_trace_status ()->running)
3591 printf_filtered (_("Trace is already running on the target.\n"));
3593 /* Get trace state variables first, they may be checked when
3594 parsing uploaded commands. */
3596 remote_upload_trace_state_variables (&uploaded_tsvs);
3598 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3600 remote_upload_tracepoints (&uploaded_tps);
3602 merge_uploaded_tracepoints (&uploaded_tps);
3605 /* The thread and inferior lists are now synchronized with the
3606 target, our symbols have been relocated, and we're merged the
3607 target's tracepoints with ours. We're done with basic start
3609 rs->starting_up = 0;
3611 /* If breakpoints are global, insert them now. */
3612 if (gdbarch_has_global_breakpoints (target_gdbarch ())
3613 && breakpoints_always_inserted_mode ())
3614 insert_breakpoints ();
3617 /* Open a connection to a remote debugger.
3618 NAME is the filename used for communication. */
3621 remote_open (char *name, int from_tty)
3623 remote_open_1 (name, from_tty, &remote_ops, 0);
3626 /* Open a connection to a remote debugger using the extended
3627 remote gdb protocol. NAME is the filename used for communication. */
3630 extended_remote_open (char *name, int from_tty)
3632 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3635 /* Generic code for opening a connection to a remote target. */
3638 init_all_packet_configs (void)
3642 for (i = 0; i < PACKET_MAX; i++)
3643 update_packet_config (&remote_protocol_packets[i]);
3646 /* Symbol look-up. */
3649 remote_check_symbols (void)
3651 struct remote_state *rs = get_remote_state ();
3652 char *msg, *reply, *tmp;
3653 struct minimal_symbol *sym;
3656 /* The remote side has no concept of inferiors that aren't running
3657 yet, it only knows about running processes. If we're connected
3658 but our current inferior is not running, we should not invite the
3659 remote target to request symbol lookups related to its
3660 (unrelated) current process. */
3661 if (!target_has_execution)
3664 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
3667 /* Make sure the remote is pointing at the right process. Note
3668 there's no way to select "no process". */
3669 set_general_process ();
3671 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3672 because we need both at the same time. */
3673 msg = alloca (get_remote_packet_size ());
3675 /* Invite target to request symbol lookups. */
3677 putpkt ("qSymbol::");
3678 getpkt (&rs->buf, &rs->buf_size, 0);
3679 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3682 while (strncmp (reply, "qSymbol:", 8) == 0)
3685 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3687 sym = lookup_minimal_symbol (msg, NULL, NULL);
3689 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3692 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3693 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3695 /* If this is a function address, return the start of code
3696 instead of any data function descriptor. */
3697 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3701 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3702 phex_nz (sym_addr, addr_size), &reply[8]);
3706 getpkt (&rs->buf, &rs->buf_size, 0);
3711 static struct serial *
3712 remote_serial_open (char *name)
3714 static int udp_warning = 0;
3716 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3717 of in ser-tcp.c, because it is the remote protocol assuming that the
3718 serial connection is reliable and not the serial connection promising
3720 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3722 warning (_("The remote protocol may be unreliable over UDP.\n"
3723 "Some events may be lost, rendering further debugging "
3728 return serial_open (name);
3731 /* Inform the target of our permission settings. The permission flags
3732 work without this, but if the target knows the settings, it can do
3733 a couple things. First, it can add its own check, to catch cases
3734 that somehow manage to get by the permissions checks in target
3735 methods. Second, if the target is wired to disallow particular
3736 settings (for instance, a system in the field that is not set up to
3737 be able to stop at a breakpoint), it can object to any unavailable
3741 remote_set_permissions (void)
3743 struct remote_state *rs = get_remote_state ();
3745 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3746 "WriteReg:%x;WriteMem:%x;"
3747 "InsertBreak:%x;InsertTrace:%x;"
3748 "InsertFastTrace:%x;Stop:%x",
3749 may_write_registers, may_write_memory,
3750 may_insert_breakpoints, may_insert_tracepoints,
3751 may_insert_fast_tracepoints, may_stop);
3753 getpkt (&rs->buf, &rs->buf_size, 0);
3755 /* If the target didn't like the packet, warn the user. Do not try
3756 to undo the user's settings, that would just be maddening. */
3757 if (strcmp (rs->buf, "OK") != 0)
3758 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3761 /* This type describes each known response to the qSupported
3763 struct protocol_feature
3765 /* The name of this protocol feature. */
3768 /* The default for this protocol feature. */
3769 enum packet_support default_support;
3771 /* The function to call when this feature is reported, or after
3772 qSupported processing if the feature is not supported.
3773 The first argument points to this structure. The second
3774 argument indicates whether the packet requested support be
3775 enabled, disabled, or probed (or the default, if this function
3776 is being called at the end of processing and this feature was
3777 not reported). The third argument may be NULL; if not NULL, it
3778 is a NUL-terminated string taken from the packet following
3779 this feature's name and an equals sign. */
3780 void (*func) (const struct protocol_feature *, enum packet_support,
3783 /* The corresponding packet for this feature. Only used if
3784 FUNC is remote_supported_packet. */
3789 remote_supported_packet (const struct protocol_feature *feature,
3790 enum packet_support support,
3791 const char *argument)
3795 warning (_("Remote qSupported response supplied an unexpected value for"
3796 " \"%s\"."), feature->name);
3800 if (remote_protocol_packets[feature->packet].support
3801 == PACKET_SUPPORT_UNKNOWN)
3802 remote_protocol_packets[feature->packet].support = support;
3806 remote_packet_size (const struct protocol_feature *feature,
3807 enum packet_support support, const char *value)
3809 struct remote_state *rs = get_remote_state ();
3814 if (support != PACKET_ENABLE)
3817 if (value == NULL || *value == '\0')
3819 warning (_("Remote target reported \"%s\" without a size."),
3825 packet_size = strtol (value, &value_end, 16);
3826 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3828 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3829 feature->name, value);
3833 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3835 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3836 packet_size, MAX_REMOTE_PACKET_SIZE);
3837 packet_size = MAX_REMOTE_PACKET_SIZE;
3840 /* Record the new maximum packet size. */
3841 rs->explicit_packet_size = packet_size;
3845 remote_multi_process_feature (const struct protocol_feature *feature,
3846 enum packet_support support, const char *value)
3848 struct remote_state *rs = get_remote_state ();
3850 rs->multi_process_aware = (support == PACKET_ENABLE);
3854 remote_non_stop_feature (const struct protocol_feature *feature,
3855 enum packet_support support, const char *value)
3857 struct remote_state *rs = get_remote_state ();
3859 rs->non_stop_aware = (support == PACKET_ENABLE);
3863 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3864 enum packet_support support,
3867 struct remote_state *rs = get_remote_state ();
3869 rs->cond_tracepoints = (support == PACKET_ENABLE);
3873 remote_cond_breakpoint_feature (const struct protocol_feature *feature,
3874 enum packet_support support,
3877 struct remote_state *rs = get_remote_state ();
3879 rs->cond_breakpoints = (support == PACKET_ENABLE);
3883 remote_breakpoint_commands_feature (const struct protocol_feature *feature,
3884 enum packet_support support,
3887 struct remote_state *rs = get_remote_state ();
3889 rs->breakpoint_commands = (support == PACKET_ENABLE);
3893 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3894 enum packet_support support,
3897 struct remote_state *rs = get_remote_state ();
3899 rs->fast_tracepoints = (support == PACKET_ENABLE);
3903 remote_static_tracepoint_feature (const struct protocol_feature *feature,
3904 enum packet_support support,
3907 struct remote_state *rs = get_remote_state ();
3909 rs->static_tracepoints = (support == PACKET_ENABLE);
3913 remote_install_in_trace_feature (const struct protocol_feature *feature,
3914 enum packet_support support,
3917 struct remote_state *rs = get_remote_state ();
3919 rs->install_in_trace = (support == PACKET_ENABLE);
3923 remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3924 enum packet_support support,
3927 struct remote_state *rs = get_remote_state ();
3929 rs->disconnected_tracing = (support == PACKET_ENABLE);
3933 remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
3934 enum packet_support support,
3937 struct remote_state *rs = get_remote_state ();
3939 rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
3943 remote_string_tracing_feature (const struct protocol_feature *feature,
3944 enum packet_support support,
3947 struct remote_state *rs = get_remote_state ();
3949 rs->string_tracing = (support == PACKET_ENABLE);
3952 static struct protocol_feature remote_protocol_features[] = {
3953 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3954 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3955 PACKET_qXfer_auxv },
3956 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3957 PACKET_qXfer_features },
3958 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3959 PACKET_qXfer_libraries },
3960 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3961 PACKET_qXfer_libraries_svr4 },
3962 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3963 PACKET_qXfer_memory_map },
3964 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3965 PACKET_qXfer_spu_read },
3966 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3967 PACKET_qXfer_spu_write },
3968 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3969 PACKET_qXfer_osdata },
3970 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3971 PACKET_qXfer_threads },
3972 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3973 PACKET_qXfer_traceframe_info },
3974 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3975 PACKET_QPassSignals },
3976 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3977 PACKET_QProgramSignals },
3978 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3979 PACKET_QStartNoAckMode },
3980 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
3981 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
3982 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3983 PACKET_qXfer_siginfo_read },
3984 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3985 PACKET_qXfer_siginfo_write },
3986 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
3987 PACKET_ConditionalTracepoints },
3988 { "ConditionalBreakpoints", PACKET_DISABLE, remote_cond_breakpoint_feature,
3989 PACKET_ConditionalBreakpoints },
3990 { "BreakpointCommands", PACKET_DISABLE, remote_breakpoint_commands_feature,
3991 PACKET_BreakpointCommands },
3992 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
3993 PACKET_FastTracepoints },
3994 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
3995 PACKET_StaticTracepoints },
3996 {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
3997 PACKET_InstallInTrace},
3998 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
4000 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4002 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4004 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4005 PACKET_TracepointSource },
4006 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4008 { "EnableDisableTracepoints", PACKET_DISABLE,
4009 remote_enable_disable_tracepoint_feature, -1 },
4010 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4011 PACKET_qXfer_fdpic },
4012 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4014 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4015 PACKET_QDisableRandomization },
4016 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4017 { "QTBuffer:size", PACKET_DISABLE,
4018 remote_supported_packet, PACKET_QTBuffer_size},
4019 { "tracenz", PACKET_DISABLE,
4020 remote_string_tracing_feature, -1 },
4021 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4022 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4023 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4024 PACKET_qXfer_btrace }
4027 static char *remote_support_xml;
4029 /* Register string appended to "xmlRegisters=" in qSupported query. */
4032 register_remote_support_xml (const char *xml)
4034 #if defined(HAVE_LIBEXPAT)
4035 if (remote_support_xml == NULL)
4036 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4039 char *copy = xstrdup (remote_support_xml + 13);
4040 char *p = strtok (copy, ",");
4044 if (strcmp (p, xml) == 0)
4051 while ((p = strtok (NULL, ",")) != NULL);
4054 remote_support_xml = reconcat (remote_support_xml,
4055 remote_support_xml, ",", xml,
4062 remote_query_supported_append (char *msg, const char *append)
4065 return reconcat (msg, msg, ";", append, (char *) NULL);
4067 return xstrdup (append);
4071 remote_query_supported (void)
4073 struct remote_state *rs = get_remote_state ();
4076 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4078 /* The packet support flags are handled differently for this packet
4079 than for most others. We treat an error, a disabled packet, and
4080 an empty response identically: any features which must be reported
4081 to be used will be automatically disabled. An empty buffer
4082 accomplishes this, since that is also the representation for a list
4083 containing no features. */
4086 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
4089 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4091 q = remote_query_supported_append (q, "multiprocess+");
4093 if (remote_support_xml)
4094 q = remote_query_supported_append (q, remote_support_xml);
4096 q = remote_query_supported_append (q, "qRelocInsn+");
4098 q = reconcat (q, "qSupported:", q, (char *) NULL);
4101 do_cleanups (old_chain);
4103 getpkt (&rs->buf, &rs->buf_size, 0);
4105 /* If an error occured, warn, but do not return - just reset the
4106 buffer to empty and go on to disable features. */
4107 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4110 warning (_("Remote failure reply: %s"), rs->buf);
4115 memset (seen, 0, sizeof (seen));
4120 enum packet_support is_supported;
4121 char *p, *end, *name_end, *value;
4123 /* First separate out this item from the rest of the packet. If
4124 there's another item after this, we overwrite the separator
4125 (terminated strings are much easier to work with). */
4127 end = strchr (p, ';');
4130 end = p + strlen (p);
4140 warning (_("empty item in \"qSupported\" response"));
4145 name_end = strchr (p, '=');
4148 /* This is a name=value entry. */
4149 is_supported = PACKET_ENABLE;
4150 value = name_end + 1;
4159 is_supported = PACKET_ENABLE;
4163 is_supported = PACKET_DISABLE;
4167 is_supported = PACKET_SUPPORT_UNKNOWN;
4171 warning (_("unrecognized item \"%s\" "
4172 "in \"qSupported\" response"), p);
4178 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4179 if (strcmp (remote_protocol_features[i].name, p) == 0)
4181 const struct protocol_feature *feature;
4184 feature = &remote_protocol_features[i];
4185 feature->func (feature, is_supported, value);
4190 /* If we increased the packet size, make sure to increase the global
4191 buffer size also. We delay this until after parsing the entire
4192 qSupported packet, because this is the same buffer we were
4194 if (rs->buf_size < rs->explicit_packet_size)
4196 rs->buf_size = rs->explicit_packet_size;
4197 rs->buf = xrealloc (rs->buf, rs->buf_size);
4200 /* Handle the defaults for unmentioned features. */
4201 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4204 const struct protocol_feature *feature;
4206 feature = &remote_protocol_features[i];
4207 feature->func (feature, feature->default_support, NULL);
4211 /* Remove any of the remote.c targets from target stack. Upper targets depend
4212 on it so remove them first. */
4215 remote_unpush_target (void)
4217 pop_all_targets_above (process_stratum - 1);
4221 remote_open_1 (char *name, int from_tty,
4222 struct target_ops *target, int extended_p)
4224 struct remote_state *rs = get_remote_state ();
4227 error (_("To open a remote debug connection, you need to specify what\n"
4228 "serial device is attached to the remote system\n"
4229 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4231 /* See FIXME above. */
4232 if (!target_async_permitted)
4233 wait_forever_enabled_p = 1;
4235 /* If we're connected to a running target, target_preopen will kill it.
4236 Ask this question first, before target_preopen has a chance to kill
4238 if (remote_desc != NULL && !have_inferiors ())
4241 && !query (_("Already connected to a remote target. Disconnect? ")))
4242 error (_("Still connected."));
4245 /* Here the possibly existing remote target gets unpushed. */
4246 target_preopen (from_tty);
4248 /* Make sure we send the passed signals list the next time we resume. */
4249 xfree (last_pass_packet);
4250 last_pass_packet = NULL;
4252 /* Make sure we send the program signals list the next time we
4254 xfree (last_program_signals_packet);
4255 last_program_signals_packet = NULL;
4257 remote_fileio_reset ();
4258 reopen_exec_file ();
4261 remote_desc = remote_serial_open (name);
4263 perror_with_name (name);
4265 if (baud_rate != -1)
4267 if (serial_setbaudrate (remote_desc, baud_rate))
4269 /* The requested speed could not be set. Error out to
4270 top level after closing remote_desc. Take care to
4271 set remote_desc to NULL to avoid closing remote_desc
4273 serial_close (remote_desc);
4275 perror_with_name (name);
4279 serial_raw (remote_desc);
4281 /* If there is something sitting in the buffer we might take it as a
4282 response to a command, which would be bad. */
4283 serial_flush_input (remote_desc);
4287 puts_filtered ("Remote debugging using ");
4288 puts_filtered (name);
4289 puts_filtered ("\n");
4291 push_target (target); /* Switch to using remote target now. */
4293 /* Register extra event sources in the event loop. */
4294 remote_async_inferior_event_token
4295 = create_async_event_handler (remote_async_inferior_event_handler,
4297 remote_notif_register_async_event_handler ();
4299 /* Reset the target state; these things will be queried either by
4300 remote_query_supported or as they are needed. */
4301 init_all_packet_configs ();
4302 rs->cached_wait_status = 0;
4303 rs->explicit_packet_size = 0;
4305 rs->multi_process_aware = 0;
4306 rs->extended = extended_p;
4307 rs->non_stop_aware = 0;
4308 rs->waiting_for_stop_reply = 0;
4309 rs->ctrlc_pending_p = 0;
4311 general_thread = not_sent_ptid;
4312 continue_thread = not_sent_ptid;
4313 remote_traceframe_number = -1;
4315 /* Probe for ability to use "ThreadInfo" query, as required. */
4316 use_threadinfo_query = 1;
4317 use_threadextra_query = 1;
4319 if (target_async_permitted)
4321 /* With this target we start out by owning the terminal. */
4322 remote_async_terminal_ours_p = 1;
4324 /* FIXME: cagney/1999-09-23: During the initial connection it is
4325 assumed that the target is already ready and able to respond to
4326 requests. Unfortunately remote_start_remote() eventually calls
4327 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4328 around this. Eventually a mechanism that allows
4329 wait_for_inferior() to expect/get timeouts will be
4331 wait_forever_enabled_p = 0;
4334 /* First delete any symbols previously loaded from shared libraries. */
4335 no_shared_libraries (NULL, 0);
4338 init_thread_list ();
4340 /* Start the remote connection. If error() or QUIT, discard this
4341 target (we'd otherwise be in an inconsistent state) and then
4342 propogate the error on up the exception chain. This ensures that
4343 the caller doesn't stumble along blindly assuming that the
4344 function succeeded. The CLI doesn't have this problem but other
4345 UI's, such as MI do.
4347 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4348 this function should return an error indication letting the
4349 caller restore the previous state. Unfortunately the command
4350 ``target remote'' is directly wired to this function making that
4351 impossible. On a positive note, the CLI side of this problem has
4352 been fixed - the function set_cmd_context() makes it possible for
4353 all the ``target ....'' commands to share a common callback
4354 function. See cli-dump.c. */
4356 volatile struct gdb_exception ex;
4358 TRY_CATCH (ex, RETURN_MASK_ALL)
4360 remote_start_remote (from_tty, target, extended_p);
4364 /* Pop the partially set up target - unless something else did
4365 already before throwing the exception. */
4366 if (remote_desc != NULL)
4367 remote_unpush_target ();
4368 if (target_async_permitted)
4369 wait_forever_enabled_p = 1;
4370 throw_exception (ex);
4374 if (target_async_permitted)
4375 wait_forever_enabled_p = 1;
4378 /* This takes a program previously attached to and detaches it. After
4379 this is done, GDB can be used to debug some other program. We
4380 better not have left any breakpoints in the target program or it'll
4381 die when it hits one. */
4384 remote_detach_1 (char *args, int from_tty, int extended)
4386 int pid = ptid_get_pid (inferior_ptid);
4387 struct remote_state *rs = get_remote_state ();
4390 error (_("Argument given to \"detach\" when remotely debugging."));
4392 if (!target_has_execution)
4393 error (_("No process to detach from."));
4397 char *exec_file = get_exec_file (0);
4398 if (exec_file == NULL)
4400 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4401 target_pid_to_str (pid_to_ptid (pid)));
4402 gdb_flush (gdb_stdout);
4405 /* Tell the remote target to detach. */
4406 if (remote_multi_process_p (rs))
4407 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4409 strcpy (rs->buf, "D");
4412 getpkt (&rs->buf, &rs->buf_size, 0);
4414 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4416 else if (rs->buf[0] == '\0')
4417 error (_("Remote doesn't know how to detach"));
4419 error (_("Can't detach process."));
4421 if (from_tty && !extended)
4422 puts_filtered (_("Ending remote debugging.\n"));
4424 target_mourn_inferior ();
4428 remote_detach (struct target_ops *ops, char *args, int from_tty)
4430 remote_detach_1 (args, from_tty, 0);
4434 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
4436 remote_detach_1 (args, from_tty, 1);
4439 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4442 remote_disconnect (struct target_ops *target, char *args, int from_tty)
4445 error (_("Argument given to \"disconnect\" when remotely debugging."));
4447 /* Make sure we unpush even the extended remote targets; mourn
4448 won't do it. So call remote_mourn_1 directly instead of
4449 target_mourn_inferior. */
4450 remote_mourn_1 (target);
4453 puts_filtered ("Ending remote debugging.\n");
4456 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4457 be chatty about it. */
4460 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4462 struct remote_state *rs = get_remote_state ();
4464 char *wait_status = NULL;
4466 pid = parse_pid_to_attach (args);
4468 /* Remote PID can be freely equal to getpid, do not check it here the same
4469 way as in other targets. */
4471 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4472 error (_("This target does not support attaching to a process"));
4476 char *exec_file = get_exec_file (0);
4479 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4480 target_pid_to_str (pid_to_ptid (pid)));
4482 printf_unfiltered (_("Attaching to %s\n"),
4483 target_pid_to_str (pid_to_ptid (pid)));
4485 gdb_flush (gdb_stdout);
4488 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4490 getpkt (&rs->buf, &rs->buf_size, 0);
4492 if (packet_ok (rs->buf,
4493 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
4497 /* Save the reply for later. */
4498 wait_status = alloca (strlen (rs->buf) + 1);
4499 strcpy (wait_status, rs->buf);
4501 else if (strcmp (rs->buf, "OK") != 0)
4502 error (_("Attaching to %s failed with: %s"),
4503 target_pid_to_str (pid_to_ptid (pid)),
4506 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4507 error (_("This target does not support attaching to a process"));
4509 error (_("Attaching to %s failed"),
4510 target_pid_to_str (pid_to_ptid (pid)));
4512 set_current_inferior (remote_add_inferior (0, pid, 1));
4514 inferior_ptid = pid_to_ptid (pid);
4518 struct thread_info *thread;
4520 /* Get list of threads. */
4521 remote_threads_info (target);
4523 thread = first_thread_of_process (pid);
4525 inferior_ptid = thread->ptid;
4527 inferior_ptid = pid_to_ptid (pid);
4529 /* Invalidate our notion of the remote current thread. */
4530 record_currthread (minus_one_ptid);
4534 /* Now, if we have thread information, update inferior_ptid. */
4535 inferior_ptid = remote_current_thread (inferior_ptid);
4537 /* Add the main thread to the thread list. */
4538 add_thread_silent (inferior_ptid);
4541 /* Next, if the target can specify a description, read it. We do
4542 this before anything involving memory or registers. */
4543 target_find_description ();
4547 /* Use the previously fetched status. */
4548 gdb_assert (wait_status != NULL);
4550 if (target_can_async_p ())
4552 struct notif_event *reply
4553 = remote_notif_parse (¬if_client_stop, wait_status);
4555 push_stop_reply ((struct stop_reply *) reply);
4557 target_async (inferior_event_handler, 0);
4561 gdb_assert (wait_status != NULL);
4562 strcpy (rs->buf, wait_status);
4563 rs->cached_wait_status = 1;
4567 gdb_assert (wait_status == NULL);
4571 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
4573 extended_remote_attach_1 (ops, args, from_tty);
4576 /* Convert hex digit A to a number. */
4581 if (a >= '0' && a <= '9')
4583 else if (a >= 'a' && a <= 'f')
4584 return a - 'a' + 10;
4585 else if (a >= 'A' && a <= 'F')
4586 return a - 'A' + 10;
4588 error (_("Reply contains invalid hex digit %d"), a);
4592 hex2bin (const char *hex, gdb_byte *bin, int count)
4596 for (i = 0; i < count; i++)
4598 if (hex[0] == 0 || hex[1] == 0)
4600 /* Hex string is short, or of uneven length.
4601 Return the count that has been converted so far. */
4604 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4610 /* Convert number NIB to a hex digit. */
4618 return 'a' + nib - 10;
4622 bin2hex (const gdb_byte *bin, char *hex, int count)
4626 /* May use a length, or a nul-terminated string as input. */
4628 count = strlen ((char *) bin);
4630 for (i = 0; i < count; i++)
4632 *hex++ = tohex ((*bin >> 4) & 0xf);
4633 *hex++ = tohex (*bin++ & 0xf);
4639 /* Check for the availability of vCont. This function should also check
4643 remote_vcont_probe (struct remote_state *rs)
4647 strcpy (rs->buf, "vCont?");
4649 getpkt (&rs->buf, &rs->buf_size, 0);
4652 /* Make sure that the features we assume are supported. */
4653 if (strncmp (buf, "vCont", 5) == 0)
4656 int support_s, support_S, support_c, support_C;
4662 rs->supports_vCont.t = 0;
4663 rs->supports_vCont.r = 0;
4664 while (p && *p == ';')
4667 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4669 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4671 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4673 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4675 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4676 rs->supports_vCont.t = 1;
4677 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4678 rs->supports_vCont.r = 1;
4680 p = strchr (p, ';');
4683 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4684 BUF will make packet_ok disable the packet. */
4685 if (!support_s || !support_S || !support_c || !support_C)
4689 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4692 /* Helper function for building "vCont" resumptions. Write a
4693 resumption to P. ENDP points to one-passed-the-end of the buffer
4694 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4695 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4696 resumed thread should be single-stepped and/or signalled. If PTID
4697 equals minus_one_ptid, then all threads are resumed; if PTID
4698 represents a process, then all threads of the process are resumed;
4699 the thread to be stepped and/or signalled is given in the global
4703 append_resumption (char *p, char *endp,
4704 ptid_t ptid, int step, enum gdb_signal siggnal)
4706 struct remote_state *rs = get_remote_state ();
4708 if (step && siggnal != GDB_SIGNAL_0)
4709 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4711 /* GDB is willing to range step. */
4712 && use_range_stepping
4713 /* Target supports range stepping. */
4714 && rs->supports_vCont.r
4715 /* We don't currently support range stepping multiple
4716 threads with a wildcard (though the protocol allows it,
4717 so stubs shouldn't make an active effort to forbid
4719 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4721 struct thread_info *tp;
4723 if (ptid_equal (ptid, minus_one_ptid))
4725 /* If we don't know about the target thread's tid, then
4726 we're resuming magic_null_ptid (see caller). */
4727 tp = find_thread_ptid (magic_null_ptid);
4730 tp = find_thread_ptid (ptid);
4731 gdb_assert (tp != NULL);
4733 if (tp->control.may_range_step)
4735 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4737 p += xsnprintf (p, endp - p, ";r%s,%s",
4738 phex_nz (tp->control.step_range_start,
4740 phex_nz (tp->control.step_range_end,
4744 p += xsnprintf (p, endp - p, ";s");
4747 p += xsnprintf (p, endp - p, ";s");
4748 else if (siggnal != GDB_SIGNAL_0)
4749 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4751 p += xsnprintf (p, endp - p, ";c");
4753 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4757 /* All (-1) threads of process. */
4758 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4760 p += xsnprintf (p, endp - p, ":");
4761 p = write_ptid (p, endp, nptid);
4763 else if (!ptid_equal (ptid, minus_one_ptid))
4765 p += xsnprintf (p, endp - p, ":");
4766 p = write_ptid (p, endp, ptid);
4772 /* Append a vCont continue-with-signal action for threads that have a
4773 non-zero stop signal. */
4776 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4778 struct thread_info *thread;
4780 ALL_THREADS (thread)
4781 if (ptid_match (thread->ptid, ptid)
4782 && !ptid_equal (inferior_ptid, thread->ptid)
4783 && thread->suspend.stop_signal != GDB_SIGNAL_0
4784 && signal_pass_state (thread->suspend.stop_signal))
4786 p = append_resumption (p, endp, thread->ptid,
4787 0, thread->suspend.stop_signal);
4788 thread->suspend.stop_signal = GDB_SIGNAL_0;
4794 /* Resume the remote inferior by using a "vCont" packet. The thread
4795 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4796 resumed thread should be single-stepped and/or signalled. If PTID
4797 equals minus_one_ptid, then all threads are resumed; the thread to
4798 be stepped and/or signalled is given in the global INFERIOR_PTID.
4799 This function returns non-zero iff it resumes the inferior.
4801 This function issues a strict subset of all possible vCont commands at the
4805 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4807 struct remote_state *rs = get_remote_state ();
4811 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4812 remote_vcont_probe (rs);
4814 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
4818 endp = rs->buf + get_remote_packet_size ();
4820 /* If we could generate a wider range of packets, we'd have to worry
4821 about overflowing BUF. Should there be a generic
4822 "multi-part-packet" packet? */
4824 p += xsnprintf (p, endp - p, "vCont");
4826 if (ptid_equal (ptid, magic_null_ptid))
4828 /* MAGIC_NULL_PTID means that we don't have any active threads,
4829 so we don't have any TID numbers the inferior will
4830 understand. Make sure to only send forms that do not specify
4832 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4834 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4836 /* Resume all threads (of all processes, or of a single
4837 process), with preference for INFERIOR_PTID. This assumes
4838 inferior_ptid belongs to the set of all threads we are about
4840 if (step || siggnal != GDB_SIGNAL_0)
4842 /* Step inferior_ptid, with or without signal. */
4843 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4846 /* Also pass down any pending signaled resumption for other
4847 threads not the current. */
4848 p = append_pending_thread_resumptions (p, endp, ptid);
4850 /* And continue others without a signal. */
4851 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4855 /* Scheduler locking; resume only PTID. */
4856 append_resumption (p, endp, ptid, step, siggnal);
4859 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4864 /* In non-stop, the stub replies to vCont with "OK". The stop
4865 reply will be reported asynchronously by means of a `%Stop'
4867 getpkt (&rs->buf, &rs->buf_size, 0);
4868 if (strcmp (rs->buf, "OK") != 0)
4869 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4875 /* Tell the remote machine to resume. */
4877 static enum gdb_signal last_sent_signal = GDB_SIGNAL_0;
4879 static int last_sent_step;
4882 remote_resume (struct target_ops *ops,
4883 ptid_t ptid, int step, enum gdb_signal siggnal)
4885 struct remote_state *rs = get_remote_state ();
4888 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4889 (explained in remote-notif.c:handle_notification) so
4890 remote_notif_process is not called. We need find a place where
4891 it is safe to start a 'vNotif' sequence. It is good to do it
4892 before resuming inferior, because inferior was stopped and no RSP
4893 traffic at that moment. */
4895 remote_notif_process (¬if_client_stop);
4897 last_sent_signal = siggnal;
4898 last_sent_step = step;
4900 /* The vCont packet doesn't need to specify threads via Hc. */
4901 /* No reverse support (yet) for vCont. */
4902 if (execution_direction != EXEC_REVERSE)
4903 if (remote_vcont_resume (ptid, step, siggnal))
4906 /* All other supported resume packets do use Hc, so set the continue
4908 if (ptid_equal (ptid, minus_one_ptid))
4909 set_continue_thread (any_thread_ptid);
4911 set_continue_thread (ptid);
4914 if (execution_direction == EXEC_REVERSE)
4916 /* We don't pass signals to the target in reverse exec mode. */
4917 if (info_verbose && siggnal != GDB_SIGNAL_0)
4918 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4922 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4923 error (_("Remote reverse-step not supported."));
4925 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
4926 error (_("Remote reverse-continue not supported."));
4928 strcpy (buf, step ? "bs" : "bc");
4930 else if (siggnal != GDB_SIGNAL_0)
4932 buf[0] = step ? 'S' : 'C';
4933 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4934 buf[2] = tohex (((int) siggnal) & 0xf);
4938 strcpy (buf, step ? "s" : "c");
4943 /* We are about to start executing the inferior, let's register it
4944 with the event loop. NOTE: this is the one place where all the
4945 execution commands end up. We could alternatively do this in each
4946 of the execution commands in infcmd.c. */
4947 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4948 into infcmd.c in order to allow inferior function calls to work
4949 NOT asynchronously. */
4950 if (target_can_async_p ())
4951 target_async (inferior_event_handler, 0);
4953 /* We've just told the target to resume. The remote server will
4954 wait for the inferior to stop, and then send a stop reply. In
4955 the mean time, we can't start another command/query ourselves
4956 because the stub wouldn't be ready to process it. This applies
4957 only to the base all-stop protocol, however. In non-stop (which
4958 only supports vCont), the stub replies with an "OK", and is
4959 immediate able to process further serial input. */
4961 rs->waiting_for_stop_reply = 1;
4965 /* Set up the signal handler for SIGINT, while the target is
4966 executing, ovewriting the 'regular' SIGINT signal handler. */
4968 initialize_sigint_signal_handler (void)
4970 signal (SIGINT, handle_remote_sigint);
4973 /* Signal handler for SIGINT, while the target is executing. */
4975 handle_remote_sigint (int sig)
4977 signal (sig, handle_remote_sigint_twice);
4978 mark_async_signal_handler (sigint_remote_token);
4981 /* Signal handler for SIGINT, installed after SIGINT has already been
4982 sent once. It will take effect the second time that the user sends
4985 handle_remote_sigint_twice (int sig)
4987 signal (sig, handle_remote_sigint);
4988 mark_async_signal_handler (sigint_remote_twice_token);
4991 /* Perform the real interruption of the target execution, in response
4994 async_remote_interrupt (gdb_client_data arg)
4997 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
4999 target_stop (inferior_ptid);
5002 /* Perform interrupt, if the first attempt did not succeed. Just give
5003 up on the target alltogether. */
5005 async_remote_interrupt_twice (gdb_client_data arg)
5008 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5013 /* Reinstall the usual SIGINT handlers, after the target has
5016 cleanup_sigint_signal_handler (void *dummy)
5018 signal (SIGINT, handle_sigint);
5021 /* Send ^C to target to halt it. Target will respond, and send us a
5023 static void (*ofunc) (int);
5025 /* The command line interface's stop routine. This function is installed
5026 as a signal handler for SIGINT. The first time a user requests a
5027 stop, we call remote_stop to send a break or ^C. If there is no
5028 response from the target (it didn't stop when the user requested it),
5029 we ask the user if he'd like to detach from the target. */
5031 remote_interrupt (int signo)
5033 /* If this doesn't work, try more severe steps. */
5034 signal (signo, remote_interrupt_twice);
5036 gdb_call_async_signal_handler (sigint_remote_token, 1);
5039 /* The user typed ^C twice. */
5042 remote_interrupt_twice (int signo)
5044 signal (signo, ofunc);
5045 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
5046 signal (signo, remote_interrupt);
5049 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5050 thread, all threads of a remote process, or all threads of all
5054 remote_stop_ns (ptid_t ptid)
5056 struct remote_state *rs = get_remote_state ();
5058 char *endp = rs->buf + get_remote_packet_size ();
5060 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
5061 remote_vcont_probe (rs);
5063 if (!rs->supports_vCont.t)
5064 error (_("Remote server does not support stopping threads"));
5066 if (ptid_equal (ptid, minus_one_ptid)
5067 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5068 p += xsnprintf (p, endp - p, "vCont;t");
5073 p += xsnprintf (p, endp - p, "vCont;t:");
5075 if (ptid_is_pid (ptid))
5076 /* All (-1) threads of process. */
5077 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
5080 /* Small optimization: if we already have a stop reply for
5081 this thread, no use in telling the stub we want this
5083 if (peek_stop_reply (ptid))
5089 write_ptid (p, endp, nptid);
5092 /* In non-stop, we get an immediate OK reply. The stop reply will
5093 come in asynchronously by notification. */
5095 getpkt (&rs->buf, &rs->buf_size, 0);
5096 if (strcmp (rs->buf, "OK") != 0)
5097 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5100 /* All-stop version of target_stop. Sends a break or a ^C to stop the
5101 remote target. It is undefined which thread of which process
5102 reports the stop. */
5105 remote_stop_as (ptid_t ptid)
5107 struct remote_state *rs = get_remote_state ();
5109 rs->ctrlc_pending_p = 1;
5111 /* If the inferior is stopped already, but the core didn't know
5112 about it yet, just ignore the request. The cached wait status
5113 will be collected in remote_wait. */
5114 if (rs->cached_wait_status)
5117 /* Send interrupt_sequence to remote target. */
5118 send_interrupt_sequence ();
5121 /* This is the generic stop called via the target vector. When a target
5122 interrupt is requested, either by the command line or the GUI, we
5123 will eventually end up here. */
5126 remote_stop (ptid_t ptid)
5129 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5132 remote_stop_ns (ptid);
5134 remote_stop_as (ptid);
5137 /* Ask the user what to do when an interrupt is received. */
5140 interrupt_query (void)
5142 target_terminal_ours ();
5144 if (target_can_async_p ())
5146 signal (SIGINT, handle_sigint);
5147 deprecated_throw_reason (RETURN_QUIT);
5151 if (query (_("Interrupted while waiting for the program.\n\
5152 Give up (and stop debugging it)? ")))
5154 remote_unpush_target ();
5155 deprecated_throw_reason (RETURN_QUIT);
5159 target_terminal_inferior ();
5162 /* Enable/disable target terminal ownership. Most targets can use
5163 terminal groups to control terminal ownership. Remote targets are
5164 different in that explicit transfer of ownership to/from GDB/target
5168 remote_terminal_inferior (void)
5170 if (!target_async_permitted)
5171 /* Nothing to do. */
5174 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5175 idempotent. The event-loop GDB talking to an asynchronous target
5176 with a synchronous command calls this function from both
5177 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5178 transfer the terminal to the target when it shouldn't this guard
5180 if (!remote_async_terminal_ours_p)
5182 delete_file_handler (input_fd);
5183 remote_async_terminal_ours_p = 0;
5184 initialize_sigint_signal_handler ();
5185 /* NOTE: At this point we could also register our selves as the
5186 recipient of all input. Any characters typed could then be
5187 passed on down to the target. */
5191 remote_terminal_ours (void)
5193 if (!target_async_permitted)
5194 /* Nothing to do. */
5197 /* See FIXME in remote_terminal_inferior. */
5198 if (remote_async_terminal_ours_p)
5200 cleanup_sigint_signal_handler (NULL);
5201 add_file_handler (input_fd, stdin_event_handler, 0);
5202 remote_async_terminal_ours_p = 1;
5206 remote_console_output (char *msg)
5210 for (p = msg; p[0] && p[1]; p += 2)
5213 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5217 fputs_unfiltered (tb, gdb_stdtarg);
5219 gdb_flush (gdb_stdtarg);
5222 typedef struct cached_reg
5225 gdb_byte data[MAX_REGISTER_SIZE];
5228 DEF_VEC_O(cached_reg_t);
5230 typedef struct stop_reply
5232 struct notif_event base;
5234 /* The identifier of the thread about this event */
5237 struct target_waitstatus ws;
5239 /* Expedited registers. This makes remote debugging a bit more
5240 efficient for those targets that provide critical registers as
5241 part of their normal status mechanism (as another roundtrip to
5242 fetch them is avoided). */
5243 VEC(cached_reg_t) *regcache;
5245 int stopped_by_watchpoint_p;
5246 CORE_ADDR watch_data_address;
5254 DECLARE_QUEUE_P (stop_reply_p);
5255 DEFINE_QUEUE_P (stop_reply_p);
5256 /* The list of already fetched and acknowledged stop events. This
5257 queue is used for notification Stop, and other notifications
5258 don't need queue for their events, because the notification events
5259 of Stop can't be consumed immediately, so that events should be
5260 queued first, and be consumed by remote_wait_{ns,as} one per
5261 time. Other notifications can consume their events immediately,
5262 so queue is not needed for them. */
5263 static QUEUE (stop_reply_p) *stop_reply_queue;
5266 stop_reply_xfree (struct stop_reply *r)
5270 VEC_free (cached_reg_t, r->regcache);
5276 remote_notif_stop_parse (struct notif_client *self, char *buf,
5277 struct notif_event *event)
5279 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5283 remote_notif_stop_ack (struct notif_client *self, char *buf,
5284 struct notif_event *event)
5286 struct stop_reply *stop_reply = (struct stop_reply *) event;
5289 putpkt ((char *) self->ack_command);
5291 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5292 /* We got an unknown stop reply. */
5293 error (_("Unknown stop reply"));
5295 push_stop_reply (stop_reply);
5299 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5301 /* We can't get pending events in remote_notif_process for
5302 notification stop, and we have to do this in remote_wait_ns
5303 instead. If we fetch all queued events from stub, remote stub
5304 may exit and we have no chance to process them back in
5306 mark_async_event_handler (remote_async_inferior_event_token);
5311 stop_reply_dtr (struct notif_event *event)
5313 struct stop_reply *r = (struct stop_reply *) event;
5315 VEC_free (cached_reg_t, r->regcache);
5318 static struct notif_event *
5319 remote_notif_stop_alloc_reply (void)
5321 struct notif_event *r
5322 = (struct notif_event *) XMALLOC (struct stop_reply);
5324 r->dtr = stop_reply_dtr;
5329 /* A client of notification Stop. */
5331 struct notif_client notif_client_stop =
5335 remote_notif_stop_parse,
5336 remote_notif_stop_ack,
5337 remote_notif_stop_can_get_pending_events,
5338 remote_notif_stop_alloc_reply,
5342 /* A parameter to pass data in and out. */
5344 struct queue_iter_param
5347 struct stop_reply *output;
5350 /* Remove all queue elements meet the condition it checks. */
5353 remote_notif_remove_all (QUEUE (stop_reply_p) *q,
5354 QUEUE_ITER (stop_reply_p) *iter,
5358 struct queue_iter_param *param = data;
5359 struct inferior *inf = param->input;
5361 if (inf == NULL || ptid_get_pid (event->ptid) == inf->pid)
5363 stop_reply_xfree (event);
5364 QUEUE_remove_elem (stop_reply_p, q, iter);
5370 /* Discard all pending stop replies of inferior INF. If INF is NULL,
5371 discard everything. */
5374 discard_pending_stop_replies (struct inferior *inf)
5377 struct queue_iter_param param;
5378 struct stop_reply *reply
5379 = (struct stop_reply *) notif_client_stop.pending_event;
5381 /* Discard the in-flight notification. */
5384 || ptid_get_pid (reply->ptid) == inf->pid))
5386 stop_reply_xfree (reply);
5387 notif_client_stop.pending_event = NULL;
5391 param.output = NULL;
5392 /* Discard the stop replies we have already pulled with
5394 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5395 remote_notif_remove_all, ¶m);
5398 /* A parameter to pass data in and out. */
5401 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5402 QUEUE_ITER (stop_reply_p) *iter,
5406 struct queue_iter_param *param = data;
5407 ptid_t *ptid = param->input;
5409 if (ptid_match (event->ptid, *ptid))
5411 param->output = event;
5412 QUEUE_remove_elem (stop_reply_p, q, iter);
5419 /* Remove the first reply in 'stop_reply_queue' which matches
5422 static struct stop_reply *
5423 remote_notif_remove_queued_reply (ptid_t ptid)
5425 struct queue_iter_param param;
5427 param.input = &ptid;
5428 param.output = NULL;
5430 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5431 remote_notif_remove_once_on_match, ¶m);
5433 fprintf_unfiltered (gdb_stdlog,
5434 "notif: discard queued event: 'Stop' in %s\n",
5435 target_pid_to_str (ptid));
5437 return param.output;
5440 /* Look for a queued stop reply belonging to PTID. If one is found,
5441 remove it from the queue, and return it. Returns NULL if none is
5442 found. If there are still queued events left to process, tell the
5443 event loop to get back to target_wait soon. */
5445 static struct stop_reply *
5446 queued_stop_reply (ptid_t ptid)
5448 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5450 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5451 /* There's still at least an event left. */
5452 mark_async_event_handler (remote_async_inferior_event_token);
5457 /* Push a fully parsed stop reply in the stop reply queue. Since we
5458 know that we now have at least one queued event left to pass to the
5459 core side, tell the event loop to get back to target_wait soon. */
5462 push_stop_reply (struct stop_reply *new_event)
5464 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5467 fprintf_unfiltered (gdb_stdlog,
5468 "notif: push 'Stop' %s to queue %d\n",
5469 target_pid_to_str (new_event->ptid),
5470 QUEUE_length (stop_reply_p,
5473 mark_async_event_handler (remote_async_inferior_event_token);
5477 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5478 QUEUE_ITER (stop_reply_p) *iter,
5479 struct stop_reply *event,
5482 ptid_t *ptid = data;
5484 return !(ptid_equal (*ptid, event->ptid)
5485 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5488 /* Returns true if we have a stop reply for PTID. */
5491 peek_stop_reply (ptid_t ptid)
5493 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5494 stop_reply_match_ptid_and_ws, &ptid);
5497 /* Parse the stop reply in BUF. Either the function succeeds, and the
5498 result is stored in EVENT, or throws an error. */
5501 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5503 struct remote_arch_state *rsa = get_remote_arch_state ();
5507 event->ptid = null_ptid;
5508 event->ws.kind = TARGET_WAITKIND_IGNORE;
5509 event->ws.value.integer = 0;
5510 event->solibs_changed = 0;
5511 event->replay_event = 0;
5512 event->stopped_by_watchpoint_p = 0;
5513 event->regcache = NULL;
5518 case 'T': /* Status with PC, SP, FP, ... */
5519 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5520 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5522 n... = register number
5523 r... = register contents
5526 p = &buf[3]; /* after Txx */
5534 /* If the packet contains a register number, save it in
5535 pnum and set p1 to point to the character following it.
5536 Otherwise p1 points to p. */
5538 /* If this packet is an awatch packet, don't parse the 'a'
5539 as a register number. */
5541 if (strncmp (p, "awatch", strlen("awatch")) != 0
5542 && strncmp (p, "core", strlen ("core") != 0))
5544 /* Read the ``P'' register number. */
5545 pnum = strtol (p, &p_temp, 16);
5551 if (p1 == p) /* No register number present here. */
5553 p1 = strchr (p, ':');
5555 error (_("Malformed packet(a) (missing colon): %s\n\
5558 if (strncmp (p, "thread", p1 - p) == 0)
5559 event->ptid = read_ptid (++p1, &p);
5560 else if ((strncmp (p, "watch", p1 - p) == 0)
5561 || (strncmp (p, "rwatch", p1 - p) == 0)
5562 || (strncmp (p, "awatch", p1 - p) == 0))
5564 event->stopped_by_watchpoint_p = 1;
5565 p = unpack_varlen_hex (++p1, &addr);
5566 event->watch_data_address = (CORE_ADDR) addr;
5568 else if (strncmp (p, "library", p1 - p) == 0)
5572 while (*p_temp && *p_temp != ';')
5575 event->solibs_changed = 1;
5578 else if (strncmp (p, "replaylog", p1 - p) == 0)
5580 /* NO_HISTORY event.
5581 p1 will indicate "begin" or "end", but
5582 it makes no difference for now, so ignore it. */
5583 event->replay_event = 1;
5584 p_temp = strchr (p1 + 1, ';');
5588 else if (strncmp (p, "core", p1 - p) == 0)
5592 p = unpack_varlen_hex (++p1, &c);
5597 /* Silently skip unknown optional info. */
5598 p_temp = strchr (p1 + 1, ';');
5605 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5606 cached_reg_t cached_reg;
5611 error (_("Malformed packet(b) (missing colon): %s\n\
5617 error (_("Remote sent bad register number %s: %s\n\
5619 hex_string (pnum), p, buf);
5621 cached_reg.num = reg->regnum;
5623 fieldsize = hex2bin (p, cached_reg.data,
5624 register_size (target_gdbarch (),
5627 if (fieldsize < register_size (target_gdbarch (),
5629 warning (_("Remote reply is too short: %s"), buf);
5631 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5635 error (_("Remote register badly formatted: %s\nhere: %s"),
5640 case 'S': /* Old style status, just signal only. */
5641 if (event->solibs_changed)
5642 event->ws.kind = TARGET_WAITKIND_LOADED;
5643 else if (event->replay_event)
5644 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5647 event->ws.kind = TARGET_WAITKIND_STOPPED;
5648 event->ws.value.sig = (enum gdb_signal)
5649 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
5652 case 'W': /* Target exited. */
5659 /* GDB used to accept only 2 hex chars here. Stubs should
5660 only send more if they detect GDB supports multi-process
5662 p = unpack_varlen_hex (&buf[1], &value);
5666 /* The remote process exited. */
5667 event->ws.kind = TARGET_WAITKIND_EXITED;
5668 event->ws.value.integer = value;
5672 /* The remote process exited with a signal. */
5673 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5674 event->ws.value.sig = (enum gdb_signal) value;
5677 /* If no process is specified, assume inferior_ptid. */
5678 pid = ptid_get_pid (inferior_ptid);
5687 else if (strncmp (p,
5688 "process:", sizeof ("process:") - 1) == 0)
5692 p += sizeof ("process:") - 1;
5693 unpack_varlen_hex (p, &upid);
5697 error (_("unknown stop reply packet: %s"), buf);
5700 error (_("unknown stop reply packet: %s"), buf);
5701 event->ptid = pid_to_ptid (pid);
5706 if (non_stop && ptid_equal (event->ptid, null_ptid))
5707 error (_("No process or thread specified in stop reply: %s"), buf);
5710 /* When the stub wants to tell GDB about a new notification reply, it
5711 sends a notification (%Stop, for example). Those can come it at
5712 any time, hence, we have to make sure that any pending
5713 putpkt/getpkt sequence we're making is finished, before querying
5714 the stub for more events with the corresponding ack command
5715 (vStopped, for example). E.g., if we started a vStopped sequence
5716 immediately upon receiving the notification, something like this
5724 1.6) <-- (registers reply to step #1.3)
5726 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5729 To solve this, whenever we parse a %Stop notification successfully,
5730 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5731 doing whatever we were doing:
5737 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5738 2.5) <-- (registers reply to step #2.3)
5740 Eventualy after step #2.5, we return to the event loop, which
5741 notices there's an event on the
5742 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5743 associated callback --- the function below. At this point, we're
5744 always safe to start a vStopped sequence. :
5747 2.7) <-- T05 thread:2
5753 remote_notif_get_pending_events (struct notif_client *nc)
5755 struct remote_state *rs = get_remote_state ();
5757 if (nc->pending_event)
5760 fprintf_unfiltered (gdb_stdlog,
5761 "notif: process: '%s' ack pending event\n",
5765 nc->ack (nc, rs->buf, nc->pending_event);
5766 nc->pending_event = NULL;
5770 getpkt (&rs->buf, &rs->buf_size, 0);
5771 if (strcmp (rs->buf, "OK") == 0)
5774 remote_notif_ack (nc, rs->buf);
5780 fprintf_unfiltered (gdb_stdlog,
5781 "notif: process: '%s' no pending reply\n",
5786 /* Called when it is decided that STOP_REPLY holds the info of the
5787 event that is to be returned to the core. This function always
5788 destroys STOP_REPLY. */
5791 process_stop_reply (struct stop_reply *stop_reply,
5792 struct target_waitstatus *status)
5796 *status = stop_reply->ws;
5797 ptid = stop_reply->ptid;
5799 /* If no thread/process was reported by the stub, assume the current
5801 if (ptid_equal (ptid, null_ptid))
5802 ptid = inferior_ptid;
5804 if (status->kind != TARGET_WAITKIND_EXITED
5805 && status->kind != TARGET_WAITKIND_SIGNALLED)
5807 /* Expedited registers. */
5808 if (stop_reply->regcache)
5810 struct regcache *regcache
5811 = get_thread_arch_regcache (ptid, target_gdbarch ());
5816 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5818 regcache_raw_supply (regcache, reg->num, reg->data);
5819 VEC_free (cached_reg_t, stop_reply->regcache);
5822 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5823 remote_watch_data_address = stop_reply->watch_data_address;
5825 remote_notice_new_inferior (ptid, 0);
5826 demand_private_info (ptid)->core = stop_reply->core;
5829 stop_reply_xfree (stop_reply);
5833 /* The non-stop mode version of target_wait. */
5836 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5838 struct remote_state *rs = get_remote_state ();
5839 struct stop_reply *stop_reply;
5843 /* If in non-stop mode, get out of getpkt even if a
5844 notification is received. */
5846 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5847 0 /* forever */, &is_notif);
5850 if (ret != -1 && !is_notif)
5853 case 'E': /* Error of some sort. */
5854 /* We're out of sync with the target now. Did it continue
5855 or not? We can't tell which thread it was in non-stop,
5856 so just ignore this. */
5857 warning (_("Remote failure reply: %s"), rs->buf);
5859 case 'O': /* Console output. */
5860 remote_console_output (rs->buf + 1);
5863 warning (_("Invalid remote reply: %s"), rs->buf);
5867 /* Acknowledge a pending stop reply that may have arrived in the
5869 if (notif_client_stop.pending_event != NULL)
5870 remote_notif_get_pending_events (¬if_client_stop);
5872 /* If indeed we noticed a stop reply, we're done. */
5873 stop_reply = queued_stop_reply (ptid);
5874 if (stop_reply != NULL)
5875 return process_stop_reply (stop_reply, status);
5877 /* Still no event. If we're just polling for an event, then
5878 return to the event loop. */
5879 if (options & TARGET_WNOHANG)
5881 status->kind = TARGET_WAITKIND_IGNORE;
5882 return minus_one_ptid;
5885 /* Otherwise do a blocking wait. */
5886 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5887 1 /* forever */, &is_notif);
5891 /* Wait until the remote machine stops, then return, storing status in
5892 STATUS just as `wait' would. */
5895 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5897 struct remote_state *rs = get_remote_state ();
5898 ptid_t event_ptid = null_ptid;
5900 struct stop_reply *stop_reply;
5904 status->kind = TARGET_WAITKIND_IGNORE;
5905 status->value.integer = 0;
5907 stop_reply = queued_stop_reply (ptid);
5908 if (stop_reply != NULL)
5909 return process_stop_reply (stop_reply, status);
5911 if (rs->cached_wait_status)
5912 /* Use the cached wait status, but only once. */
5913 rs->cached_wait_status = 0;
5919 if (!target_is_async_p ())
5921 ofunc = signal (SIGINT, remote_interrupt);
5922 /* If the user hit C-c before this packet, or between packets,
5923 pretend that it was hit right here. */
5924 if (check_quit_flag ())
5927 remote_interrupt (SIGINT);
5931 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5932 _never_ wait for ever -> test on target_is_async_p().
5933 However, before we do that we need to ensure that the caller
5934 knows how to take the target into/out of async mode. */
5935 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5936 wait_forever_enabled_p, &is_notif);
5938 /* GDB gets a notification. Return to core as this event is
5940 if (ret != -1 && is_notif)
5941 return minus_one_ptid;
5943 if (!target_is_async_p ())
5944 signal (SIGINT, ofunc);
5949 remote_stopped_by_watchpoint_p = 0;
5951 /* We got something. */
5952 rs->waiting_for_stop_reply = 0;
5954 /* Assume that the target has acknowledged Ctrl-C unless we receive
5955 an 'F' or 'O' packet. */
5956 if (buf[0] != 'F' && buf[0] != 'O')
5957 rs->ctrlc_pending_p = 0;
5961 case 'E': /* Error of some sort. */
5962 /* We're out of sync with the target now. Did it continue or
5963 not? Not is more likely, so report a stop. */
5964 warning (_("Remote failure reply: %s"), buf);
5965 status->kind = TARGET_WAITKIND_STOPPED;
5966 status->value.sig = GDB_SIGNAL_0;
5968 case 'F': /* File-I/O request. */
5969 remote_fileio_request (buf, rs->ctrlc_pending_p);
5970 rs->ctrlc_pending_p = 0;
5972 case 'T': case 'S': case 'X': case 'W':
5974 struct stop_reply *stop_reply
5975 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
5978 event_ptid = process_stop_reply (stop_reply, status);
5981 case 'O': /* Console output. */
5982 remote_console_output (buf + 1);
5984 /* The target didn't really stop; keep waiting. */
5985 rs->waiting_for_stop_reply = 1;
5989 if (last_sent_signal != GDB_SIGNAL_0)
5991 /* Zero length reply means that we tried 'S' or 'C' and the
5992 remote system doesn't support it. */
5993 target_terminal_ours_for_output ();
5995 ("Can't send signals to this remote system. %s not sent.\n",
5996 gdb_signal_to_name (last_sent_signal));
5997 last_sent_signal = GDB_SIGNAL_0;
5998 target_terminal_inferior ();
6000 strcpy ((char *) buf, last_sent_step ? "s" : "c");
6001 putpkt ((char *) buf);
6003 /* We just told the target to resume, so a stop reply is in
6005 rs->waiting_for_stop_reply = 1;
6008 /* else fallthrough */
6010 warning (_("Invalid remote reply: %s"), buf);
6012 rs->waiting_for_stop_reply = 1;
6016 if (status->kind == TARGET_WAITKIND_IGNORE)
6018 /* Nothing interesting happened. If we're doing a non-blocking
6019 poll, we're done. Otherwise, go back to waiting. */
6020 if (options & TARGET_WNOHANG)
6021 return minus_one_ptid;
6025 else if (status->kind != TARGET_WAITKIND_EXITED
6026 && status->kind != TARGET_WAITKIND_SIGNALLED)
6028 if (!ptid_equal (event_ptid, null_ptid))
6029 record_currthread (event_ptid);
6031 event_ptid = inferior_ptid;
6034 /* A process exit. Invalidate our notion of current thread. */
6035 record_currthread (minus_one_ptid);
6040 /* Wait until the remote machine stops, then return, storing status in
6041 STATUS just as `wait' would. */
6044 remote_wait (struct target_ops *ops,
6045 ptid_t ptid, struct target_waitstatus *status, int options)
6050 event_ptid = remote_wait_ns (ptid, status, options);
6052 event_ptid = remote_wait_as (ptid, status, options);
6054 if (target_can_async_p ())
6056 /* If there are are events left in the queue tell the event loop
6058 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6059 mark_async_event_handler (remote_async_inferior_event_token);
6065 /* Fetch a single register using a 'p' packet. */
6068 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6070 struct remote_state *rs = get_remote_state ();
6072 char regp[MAX_REGISTER_SIZE];
6075 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
6078 if (reg->pnum == -1)
6083 p += hexnumstr (p, reg->pnum);
6086 getpkt (&rs->buf, &rs->buf_size, 0);
6090 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6094 case PACKET_UNKNOWN:
6097 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6098 gdbarch_register_name (get_regcache_arch (regcache),
6103 /* If this register is unfetchable, tell the regcache. */
6106 regcache_raw_supply (regcache, reg->regnum, NULL);
6110 /* Otherwise, parse and supply the value. */
6116 error (_("fetch_register_using_p: early buf termination"));
6118 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6121 regcache_raw_supply (regcache, reg->regnum, regp);
6125 /* Fetch the registers included in the target's 'g' packet. */
6128 send_g_packet (void)
6130 struct remote_state *rs = get_remote_state ();
6133 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6134 remote_send (&rs->buf, &rs->buf_size);
6136 /* We can get out of synch in various cases. If the first character
6137 in the buffer is not a hex character, assume that has happened
6138 and try to fetch another packet to read. */
6139 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6140 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6141 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6142 && rs->buf[0] != 'x') /* New: unavailable register value. */
6145 fprintf_unfiltered (gdb_stdlog,
6146 "Bad register packet; fetching a new packet\n");
6147 getpkt (&rs->buf, &rs->buf_size, 0);
6150 buf_len = strlen (rs->buf);
6152 /* Sanity check the received packet. */
6153 if (buf_len % 2 != 0)
6154 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6160 process_g_packet (struct regcache *regcache)
6162 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6163 struct remote_state *rs = get_remote_state ();
6164 struct remote_arch_state *rsa = get_remote_arch_state ();
6169 buf_len = strlen (rs->buf);
6171 /* Further sanity checks, with knowledge of the architecture. */
6172 if (buf_len > 2 * rsa->sizeof_g_packet)
6173 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6175 /* Save the size of the packet sent to us by the target. It is used
6176 as a heuristic when determining the max size of packets that the
6177 target can safely receive. */
6178 if (rsa->actual_register_packet_size == 0)
6179 rsa->actual_register_packet_size = buf_len;
6181 /* If this is smaller than we guessed the 'g' packet would be,
6182 update our records. A 'g' reply that doesn't include a register's
6183 value implies either that the register is not available, or that
6184 the 'p' packet must be used. */
6185 if (buf_len < 2 * rsa->sizeof_g_packet)
6187 rsa->sizeof_g_packet = buf_len / 2;
6189 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6191 if (rsa->regs[i].pnum == -1)
6194 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6195 rsa->regs[i].in_g_packet = 0;
6197 rsa->regs[i].in_g_packet = 1;
6201 regs = alloca (rsa->sizeof_g_packet);
6203 /* Unimplemented registers read as all bits zero. */
6204 memset (regs, 0, rsa->sizeof_g_packet);
6206 /* Reply describes registers byte by byte, each byte encoded as two
6207 hex characters. Suck them all up, then supply them to the
6208 register cacheing/storage mechanism. */
6211 for (i = 0; i < rsa->sizeof_g_packet; i++)
6213 if (p[0] == 0 || p[1] == 0)
6214 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6215 internal_error (__FILE__, __LINE__,
6216 _("unexpected end of 'g' packet reply"));
6218 if (p[0] == 'x' && p[1] == 'x')
6219 regs[i] = 0; /* 'x' */
6221 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6225 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6227 struct packet_reg *r = &rsa->regs[i];
6231 if (r->offset * 2 >= strlen (rs->buf))
6232 /* This shouldn't happen - we adjusted in_g_packet above. */
6233 internal_error (__FILE__, __LINE__,
6234 _("unexpected end of 'g' packet reply"));
6235 else if (rs->buf[r->offset * 2] == 'x')
6237 gdb_assert (r->offset * 2 < strlen (rs->buf));
6238 /* The register isn't available, mark it as such (at
6239 the same time setting the value to zero). */
6240 regcache_raw_supply (regcache, r->regnum, NULL);
6243 regcache_raw_supply (regcache, r->regnum,
6250 fetch_registers_using_g (struct regcache *regcache)
6253 process_g_packet (regcache);
6256 /* Make the remote selected traceframe match GDB's selected
6260 set_remote_traceframe (void)
6264 if (remote_traceframe_number == get_traceframe_number ())
6267 /* Avoid recursion, remote_trace_find calls us again. */
6268 remote_traceframe_number = get_traceframe_number ();
6270 newnum = target_trace_find (tfind_number,
6271 get_traceframe_number (), 0, 0, NULL);
6273 /* Should not happen. If it does, all bets are off. */
6274 if (newnum != get_traceframe_number ())
6275 warning (_("could not set remote traceframe"));
6279 remote_fetch_registers (struct target_ops *ops,
6280 struct regcache *regcache, int regnum)
6282 struct remote_arch_state *rsa = get_remote_arch_state ();
6285 set_remote_traceframe ();
6286 set_general_thread (inferior_ptid);
6290 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6292 gdb_assert (reg != NULL);
6294 /* If this register might be in the 'g' packet, try that first -
6295 we are likely to read more than one register. If this is the
6296 first 'g' packet, we might be overly optimistic about its
6297 contents, so fall back to 'p'. */
6298 if (reg->in_g_packet)
6300 fetch_registers_using_g (regcache);
6301 if (reg->in_g_packet)
6305 if (fetch_register_using_p (regcache, reg))
6308 /* This register is not available. */
6309 regcache_raw_supply (regcache, reg->regnum, NULL);
6314 fetch_registers_using_g (regcache);
6316 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6317 if (!rsa->regs[i].in_g_packet)
6318 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6320 /* This register is not available. */
6321 regcache_raw_supply (regcache, i, NULL);
6325 /* Prepare to store registers. Since we may send them all (using a
6326 'G' request), we have to read out the ones we don't want to change
6330 remote_prepare_to_store (struct regcache *regcache)
6332 struct remote_arch_state *rsa = get_remote_arch_state ();
6334 gdb_byte buf[MAX_REGISTER_SIZE];
6336 /* Make sure the entire registers array is valid. */
6337 switch (remote_protocol_packets[PACKET_P].support)
6339 case PACKET_DISABLE:
6340 case PACKET_SUPPORT_UNKNOWN:
6341 /* Make sure all the necessary registers are cached. */
6342 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6343 if (rsa->regs[i].in_g_packet)
6344 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6351 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6352 packet was not recognized. */
6355 store_register_using_P (const struct regcache *regcache,
6356 struct packet_reg *reg)
6358 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6359 struct remote_state *rs = get_remote_state ();
6360 /* Try storing a single register. */
6361 char *buf = rs->buf;
6362 gdb_byte regp[MAX_REGISTER_SIZE];
6365 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
6368 if (reg->pnum == -1)
6371 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6372 p = buf + strlen (buf);
6373 regcache_raw_collect (regcache, reg->regnum, regp);
6374 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6376 getpkt (&rs->buf, &rs->buf_size, 0);
6378 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6383 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6384 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6385 case PACKET_UNKNOWN:
6388 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6392 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6393 contents of the register cache buffer. FIXME: ignores errors. */
6396 store_registers_using_G (const struct regcache *regcache)
6398 struct remote_state *rs = get_remote_state ();
6399 struct remote_arch_state *rsa = get_remote_arch_state ();
6403 /* Extract all the registers in the regcache copying them into a
6408 regs = alloca (rsa->sizeof_g_packet);
6409 memset (regs, 0, rsa->sizeof_g_packet);
6410 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6412 struct packet_reg *r = &rsa->regs[i];
6415 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6419 /* Command describes registers byte by byte,
6420 each byte encoded as two hex characters. */
6423 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6425 bin2hex (regs, p, rsa->sizeof_g_packet);
6427 getpkt (&rs->buf, &rs->buf_size, 0);
6428 if (packet_check_result (rs->buf) == PACKET_ERROR)
6429 error (_("Could not write registers; remote failure reply '%s'"),
6433 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6434 of the register cache buffer. FIXME: ignores errors. */
6437 remote_store_registers (struct target_ops *ops,
6438 struct regcache *regcache, int regnum)
6440 struct remote_arch_state *rsa = get_remote_arch_state ();
6443 set_remote_traceframe ();
6444 set_general_thread (inferior_ptid);
6448 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6450 gdb_assert (reg != NULL);
6452 /* Always prefer to store registers using the 'P' packet if
6453 possible; we often change only a small number of registers.
6454 Sometimes we change a larger number; we'd need help from a
6455 higher layer to know to use 'G'. */
6456 if (store_register_using_P (regcache, reg))
6459 /* For now, don't complain if we have no way to write the
6460 register. GDB loses track of unavailable registers too
6461 easily. Some day, this may be an error. We don't have
6462 any way to read the register, either... */
6463 if (!reg->in_g_packet)
6466 store_registers_using_G (regcache);
6470 store_registers_using_G (regcache);
6472 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6473 if (!rsa->regs[i].in_g_packet)
6474 if (!store_register_using_P (regcache, &rsa->regs[i]))
6475 /* See above for why we do not issue an error here. */
6480 /* Return the number of hex digits in num. */
6483 hexnumlen (ULONGEST num)
6487 for (i = 0; num != 0; i++)
6493 /* Set BUF to the minimum number of hex digits representing NUM. */
6496 hexnumstr (char *buf, ULONGEST num)
6498 int len = hexnumlen (num);
6500 return hexnumnstr (buf, num, len);
6504 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6507 hexnumnstr (char *buf, ULONGEST num, int width)
6513 for (i = width - 1; i >= 0; i--)
6515 buf[i] = "0123456789abcdef"[(num & 0xf)];
6522 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6525 remote_address_masked (CORE_ADDR addr)
6527 unsigned int address_size = remote_address_size;
6529 /* If "remoteaddresssize" was not set, default to target address size. */
6531 address_size = gdbarch_addr_bit (target_gdbarch ());
6533 if (address_size > 0
6534 && address_size < (sizeof (ULONGEST) * 8))
6536 /* Only create a mask when that mask can safely be constructed
6537 in a ULONGEST variable. */
6540 mask = (mask << address_size) - 1;
6546 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
6547 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
6548 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
6549 (which may be more than *OUT_LEN due to escape characters). The
6550 total number of bytes in the output buffer will be at most
6554 remote_escape_output (const gdb_byte *buffer, int len,
6555 gdb_byte *out_buf, int *out_len,
6558 int input_index, output_index;
6561 for (input_index = 0; input_index < len; input_index++)
6563 gdb_byte b = buffer[input_index];
6565 if (b == '$' || b == '#' || b == '}')
6567 /* These must be escaped. */
6568 if (output_index + 2 > out_maxlen)
6570 out_buf[output_index++] = '}';
6571 out_buf[output_index++] = b ^ 0x20;
6575 if (output_index + 1 > out_maxlen)
6577 out_buf[output_index++] = b;
6581 *out_len = input_index;
6582 return output_index;
6585 /* Convert BUFFER, escaped data LEN bytes long, into binary data
6586 in OUT_BUF. Return the number of bytes written to OUT_BUF.
6587 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
6589 This function reverses remote_escape_output. It allows more
6590 escaped characters than that function does, in particular because
6591 '*' must be escaped to avoid the run-length encoding processing
6592 in reading packets. */
6595 remote_unescape_input (const gdb_byte *buffer, int len,
6596 gdb_byte *out_buf, int out_maxlen)
6598 int input_index, output_index;
6603 for (input_index = 0; input_index < len; input_index++)
6605 gdb_byte b = buffer[input_index];
6607 if (output_index + 1 > out_maxlen)
6609 warning (_("Received too much data from remote target;"
6610 " ignoring overflow."));
6611 return output_index;
6616 out_buf[output_index++] = b ^ 0x20;
6622 out_buf[output_index++] = b;
6626 error (_("Unmatched escape character in target response."));
6628 return output_index;
6631 /* Determine whether the remote target supports binary downloading.
6632 This is accomplished by sending a no-op memory write of zero length
6633 to the target at the specified address. It does not suffice to send
6634 the whole packet, since many stubs strip the eighth bit and
6635 subsequently compute a wrong checksum, which causes real havoc with
6638 NOTE: This can still lose if the serial line is not eight-bit
6639 clean. In cases like this, the user should clear "remote
6643 check_binary_download (CORE_ADDR addr)
6645 struct remote_state *rs = get_remote_state ();
6647 switch (remote_protocol_packets[PACKET_X].support)
6649 case PACKET_DISABLE:
6653 case PACKET_SUPPORT_UNKNOWN:
6659 p += hexnumstr (p, (ULONGEST) addr);
6661 p += hexnumstr (p, (ULONGEST) 0);
6665 putpkt_binary (rs->buf, (int) (p - rs->buf));
6666 getpkt (&rs->buf, &rs->buf_size, 0);
6668 if (rs->buf[0] == '\0')
6671 fprintf_unfiltered (gdb_stdlog,
6672 "binary downloading NOT "
6673 "supported by target\n");
6674 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6679 fprintf_unfiltered (gdb_stdlog,
6680 "binary downloading supported by target\n");
6681 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6688 /* Write memory data directly to the remote machine.
6689 This does not inform the data cache; the data cache uses this.
6690 HEADER is the starting part of the packet.
6691 MEMADDR is the address in the remote memory space.
6692 MYADDR is the address of the buffer in our space.
6693 LEN is the number of bytes.
6694 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6695 should send data as binary ('X'), or hex-encoded ('M').
6697 The function creates packet of the form
6698 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6700 where encoding of <DATA> is termined by PACKET_FORMAT.
6702 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6705 Returns the number of bytes transferred, or 0 (setting errno) for
6706 error. Only transfer a single packet. */
6709 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6710 const gdb_byte *myaddr, ssize_t len,
6711 char packet_format, int use_length)
6713 struct remote_state *rs = get_remote_state ();
6723 if (packet_format != 'X' && packet_format != 'M')
6724 internal_error (__FILE__, __LINE__,
6725 _("remote_write_bytes_aux: bad packet format"));
6730 payload_size = get_memory_write_packet_size ();
6732 /* The packet buffer will be large enough for the payload;
6733 get_memory_packet_size ensures this. */
6736 /* Compute the size of the actual payload by subtracting out the
6737 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6739 payload_size -= strlen ("$,:#NN");
6741 /* The comma won't be used. */
6743 header_length = strlen (header);
6744 payload_size -= header_length;
6745 payload_size -= hexnumlen (memaddr);
6747 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6749 strcat (rs->buf, header);
6750 p = rs->buf + strlen (header);
6752 /* Compute a best guess of the number of bytes actually transfered. */
6753 if (packet_format == 'X')
6755 /* Best guess at number of bytes that will fit. */
6756 todo = min (len, payload_size);
6758 payload_size -= hexnumlen (todo);
6759 todo = min (todo, payload_size);
6763 /* Num bytes that will fit. */
6764 todo = min (len, payload_size / 2);
6766 payload_size -= hexnumlen (todo);
6767 todo = min (todo, payload_size / 2);
6771 internal_error (__FILE__, __LINE__,
6772 _("minimum packet size too small to write data"));
6774 /* If we already need another packet, then try to align the end
6775 of this packet to a useful boundary. */
6776 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6777 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6779 /* Append "<memaddr>". */
6780 memaddr = remote_address_masked (memaddr);
6781 p += hexnumstr (p, (ULONGEST) memaddr);
6788 /* Append <len>. Retain the location/size of <len>. It may need to
6789 be adjusted once the packet body has been created. */
6791 plenlen = hexnumstr (p, (ULONGEST) todo);
6799 /* Append the packet body. */
6800 if (packet_format == 'X')
6802 /* Binary mode. Send target system values byte by byte, in
6803 increasing byte addresses. Only escape certain critical
6805 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6806 &nr_bytes, payload_size);
6808 /* If not all TODO bytes fit, then we'll need another packet. Make
6809 a second try to keep the end of the packet aligned. Don't do
6810 this if the packet is tiny. */
6811 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6815 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6817 if (new_nr_bytes != nr_bytes)
6818 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6819 (gdb_byte *) p, &nr_bytes,
6823 p += payload_length;
6824 if (use_length && nr_bytes < todo)
6826 /* Escape chars have filled up the buffer prematurely,
6827 and we have actually sent fewer bytes than planned.
6828 Fix-up the length field of the packet. Use the same
6829 number of characters as before. */
6830 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6831 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6836 /* Normal mode: Send target system values byte by byte, in
6837 increasing byte addresses. Each byte is encoded as a two hex
6839 nr_bytes = bin2hex (myaddr, p, todo);
6843 putpkt_binary (rs->buf, (int) (p - rs->buf));
6844 getpkt (&rs->buf, &rs->buf_size, 0);
6846 if (rs->buf[0] == 'E')
6848 /* There is no correspondance between what the remote protocol
6849 uses for errors and errno codes. We would like a cleaner way
6850 of representing errors (big enough to include errno codes,
6851 bfd_error codes, and others). But for now just return EIO. */
6856 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6857 fewer bytes than we'd planned. */
6861 /* Write memory data directly to the remote machine.
6862 This does not inform the data cache; the data cache uses this.
6863 MEMADDR is the address in the remote memory space.
6864 MYADDR is the address of the buffer in our space.
6865 LEN is the number of bytes.
6867 Returns number of bytes transferred, or 0 (setting errno) for
6868 error. Only transfer a single packet. */
6871 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
6873 char *packet_format = 0;
6875 /* Check whether the target supports binary download. */
6876 check_binary_download (memaddr);
6878 switch (remote_protocol_packets[PACKET_X].support)
6881 packet_format = "X";
6883 case PACKET_DISABLE:
6884 packet_format = "M";
6886 case PACKET_SUPPORT_UNKNOWN:
6887 internal_error (__FILE__, __LINE__,
6888 _("remote_write_bytes: bad internal state"));
6890 internal_error (__FILE__, __LINE__, _("bad switch"));
6893 return remote_write_bytes_aux (packet_format,
6894 memaddr, myaddr, len, packet_format[0], 1);
6897 /* Read memory data directly from the remote machine.
6898 This does not use the data cache; the data cache uses this.
6899 MEMADDR is the address in the remote memory space.
6900 MYADDR is the address of the buffer in our space.
6901 LEN is the number of bytes.
6903 Returns number of bytes transferred, or 0 for error. */
6906 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
6908 struct remote_state *rs = get_remote_state ();
6909 int max_buf_size; /* Max size of packet output buffer. */
6917 max_buf_size = get_memory_read_packet_size ();
6918 /* The packet buffer will be large enough for the payload;
6919 get_memory_packet_size ensures this. */
6921 /* Number if bytes that will fit. */
6922 todo = min (len, max_buf_size / 2);
6924 /* Construct "m"<memaddr>","<len>". */
6925 memaddr = remote_address_masked (memaddr);
6928 p += hexnumstr (p, (ULONGEST) memaddr);
6930 p += hexnumstr (p, (ULONGEST) todo);
6933 getpkt (&rs->buf, &rs->buf_size, 0);
6934 if (rs->buf[0] == 'E'
6935 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6936 && rs->buf[3] == '\0')
6938 /* There is no correspondance between what the remote protocol
6939 uses for errors and errno codes. We would like a cleaner way
6940 of representing errors (big enough to include errno codes,
6941 bfd_error codes, and others). But for now just return
6946 /* Reply describes memory byte by byte, each byte encoded as two hex
6949 i = hex2bin (p, myaddr, todo);
6950 /* Return what we have. Let higher layers handle partial reads. */
6955 /* Read or write LEN bytes from inferior memory at MEMADDR,
6956 transferring to or from debugger address BUFFER. Write to inferior
6957 if SHOULD_WRITE is nonzero. Returns length of data written or
6958 read; 0 for error. TARGET is unused. */
6961 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
6962 int should_write, struct mem_attrib *attrib,
6963 struct target_ops *target)
6967 set_remote_traceframe ();
6968 set_general_thread (inferior_ptid);
6971 res = remote_write_bytes (mem_addr, buffer, mem_len);
6973 res = remote_read_bytes (mem_addr, buffer, mem_len);
6978 /* Sends a packet with content determined by the printf format string
6979 FORMAT and the remaining arguments, then gets the reply. Returns
6980 whether the packet was a success, a failure, or unknown. */
6982 static enum packet_result
6983 remote_send_printf (const char *format, ...)
6985 struct remote_state *rs = get_remote_state ();
6986 int max_size = get_remote_packet_size ();
6989 va_start (ap, format);
6992 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
6993 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
6995 if (putpkt (rs->buf) < 0)
6996 error (_("Communication problem with target."));
6999 getpkt (&rs->buf, &rs->buf_size, 0);
7001 return packet_check_result (rs->buf);
7005 restore_remote_timeout (void *p)
7007 int value = *(int *)p;
7009 remote_timeout = value;
7012 /* Flash writing can take quite some time. We'll set
7013 effectively infinite timeout for flash operations.
7014 In future, we'll need to decide on a better approach. */
7015 static const int remote_flash_timeout = 1000;
7018 remote_flash_erase (struct target_ops *ops,
7019 ULONGEST address, LONGEST length)
7021 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7022 int saved_remote_timeout = remote_timeout;
7023 enum packet_result ret;
7024 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7025 &saved_remote_timeout);
7027 remote_timeout = remote_flash_timeout;
7029 ret = remote_send_printf ("vFlashErase:%s,%s",
7030 phex (address, addr_size),
7034 case PACKET_UNKNOWN:
7035 error (_("Remote target does not support flash erase"));
7037 error (_("Error erasing flash with vFlashErase packet"));
7042 do_cleanups (back_to);
7046 remote_flash_write (struct target_ops *ops,
7047 ULONGEST address, LONGEST length,
7048 const gdb_byte *data)
7050 int saved_remote_timeout = remote_timeout;
7052 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7053 &saved_remote_timeout);
7055 remote_timeout = remote_flash_timeout;
7056 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
7057 do_cleanups (back_to);
7063 remote_flash_done (struct target_ops *ops)
7065 int saved_remote_timeout = remote_timeout;
7067 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7068 &saved_remote_timeout);
7070 remote_timeout = remote_flash_timeout;
7071 ret = remote_send_printf ("vFlashDone");
7072 do_cleanups (back_to);
7076 case PACKET_UNKNOWN:
7077 error (_("Remote target does not support vFlashDone"));
7079 error (_("Error finishing flash operation"));
7086 remote_files_info (struct target_ops *ignore)
7088 puts_filtered ("Debugging a target over a serial line.\n");
7091 /* Stuff for dealing with the packets which are part of this protocol.
7092 See comment at top of file for details. */
7094 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7095 error to higher layers. Called when a serial error is detected.
7096 The exception message is STRING, followed by a colon and a blank,
7097 the system error message for errno at function entry and final dot
7098 for output compatibility with throw_perror_with_name. */
7101 unpush_and_perror (const char *string)
7103 int saved_errno = errno;
7105 remote_unpush_target ();
7106 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7107 safe_strerror (saved_errno));
7110 /* Read a single character from the remote end. */
7113 readchar (int timeout)
7117 ch = serial_readchar (remote_desc, timeout);
7122 switch ((enum serial_rc) ch)
7125 remote_unpush_target ();
7126 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7129 unpush_and_perror (_("Remote communication error. "
7130 "Target disconnected."));
7132 case SERIAL_TIMEOUT:
7138 /* Wrapper for serial_write that closes the target and throws if
7142 remote_serial_write (const char *str, int len)
7144 if (serial_write (remote_desc, str, len))
7146 unpush_and_perror (_("Remote communication error. "
7147 "Target disconnected."));
7151 /* Send the command in *BUF to the remote machine, and read the reply
7152 into *BUF. Report an error if we get an error reply. Resize
7153 *BUF using xrealloc if necessary to hold the result, and update
7157 remote_send (char **buf,
7161 getpkt (buf, sizeof_buf, 0);
7163 if ((*buf)[0] == 'E')
7164 error (_("Remote failure reply: %s"), *buf);
7167 /* Return a pointer to an xmalloc'ed string representing an escaped
7168 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7169 etc. The caller is responsible for releasing the returned
7173 escape_buffer (const char *buf, int n)
7175 struct cleanup *old_chain;
7176 struct ui_file *stb;
7179 stb = mem_fileopen ();
7180 old_chain = make_cleanup_ui_file_delete (stb);
7182 fputstrn_unfiltered (buf, n, 0, stb);
7183 str = ui_file_xstrdup (stb, NULL);
7184 do_cleanups (old_chain);
7188 /* Display a null-terminated packet on stdout, for debugging, using C
7192 print_packet (char *buf)
7194 puts_filtered ("\"");
7195 fputstr_filtered (buf, '"', gdb_stdout);
7196 puts_filtered ("\"");
7202 return putpkt_binary (buf, strlen (buf));
7205 /* Send a packet to the remote machine, with error checking. The data
7206 of the packet is in BUF. The string in BUF can be at most
7207 get_remote_packet_size () - 5 to account for the $, # and checksum,
7208 and for a possible /0 if we are debugging (remote_debug) and want
7209 to print the sent packet as a string. */
7212 putpkt_binary (char *buf, int cnt)
7214 struct remote_state *rs = get_remote_state ();
7216 unsigned char csum = 0;
7217 char *buf2 = alloca (cnt + 6);
7224 /* Catch cases like trying to read memory or listing threads while
7225 we're waiting for a stop reply. The remote server wouldn't be
7226 ready to handle this request, so we'd hang and timeout. We don't
7227 have to worry about this in synchronous mode, because in that
7228 case it's not possible to issue a command while the target is
7229 running. This is not a problem in non-stop mode, because in that
7230 case, the stub is always ready to process serial input. */
7231 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
7232 error (_("Cannot execute this command while the target is running."));
7234 /* We're sending out a new packet. Make sure we don't look at a
7235 stale cached response. */
7236 rs->cached_wait_status = 0;
7238 /* Copy the packet into buffer BUF2, encapsulating it
7239 and giving it a checksum. */
7244 for (i = 0; i < cnt; i++)
7250 *p++ = tohex ((csum >> 4) & 0xf);
7251 *p++ = tohex (csum & 0xf);
7253 /* Send it over and over until we get a positive ack. */
7257 int started_error_output = 0;
7261 struct cleanup *old_chain;
7265 str = escape_buffer (buf2, p - buf2);
7266 old_chain = make_cleanup (xfree, str);
7267 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7268 gdb_flush (gdb_stdlog);
7269 do_cleanups (old_chain);
7271 remote_serial_write (buf2, p - buf2);
7273 /* If this is a no acks version of the remote protocol, send the
7274 packet and move on. */
7278 /* Read until either a timeout occurs (-2) or '+' is read.
7279 Handle any notification that arrives in the mean time. */
7282 ch = readchar (remote_timeout);
7290 case SERIAL_TIMEOUT:
7293 if (started_error_output)
7295 putchar_unfiltered ('\n');
7296 started_error_output = 0;
7305 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7309 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7311 case SERIAL_TIMEOUT:
7315 break; /* Retransmit buffer. */
7319 fprintf_unfiltered (gdb_stdlog,
7320 "Packet instead of Ack, ignoring it\n");
7321 /* It's probably an old response sent because an ACK
7322 was lost. Gobble up the packet and ack it so it
7323 doesn't get retransmitted when we resend this
7326 remote_serial_write ("+", 1);
7327 continue; /* Now, go look for +. */
7334 /* If we got a notification, handle it, and go back to looking
7336 /* We've found the start of a notification. Now
7337 collect the data. */
7338 val = read_frame (&rs->buf, &rs->buf_size);
7343 struct cleanup *old_chain;
7346 str = escape_buffer (rs->buf, val);
7347 old_chain = make_cleanup (xfree, str);
7348 fprintf_unfiltered (gdb_stdlog,
7349 " Notification received: %s\n",
7351 do_cleanups (old_chain);
7353 handle_notification (rs->buf);
7354 /* We're in sync now, rewait for the ack. */
7361 if (!started_error_output)
7363 started_error_output = 1;
7364 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7366 fputc_unfiltered (ch & 0177, gdb_stdlog);
7367 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7376 if (!started_error_output)
7378 started_error_output = 1;
7379 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7381 fputc_unfiltered (ch & 0177, gdb_stdlog);
7385 break; /* Here to retransmit. */
7389 /* This is wrong. If doing a long backtrace, the user should be
7390 able to get out next time we call QUIT, without anything as
7391 violent as interrupt_query. If we want to provide a way out of
7392 here without getting to the next QUIT, it should be based on
7393 hitting ^C twice as in remote_wait. */
7404 /* Come here after finding the start of a frame when we expected an
7405 ack. Do our best to discard the rest of this packet. */
7414 c = readchar (remote_timeout);
7417 case SERIAL_TIMEOUT:
7418 /* Nothing we can do. */
7421 /* Discard the two bytes of checksum and stop. */
7422 c = readchar (remote_timeout);
7424 c = readchar (remote_timeout);
7427 case '*': /* Run length encoding. */
7428 /* Discard the repeat count. */
7429 c = readchar (remote_timeout);
7434 /* A regular character. */
7440 /* Come here after finding the start of the frame. Collect the rest
7441 into *BUF, verifying the checksum, length, and handling run-length
7442 compression. NUL terminate the buffer. If there is not enough room,
7443 expand *BUF using xrealloc.
7445 Returns -1 on error, number of characters in buffer (ignoring the
7446 trailing NULL) on success. (could be extended to return one of the
7447 SERIAL status indications). */
7450 read_frame (char **buf_p,
7457 struct remote_state *rs = get_remote_state ();
7464 c = readchar (remote_timeout);
7467 case SERIAL_TIMEOUT:
7469 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7473 fputs_filtered ("Saw new packet start in middle of old one\n",
7475 return -1; /* Start a new packet, count retries. */
7478 unsigned char pktcsum;
7484 check_0 = readchar (remote_timeout);
7486 check_1 = readchar (remote_timeout);
7488 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7491 fputs_filtered ("Timeout in checksum, retrying\n",
7495 else if (check_0 < 0 || check_1 < 0)
7498 fputs_filtered ("Communication error in checksum\n",
7503 /* Don't recompute the checksum; with no ack packets we
7504 don't have any way to indicate a packet retransmission
7509 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7510 if (csum == pktcsum)
7515 struct cleanup *old_chain;
7518 str = escape_buffer (buf, bc);
7519 old_chain = make_cleanup (xfree, str);
7520 fprintf_unfiltered (gdb_stdlog,
7521 "Bad checksum, sentsum=0x%x, "
7522 "csum=0x%x, buf=%s\n",
7523 pktcsum, csum, str);
7524 do_cleanups (old_chain);
7526 /* Number of characters in buffer ignoring trailing
7530 case '*': /* Run length encoding. */
7535 c = readchar (remote_timeout);
7537 repeat = c - ' ' + 3; /* Compute repeat count. */
7539 /* The character before ``*'' is repeated. */
7541 if (repeat > 0 && repeat <= 255 && bc > 0)
7543 if (bc + repeat - 1 >= *sizeof_buf - 1)
7545 /* Make some more room in the buffer. */
7546 *sizeof_buf += repeat;
7547 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7551 memset (&buf[bc], buf[bc - 1], repeat);
7557 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7561 if (bc >= *sizeof_buf - 1)
7563 /* Make some more room in the buffer. */
7565 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7576 /* Read a packet from the remote machine, with error checking, and
7577 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7578 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7579 rather than timing out; this is used (in synchronous mode) to wait
7580 for a target that is is executing user code to stop. */
7581 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7582 don't have to change all the calls to getpkt to deal with the
7583 return value, because at the moment I don't know what the right
7584 thing to do it for those. */
7592 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7596 /* Read a packet from the remote machine, with error checking, and
7597 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7598 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7599 rather than timing out; this is used (in synchronous mode) to wait
7600 for a target that is is executing user code to stop. If FOREVER ==
7601 0, this function is allowed to time out gracefully and return an
7602 indication of this to the caller. Otherwise return the number of
7603 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7604 enough reason to return to the caller. *IS_NOTIF is an output
7605 boolean that indicates whether *BUF holds a notification or not
7606 (a regular packet). */
7609 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7610 int expecting_notif, int *is_notif)
7612 struct remote_state *rs = get_remote_state ();
7618 /* We're reading a new response. Make sure we don't look at a
7619 previously cached response. */
7620 rs->cached_wait_status = 0;
7622 strcpy (*buf, "timeout");
7625 timeout = watchdog > 0 ? watchdog : -1;
7626 else if (expecting_notif)
7627 timeout = 0; /* There should already be a char in the buffer. If
7630 timeout = remote_timeout;
7634 /* Process any number of notifications, and then return when
7638 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
7640 for (tries = 1; tries <= MAX_TRIES; tries++)
7642 /* This can loop forever if the remote side sends us
7643 characters continuously, but if it pauses, we'll get
7644 SERIAL_TIMEOUT from readchar because of timeout. Then
7645 we'll count that as a retry.
7647 Note that even when forever is set, we will only wait
7648 forever prior to the start of a packet. After that, we
7649 expect characters to arrive at a brisk pace. They should
7650 show up within remote_timeout intervals. */
7652 c = readchar (timeout);
7653 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7655 if (c == SERIAL_TIMEOUT)
7657 if (expecting_notif)
7658 return -1; /* Don't complain, it's normal to not get
7659 anything in this case. */
7661 if (forever) /* Watchdog went off? Kill the target. */
7664 remote_unpush_target ();
7665 throw_error (TARGET_CLOSE_ERROR,
7666 _("Watchdog timeout has expired. "
7667 "Target detached."));
7670 fputs_filtered ("Timed out.\n", gdb_stdlog);
7674 /* We've found the start of a packet or notification.
7675 Now collect the data. */
7676 val = read_frame (buf, sizeof_buf);
7681 remote_serial_write ("-", 1);
7684 if (tries > MAX_TRIES)
7686 /* We have tried hard enough, and just can't receive the
7687 packet/notification. Give up. */
7688 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7690 /* Skip the ack char if we're in no-ack mode. */
7691 if (!rs->noack_mode)
7692 remote_serial_write ("+", 1);
7696 /* If we got an ordinary packet, return that to our caller. */
7701 struct cleanup *old_chain;
7704 str = escape_buffer (*buf, val);
7705 old_chain = make_cleanup (xfree, str);
7706 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7707 do_cleanups (old_chain);
7710 /* Skip the ack char if we're in no-ack mode. */
7711 if (!rs->noack_mode)
7712 remote_serial_write ("+", 1);
7713 if (is_notif != NULL)
7718 /* If we got a notification, handle it, and go back to looking
7722 gdb_assert (c == '%');
7726 struct cleanup *old_chain;
7729 str = escape_buffer (*buf, val);
7730 old_chain = make_cleanup (xfree, str);
7731 fprintf_unfiltered (gdb_stdlog,
7732 " Notification received: %s\n",
7734 do_cleanups (old_chain);
7736 if (is_notif != NULL)
7739 handle_notification (*buf);
7741 /* Notifications require no acknowledgement. */
7743 if (expecting_notif)
7750 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7752 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7756 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7759 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7764 /* A helper function that just calls putpkt; for type correctness. */
7767 putpkt_for_catch_errors (void *arg)
7769 return putpkt (arg);
7773 remote_kill (struct target_ops *ops)
7775 /* Use catch_errors so the user can quit from gdb even when we
7776 aren't on speaking terms with the remote system. */
7777 catch_errors (putpkt_for_catch_errors, "k", "", RETURN_MASK_ERROR);
7779 /* Don't wait for it to die. I'm not really sure it matters whether
7780 we do or not. For the existing stubs, kill is a noop. */
7781 target_mourn_inferior ();
7785 remote_vkill (int pid, struct remote_state *rs)
7787 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7790 /* Tell the remote target to detach. */
7791 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7793 getpkt (&rs->buf, &rs->buf_size, 0);
7795 if (packet_ok (rs->buf,
7796 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7798 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7805 extended_remote_kill (struct target_ops *ops)
7808 int pid = ptid_get_pid (inferior_ptid);
7809 struct remote_state *rs = get_remote_state ();
7811 res = remote_vkill (pid, rs);
7812 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7814 /* Don't try 'k' on a multi-process aware stub -- it has no way
7815 to specify the pid. */
7819 getpkt (&rs->buf, &rs->buf_size, 0);
7820 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7823 /* Don't wait for it to die. I'm not really sure it matters whether
7824 we do or not. For the existing stubs, kill is a noop. */
7830 error (_("Can't kill process"));
7832 target_mourn_inferior ();
7836 remote_mourn (struct target_ops *ops)
7838 remote_mourn_1 (ops);
7841 /* Worker function for remote_mourn. */
7843 remote_mourn_1 (struct target_ops *target)
7845 unpush_target (target);
7847 /* remote_close takes care of doing most of the clean up. */
7848 generic_mourn_inferior ();
7852 extended_remote_mourn_1 (struct target_ops *target)
7854 struct remote_state *rs = get_remote_state ();
7856 /* In case we got here due to an error, but we're going to stay
7858 rs->waiting_for_stop_reply = 0;
7860 /* If the current general thread belonged to the process we just
7861 detached from or has exited, the remote side current general
7862 thread becomes undefined. Considering a case like this:
7864 - We just got here due to a detach.
7865 - The process that we're detaching from happens to immediately
7866 report a global breakpoint being hit in non-stop mode, in the
7867 same thread we had selected before.
7868 - GDB attaches to this process again.
7869 - This event happens to be the next event we handle.
7871 GDB would consider that the current general thread didn't need to
7872 be set on the stub side (with Hg), since for all it knew,
7873 GENERAL_THREAD hadn't changed.
7875 Notice that although in all-stop mode, the remote server always
7876 sets the current thread to the thread reporting the stop event,
7877 that doesn't happen in non-stop mode; in non-stop, the stub *must
7878 not* change the current thread when reporting a breakpoint hit,
7879 due to the decoupling of event reporting and event handling.
7881 To keep things simple, we always invalidate our notion of the
7883 record_currthread (minus_one_ptid);
7885 /* Unlike "target remote", we do not want to unpush the target; then
7886 the next time the user says "run", we won't be connected. */
7888 /* Call common code to mark the inferior as not running. */
7889 generic_mourn_inferior ();
7891 if (!have_inferiors ())
7893 if (!remote_multi_process_p (rs))
7895 /* Check whether the target is running now - some remote stubs
7896 automatically restart after kill. */
7898 getpkt (&rs->buf, &rs->buf_size, 0);
7900 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7902 /* Assume that the target has been restarted. Set
7903 inferior_ptid so that bits of core GDB realizes
7904 there's something here, e.g., so that the user can
7905 say "kill" again. */
7906 inferior_ptid = magic_null_ptid;
7913 extended_remote_mourn (struct target_ops *ops)
7915 extended_remote_mourn_1 (ops);
7919 extended_remote_supports_disable_randomization (void)
7921 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7926 extended_remote_disable_randomization (int val)
7928 struct remote_state *rs = get_remote_state ();
7931 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7934 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7936 error (_("Target does not support QDisableRandomization."));
7937 if (strcmp (reply, "OK") != 0)
7938 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7942 extended_remote_run (char *args)
7944 struct remote_state *rs = get_remote_state ();
7947 /* If the user has disabled vRun support, or we have detected that
7948 support is not available, do not try it. */
7949 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7952 strcpy (rs->buf, "vRun;");
7953 len = strlen (rs->buf);
7955 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7956 error (_("Remote file name too long for run packet"));
7957 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7959 gdb_assert (args != NULL);
7962 struct cleanup *back_to;
7966 argv = gdb_buildargv (args);
7967 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7968 for (i = 0; argv[i] != NULL; i++)
7970 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7971 error (_("Argument list too long for run packet"));
7972 rs->buf[len++] = ';';
7973 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7975 do_cleanups (back_to);
7978 rs->buf[len++] = '\0';
7981 getpkt (&rs->buf, &rs->buf_size, 0);
7983 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
7985 /* We have a wait response. All is well. */
7988 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7989 /* It wasn't disabled before, but it is now. */
7993 if (remote_exec_file[0] == '\0')
7994 error (_("Running the default executable on the remote target failed; "
7995 "try \"set remote exec-file\"?"));
7997 error (_("Running \"%s\" on the remote target failed"),
8002 /* In the extended protocol we want to be able to do things like
8003 "run" and have them basically work as expected. So we need
8004 a special create_inferior function. We support changing the
8005 executable file and the command line arguments, but not the
8009 extended_remote_create_inferior_1 (char *exec_file, char *args,
8010 char **env, int from_tty)
8014 struct remote_state *rs = get_remote_state ();
8016 /* If running asynchronously, register the target file descriptor
8017 with the event loop. */
8018 if (target_can_async_p ())
8019 target_async (inferior_event_handler, 0);
8021 /* Disable address space randomization if requested (and supported). */
8022 if (extended_remote_supports_disable_randomization ())
8023 extended_remote_disable_randomization (disable_randomization);
8025 /* Now restart the remote server. */
8026 run_worked = extended_remote_run (args) != -1;
8029 /* vRun was not supported. Fail if we need it to do what the
8031 if (remote_exec_file[0])
8032 error (_("Remote target does not support \"set remote exec-file\""));
8034 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8036 /* Fall back to "R". */
8037 extended_remote_restart ();
8040 if (!have_inferiors ())
8042 /* Clean up from the last time we ran, before we mark the target
8043 running again. This will mark breakpoints uninserted, and
8044 get_offsets may insert breakpoints. */
8045 init_thread_list ();
8046 init_wait_for_inferior ();
8049 /* vRun's success return is a stop reply. */
8050 stop_reply = run_worked ? rs->buf : NULL;
8051 add_current_inferior_and_thread (stop_reply);
8053 /* Get updated offsets, if the stub uses qOffsets. */
8058 extended_remote_create_inferior (struct target_ops *ops,
8059 char *exec_file, char *args,
8060 char **env, int from_tty)
8062 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
8066 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8067 the list of conditions (in agent expression bytecode format), if any, the
8068 target needs to evaluate. The output is placed into the packet buffer
8069 started from BUF and ended at BUF_END. */
8072 remote_add_target_side_condition (struct gdbarch *gdbarch,
8073 struct bp_target_info *bp_tgt, char *buf,
8076 struct agent_expr *aexpr = NULL;
8079 char *buf_start = buf;
8081 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8084 buf += strlen (buf);
8085 xsnprintf (buf, buf_end - buf, "%s", ";");
8088 /* Send conditions to the target and free the vector. */
8090 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8093 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8094 buf += strlen (buf);
8095 for (i = 0; i < aexpr->len; ++i)
8096 buf = pack_hex_byte (buf, aexpr->buf[i]);
8100 VEC_free (agent_expr_p, bp_tgt->conditions);
8105 remote_add_target_side_commands (struct gdbarch *gdbarch,
8106 struct bp_target_info *bp_tgt, char *buf)
8108 struct agent_expr *aexpr = NULL;
8111 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8114 buf += strlen (buf);
8116 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8117 buf += strlen (buf);
8119 /* Concatenate all the agent expressions that are commands into the
8122 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8125 sprintf (buf, "X%x,", aexpr->len);
8126 buf += strlen (buf);
8127 for (i = 0; i < aexpr->len; ++i)
8128 buf = pack_hex_byte (buf, aexpr->buf[i]);
8132 VEC_free (agent_expr_p, bp_tgt->tcommands);
8135 /* Insert a breakpoint. On targets that have software breakpoint
8136 support, we ask the remote target to do the work; on targets
8137 which don't, we insert a traditional memory breakpoint. */
8140 remote_insert_breakpoint (struct gdbarch *gdbarch,
8141 struct bp_target_info *bp_tgt)
8143 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8144 If it succeeds, then set the support to PACKET_ENABLE. If it
8145 fails, and the user has explicitly requested the Z support then
8146 report an error, otherwise, mark it disabled and go on. */
8148 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
8150 CORE_ADDR addr = bp_tgt->placed_address;
8151 struct remote_state *rs;
8154 struct condition_list *cond = NULL;
8156 /* Make sure the remote is pointing at the right process, if
8158 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8159 set_general_process ();
8161 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8163 rs = get_remote_state ();
8165 endbuf = rs->buf + get_remote_packet_size ();
8170 addr = (ULONGEST) remote_address_masked (addr);
8171 p += hexnumstr (p, addr);
8172 xsnprintf (p, endbuf - p, ",%d", bpsize);
8174 if (remote_supports_cond_breakpoints ())
8175 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8177 if (remote_can_run_breakpoint_commands ())
8178 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8181 getpkt (&rs->buf, &rs->buf_size, 0);
8183 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8188 bp_tgt->placed_address = addr;
8189 bp_tgt->placed_size = bpsize;
8191 case PACKET_UNKNOWN:
8196 return memory_insert_breakpoint (gdbarch, bp_tgt);
8200 remote_remove_breakpoint (struct gdbarch *gdbarch,
8201 struct bp_target_info *bp_tgt)
8203 CORE_ADDR addr = bp_tgt->placed_address;
8204 struct remote_state *rs = get_remote_state ();
8206 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
8209 char *endbuf = rs->buf + get_remote_packet_size ();
8211 /* Make sure the remote is pointing at the right process, if
8213 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8214 set_general_process ();
8220 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8221 p += hexnumstr (p, addr);
8222 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8225 getpkt (&rs->buf, &rs->buf_size, 0);
8227 return (rs->buf[0] == 'E');
8230 return memory_remove_breakpoint (gdbarch, bp_tgt);
8234 watchpoint_to_Z_packet (int type)
8239 return Z_PACKET_WRITE_WP;
8242 return Z_PACKET_READ_WP;
8245 return Z_PACKET_ACCESS_WP;
8248 internal_error (__FILE__, __LINE__,
8249 _("hw_bp_to_z: bad watchpoint type %d"), type);
8254 remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
8255 struct expression *cond)
8257 struct remote_state *rs = get_remote_state ();
8258 char *endbuf = rs->buf + get_remote_packet_size ();
8260 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8262 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8265 /* Make sure the remote is pointing at the right process, if
8267 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8268 set_general_process ();
8270 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8271 p = strchr (rs->buf, '\0');
8272 addr = remote_address_masked (addr);
8273 p += hexnumstr (p, (ULONGEST) addr);
8274 xsnprintf (p, endbuf - p, ",%x", len);
8277 getpkt (&rs->buf, &rs->buf_size, 0);
8279 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8283 case PACKET_UNKNOWN:
8288 internal_error (__FILE__, __LINE__,
8289 _("remote_insert_watchpoint: reached end of function"));
8293 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8294 CORE_ADDR start, int length)
8296 CORE_ADDR diff = remote_address_masked (addr - start);
8298 return diff < length;
8303 remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
8304 struct expression *cond)
8306 struct remote_state *rs = get_remote_state ();
8307 char *endbuf = rs->buf + get_remote_packet_size ();
8309 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8311 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8314 /* Make sure the remote is pointing at the right process, if
8316 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8317 set_general_process ();
8319 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8320 p = strchr (rs->buf, '\0');
8321 addr = remote_address_masked (addr);
8322 p += hexnumstr (p, (ULONGEST) addr);
8323 xsnprintf (p, endbuf - p, ",%x", len);
8325 getpkt (&rs->buf, &rs->buf_size, 0);
8327 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8330 case PACKET_UNKNOWN:
8335 internal_error (__FILE__, __LINE__,
8336 _("remote_remove_watchpoint: reached end of function"));
8340 int remote_hw_watchpoint_limit = -1;
8341 int remote_hw_watchpoint_length_limit = -1;
8342 int remote_hw_breakpoint_limit = -1;
8345 remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
8347 if (remote_hw_watchpoint_length_limit == 0)
8349 else if (remote_hw_watchpoint_length_limit < 0)
8351 else if (len <= remote_hw_watchpoint_length_limit)
8358 remote_check_watch_resources (int type, int cnt, int ot)
8360 if (type == bp_hardware_breakpoint)
8362 if (remote_hw_breakpoint_limit == 0)
8364 else if (remote_hw_breakpoint_limit < 0)
8366 else if (cnt <= remote_hw_breakpoint_limit)
8371 if (remote_hw_watchpoint_limit == 0)
8373 else if (remote_hw_watchpoint_limit < 0)
8377 else if (cnt <= remote_hw_watchpoint_limit)
8384 remote_stopped_by_watchpoint (void)
8386 return remote_stopped_by_watchpoint_p;
8390 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8394 if (remote_stopped_by_watchpoint ())
8396 *addr_p = remote_watch_data_address;
8405 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
8406 struct bp_target_info *bp_tgt)
8409 struct remote_state *rs;
8413 /* The length field should be set to the size of a breakpoint
8414 instruction, even though we aren't inserting one ourselves. */
8416 gdbarch_remote_breakpoint_from_pc
8417 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
8419 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8422 /* Make sure the remote is pointing at the right process, if
8424 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8425 set_general_process ();
8427 rs = get_remote_state ();
8429 endbuf = rs->buf + get_remote_packet_size ();
8435 addr = remote_address_masked (bp_tgt->placed_address);
8436 p += hexnumstr (p, (ULONGEST) addr);
8437 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8439 if (remote_supports_cond_breakpoints ())
8440 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8442 if (remote_can_run_breakpoint_commands ())
8443 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8446 getpkt (&rs->buf, &rs->buf_size, 0);
8448 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8451 if (rs->buf[1] == '.')
8453 message = strchr (rs->buf + 2, '.');
8455 error (_("Remote failure reply: %s"), message + 1);
8458 case PACKET_UNKNOWN:
8463 internal_error (__FILE__, __LINE__,
8464 _("remote_insert_hw_breakpoint: reached end of function"));
8469 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
8470 struct bp_target_info *bp_tgt)
8473 struct remote_state *rs = get_remote_state ();
8475 char *endbuf = rs->buf + get_remote_packet_size ();
8477 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8480 /* Make sure the remote is pointing at the right process, if
8482 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8483 set_general_process ();
8489 addr = remote_address_masked (bp_tgt->placed_address);
8490 p += hexnumstr (p, (ULONGEST) addr);
8491 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8494 getpkt (&rs->buf, &rs->buf_size, 0);
8496 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8499 case PACKET_UNKNOWN:
8504 internal_error (__FILE__, __LINE__,
8505 _("remote_remove_hw_breakpoint: reached end of function"));
8508 /* Table used by the crc32 function to calcuate the checksum. */
8510 static unsigned long crc32_table[256] =
8513 static unsigned long
8514 crc32 (const unsigned char *buf, int len, unsigned int crc)
8516 if (!crc32_table[1])
8518 /* Initialize the CRC table and the decoding table. */
8522 for (i = 0; i < 256; i++)
8524 for (c = i << 24, j = 8; j > 0; --j)
8525 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
8532 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
8538 /* Verify memory using the "qCRC:" request. */
8541 remote_verify_memory (struct target_ops *ops,
8542 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8544 struct remote_state *rs = get_remote_state ();
8545 unsigned long host_crc, target_crc;
8548 /* Make sure the remote is pointing at the right process. */
8549 set_general_process ();
8551 /* FIXME: assumes lma can fit into long. */
8552 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8553 (long) lma, (long) size);
8556 /* Be clever; compute the host_crc before waiting for target
8558 host_crc = crc32 (data, size, 0xffffffff);
8560 getpkt (&rs->buf, &rs->buf_size, 0);
8561 if (rs->buf[0] == 'E')
8564 if (rs->buf[0] != 'C')
8565 error (_("remote target does not support this operation"));
8567 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8568 target_crc = target_crc * 16 + fromhex (*tmp);
8570 return (host_crc == target_crc);
8573 /* compare-sections command
8575 With no arguments, compares each loadable section in the exec bfd
8576 with the same memory range on the target, and reports mismatches.
8577 Useful for verifying the image on the target against the exec file. */
8580 compare_sections_command (char *args, int from_tty)
8583 struct cleanup *old_chain;
8585 const char *sectname;
8593 error (_("command cannot be used without an exec file"));
8595 /* Make sure the remote is pointing at the right process. */
8596 set_general_process ();
8598 for (s = exec_bfd->sections; s; s = s->next)
8600 if (!(s->flags & SEC_LOAD))
8601 continue; /* Skip non-loadable section. */
8603 size = bfd_get_section_size (s);
8605 continue; /* Skip zero-length section. */
8607 sectname = bfd_get_section_name (exec_bfd, s);
8608 if (args && strcmp (args, sectname) != 0)
8609 continue; /* Not the section selected by user. */
8611 matched = 1; /* Do this section. */
8614 sectdata = xmalloc (size);
8615 old_chain = make_cleanup (xfree, sectdata);
8616 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8618 res = target_verify_memory (sectdata, lma, size);
8621 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8622 paddress (target_gdbarch (), lma),
8623 paddress (target_gdbarch (), lma + size));
8625 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8626 paddress (target_gdbarch (), lma),
8627 paddress (target_gdbarch (), lma + size));
8629 printf_filtered ("matched.\n");
8632 printf_filtered ("MIS-MATCHED!\n");
8636 do_cleanups (old_chain);
8639 warning (_("One or more sections of the remote executable does not match\n\
8640 the loaded file\n"));
8641 if (args && !matched)
8642 printf_filtered (_("No loaded section named '%s'.\n"), args);
8645 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8646 into remote target. The number of bytes written to the remote
8647 target is returned, or -1 for error. */
8650 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8651 const char *annex, const gdb_byte *writebuf,
8652 ULONGEST offset, LONGEST len,
8653 struct packet_config *packet)
8657 struct remote_state *rs = get_remote_state ();
8658 int max_size = get_memory_write_packet_size ();
8660 if (packet->support == PACKET_DISABLE)
8663 /* Insert header. */
8664 i = snprintf (rs->buf, max_size,
8665 "qXfer:%s:write:%s:%s:",
8666 object_name, annex ? annex : "",
8667 phex_nz (offset, sizeof offset));
8668 max_size -= (i + 1);
8670 /* Escape as much data as fits into rs->buf. */
8671 buf_len = remote_escape_output
8672 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8674 if (putpkt_binary (rs->buf, i + buf_len) < 0
8675 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8676 || packet_ok (rs->buf, packet) != PACKET_OK)
8679 unpack_varlen_hex (rs->buf, &n);
8683 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8684 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8685 number of bytes read is returned, or 0 for EOF, or -1 for error.
8686 The number of bytes read may be less than LEN without indicating an
8687 EOF. PACKET is checked and updated to indicate whether the remote
8688 target supports this object. */
8691 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8693 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8694 struct packet_config *packet)
8696 static char *finished_object;
8697 static char *finished_annex;
8698 static ULONGEST finished_offset;
8700 struct remote_state *rs = get_remote_state ();
8701 LONGEST i, n, packet_len;
8703 if (packet->support == PACKET_DISABLE)
8706 /* Check whether we've cached an end-of-object packet that matches
8708 if (finished_object)
8710 if (strcmp (object_name, finished_object) == 0
8711 && strcmp (annex ? annex : "", finished_annex) == 0
8712 && offset == finished_offset)
8715 /* Otherwise, we're now reading something different. Discard
8717 xfree (finished_object);
8718 xfree (finished_annex);
8719 finished_object = NULL;
8720 finished_annex = NULL;
8723 /* Request only enough to fit in a single packet. The actual data
8724 may not, since we don't know how much of it will need to be escaped;
8725 the target is free to respond with slightly less data. We subtract
8726 five to account for the response type and the protocol frame. */
8727 n = min (get_remote_packet_size () - 5, len);
8728 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8729 object_name, annex ? annex : "",
8730 phex_nz (offset, sizeof offset),
8731 phex_nz (n, sizeof n));
8732 i = putpkt (rs->buf);
8737 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8738 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8741 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8742 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8744 /* 'm' means there is (or at least might be) more data after this
8745 batch. That does not make sense unless there's at least one byte
8746 of data in this reply. */
8747 if (rs->buf[0] == 'm' && packet_len == 1)
8748 error (_("Remote qXfer reply contained no data."));
8750 /* Got some data. */
8751 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8752 packet_len - 1, readbuf, n);
8754 /* 'l' is an EOF marker, possibly including a final block of data,
8755 or possibly empty. If we have the final block of a non-empty
8756 object, record this fact to bypass a subsequent partial read. */
8757 if (rs->buf[0] == 'l' && offset + i > 0)
8759 finished_object = xstrdup (object_name);
8760 finished_annex = xstrdup (annex ? annex : "");
8761 finished_offset = offset + i;
8768 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8769 const char *annex, gdb_byte *readbuf,
8770 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
8772 struct remote_state *rs;
8777 set_remote_traceframe ();
8778 set_general_thread (inferior_ptid);
8780 rs = get_remote_state ();
8782 /* Handle memory using the standard memory routines. */
8783 if (object == TARGET_OBJECT_MEMORY)
8789 /* If the remote target is connected but not running, we should
8790 pass this request down to a lower stratum (e.g. the executable
8792 if (!target_has_execution)
8795 if (writebuf != NULL)
8796 xfered = remote_write_bytes (offset, writebuf, len);
8798 xfered = remote_read_bytes (offset, readbuf, len);
8802 else if (xfered == 0 && errno == 0)
8808 /* Handle SPU memory using qxfer packets. */
8809 if (object == TARGET_OBJECT_SPU)
8812 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8813 &remote_protocol_packets
8814 [PACKET_qXfer_spu_read]);
8816 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8817 &remote_protocol_packets
8818 [PACKET_qXfer_spu_write]);
8821 /* Handle extra signal info using qxfer packets. */
8822 if (object == TARGET_OBJECT_SIGNAL_INFO)
8825 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8826 &remote_protocol_packets
8827 [PACKET_qXfer_siginfo_read]);
8829 return remote_write_qxfer (ops, "siginfo", annex,
8830 writebuf, offset, len,
8831 &remote_protocol_packets
8832 [PACKET_qXfer_siginfo_write]);
8835 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8838 return remote_read_qxfer (ops, "statictrace", annex,
8839 readbuf, offset, len,
8840 &remote_protocol_packets
8841 [PACKET_qXfer_statictrace_read]);
8846 /* Only handle flash writes. */
8847 if (writebuf != NULL)
8853 case TARGET_OBJECT_FLASH:
8854 xfered = remote_flash_write (ops, offset, len, writebuf);
8858 else if (xfered == 0 && errno == 0)
8868 /* Map pre-existing objects onto letters. DO NOT do this for new
8869 objects!!! Instead specify new query packets. */
8872 case TARGET_OBJECT_AVR:
8876 case TARGET_OBJECT_AUXV:
8877 gdb_assert (annex == NULL);
8878 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8879 &remote_protocol_packets[PACKET_qXfer_auxv]);
8881 case TARGET_OBJECT_AVAILABLE_FEATURES:
8882 return remote_read_qxfer
8883 (ops, "features", annex, readbuf, offset, len,
8884 &remote_protocol_packets[PACKET_qXfer_features]);
8886 case TARGET_OBJECT_LIBRARIES:
8887 return remote_read_qxfer
8888 (ops, "libraries", annex, readbuf, offset, len,
8889 &remote_protocol_packets[PACKET_qXfer_libraries]);
8891 case TARGET_OBJECT_LIBRARIES_SVR4:
8892 return remote_read_qxfer
8893 (ops, "libraries-svr4", annex, readbuf, offset, len,
8894 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8896 case TARGET_OBJECT_MEMORY_MAP:
8897 gdb_assert (annex == NULL);
8898 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8899 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8901 case TARGET_OBJECT_OSDATA:
8902 /* Should only get here if we're connected. */
8903 gdb_assert (remote_desc);
8904 return remote_read_qxfer
8905 (ops, "osdata", annex, readbuf, offset, len,
8906 &remote_protocol_packets[PACKET_qXfer_osdata]);
8908 case TARGET_OBJECT_THREADS:
8909 gdb_assert (annex == NULL);
8910 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8911 &remote_protocol_packets[PACKET_qXfer_threads]);
8913 case TARGET_OBJECT_TRACEFRAME_INFO:
8914 gdb_assert (annex == NULL);
8915 return remote_read_qxfer
8916 (ops, "traceframe-info", annex, readbuf, offset, len,
8917 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8919 case TARGET_OBJECT_FDPIC:
8920 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8921 &remote_protocol_packets[PACKET_qXfer_fdpic]);
8923 case TARGET_OBJECT_OPENVMS_UIB:
8924 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
8925 &remote_protocol_packets[PACKET_qXfer_uib]);
8927 case TARGET_OBJECT_BTRACE:
8928 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
8929 &remote_protocol_packets[PACKET_qXfer_btrace]);
8935 /* Note: a zero OFFSET and LEN can be used to query the minimum
8937 if (offset == 0 && len == 0)
8938 return (get_remote_packet_size ());
8939 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
8940 large enough let the caller deal with it. */
8941 if (len < get_remote_packet_size ())
8943 len = get_remote_packet_size ();
8945 /* Except for querying the minimum buffer size, target must be open. */
8947 error (_("remote query is only available after target open"));
8949 gdb_assert (annex != NULL);
8950 gdb_assert (readbuf != NULL);
8956 /* We used one buffer char for the remote protocol q command and
8957 another for the query type. As the remote protocol encapsulation
8958 uses 4 chars plus one extra in case we are debugging
8959 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8962 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8964 /* Bad caller may have sent forbidden characters. */
8965 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8970 gdb_assert (annex[i] == '\0');
8972 i = putpkt (rs->buf);
8976 getpkt (&rs->buf, &rs->buf_size, 0);
8977 strcpy ((char *) readbuf, rs->buf);
8979 return strlen ((char *) readbuf);
8983 remote_search_memory (struct target_ops* ops,
8984 CORE_ADDR start_addr, ULONGEST search_space_len,
8985 const gdb_byte *pattern, ULONGEST pattern_len,
8986 CORE_ADDR *found_addrp)
8988 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8989 struct remote_state *rs = get_remote_state ();
8990 int max_size = get_memory_write_packet_size ();
8991 struct packet_config *packet =
8992 &remote_protocol_packets[PACKET_qSearch_memory];
8993 /* Number of packet bytes used to encode the pattern;
8994 this could be more than PATTERN_LEN due to escape characters. */
8995 int escaped_pattern_len;
8996 /* Amount of pattern that was encodable in the packet. */
8997 int used_pattern_len;
9000 ULONGEST found_addr;
9002 /* Don't go to the target if we don't have to.
9003 This is done before checking packet->support to avoid the possibility that
9004 a success for this edge case means the facility works in general. */
9005 if (pattern_len > search_space_len)
9007 if (pattern_len == 0)
9009 *found_addrp = start_addr;
9013 /* If we already know the packet isn't supported, fall back to the simple
9014 way of searching memory. */
9016 if (packet->support == PACKET_DISABLE)
9018 /* Target doesn't provided special support, fall back and use the
9019 standard support (copy memory and do the search here). */
9020 return simple_search_memory (ops, start_addr, search_space_len,
9021 pattern, pattern_len, found_addrp);
9024 /* Make sure the remote is pointing at the right process. */
9025 set_general_process ();
9027 /* Insert header. */
9028 i = snprintf (rs->buf, max_size,
9029 "qSearch:memory:%s;%s;",
9030 phex_nz (start_addr, addr_size),
9031 phex_nz (search_space_len, sizeof (search_space_len)));
9032 max_size -= (i + 1);
9034 /* Escape as much data as fits into rs->buf. */
9035 escaped_pattern_len =
9036 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9037 &used_pattern_len, max_size);
9039 /* Bail if the pattern is too large. */
9040 if (used_pattern_len != pattern_len)
9041 error (_("Pattern is too large to transmit to remote target."));
9043 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9044 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9045 || packet_ok (rs->buf, packet) != PACKET_OK)
9047 /* The request may not have worked because the command is not
9048 supported. If so, fall back to the simple way. */
9049 if (packet->support == PACKET_DISABLE)
9051 return simple_search_memory (ops, start_addr, search_space_len,
9052 pattern, pattern_len, found_addrp);
9057 if (rs->buf[0] == '0')
9059 else if (rs->buf[0] == '1')
9062 if (rs->buf[1] != ',')
9063 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9064 unpack_varlen_hex (rs->buf + 2, &found_addr);
9065 *found_addrp = found_addr;
9068 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9074 remote_rcmd (char *command,
9075 struct ui_file *outbuf)
9077 struct remote_state *rs = get_remote_state ();
9081 error (_("remote rcmd is only available after target open"));
9083 /* Send a NULL command across as an empty command. */
9084 if (command == NULL)
9087 /* The query prefix. */
9088 strcpy (rs->buf, "qRcmd,");
9089 p = strchr (rs->buf, '\0');
9091 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9092 > get_remote_packet_size ())
9093 error (_("\"monitor\" command ``%s'' is too long."), command);
9095 /* Encode the actual command. */
9096 bin2hex ((gdb_byte *) command, p, 0);
9098 if (putpkt (rs->buf) < 0)
9099 error (_("Communication problem with target."));
9101 /* get/display the response */
9106 /* XXX - see also remote_get_noisy_reply(). */
9107 QUIT; /* Allow user to bail out with ^C. */
9109 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9111 /* Timeout. Continue to (try to) read responses.
9112 This is better than stopping with an error, assuming the stub
9113 is still executing the (long) monitor command.
9114 If needed, the user can interrupt gdb using C-c, obtaining
9115 an effect similar to stop on timeout. */
9120 error (_("Target does not support this command."));
9121 if (buf[0] == 'O' && buf[1] != 'K')
9123 remote_console_output (buf + 1); /* 'O' message from stub. */
9126 if (strcmp (buf, "OK") == 0)
9128 if (strlen (buf) == 3 && buf[0] == 'E'
9129 && isdigit (buf[1]) && isdigit (buf[2]))
9131 error (_("Protocol error with Rcmd"));
9133 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9135 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9137 fputc_unfiltered (c, outbuf);
9143 static VEC(mem_region_s) *
9144 remote_memory_map (struct target_ops *ops)
9146 VEC(mem_region_s) *result = NULL;
9147 char *text = target_read_stralloc (¤t_target,
9148 TARGET_OBJECT_MEMORY_MAP, NULL);
9152 struct cleanup *back_to = make_cleanup (xfree, text);
9154 result = parse_memory_map (text);
9155 do_cleanups (back_to);
9162 packet_command (char *args, int from_tty)
9164 struct remote_state *rs = get_remote_state ();
9167 error (_("command can only be used with remote target"));
9170 error (_("remote-packet command requires packet text as argument"));
9172 puts_filtered ("sending: ");
9173 print_packet (args);
9174 puts_filtered ("\n");
9177 getpkt (&rs->buf, &rs->buf_size, 0);
9178 puts_filtered ("received: ");
9179 print_packet (rs->buf);
9180 puts_filtered ("\n");
9184 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9186 static void display_thread_info (struct gdb_ext_thread_info *info);
9188 static void threadset_test_cmd (char *cmd, int tty);
9190 static void threadalive_test (char *cmd, int tty);
9192 static void threadlist_test_cmd (char *cmd, int tty);
9194 int get_and_display_threadinfo (threadref *ref);
9196 static void threadinfo_test_cmd (char *cmd, int tty);
9198 static int thread_display_step (threadref *ref, void *context);
9200 static void threadlist_update_test_cmd (char *cmd, int tty);
9202 static void init_remote_threadtests (void);
9204 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9207 threadset_test_cmd (char *cmd, int tty)
9209 int sample_thread = SAMPLE_THREAD;
9211 printf_filtered (_("Remote threadset test\n"));
9212 set_general_thread (sample_thread);
9217 threadalive_test (char *cmd, int tty)
9219 int sample_thread = SAMPLE_THREAD;
9220 int pid = ptid_get_pid (inferior_ptid);
9221 ptid_t ptid = ptid_build (pid, 0, sample_thread);
9223 if (remote_thread_alive (ptid))
9224 printf_filtered ("PASS: Thread alive test\n");
9226 printf_filtered ("FAIL: Thread alive test\n");
9229 void output_threadid (char *title, threadref *ref);
9232 output_threadid (char *title, threadref *ref)
9236 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9238 printf_filtered ("%s %s\n", title, (&hexid[0]));
9242 threadlist_test_cmd (char *cmd, int tty)
9245 threadref nextthread;
9246 int done, result_count;
9247 threadref threadlist[3];
9249 printf_filtered ("Remote Threadlist test\n");
9250 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9251 &result_count, &threadlist[0]))
9252 printf_filtered ("FAIL: threadlist test\n");
9255 threadref *scan = threadlist;
9256 threadref *limit = scan + result_count;
9258 while (scan < limit)
9259 output_threadid (" thread ", scan++);
9264 display_thread_info (struct gdb_ext_thread_info *info)
9266 output_threadid ("Threadid: ", &info->threadid);
9267 printf_filtered ("Name: %s\n ", info->shortname);
9268 printf_filtered ("State: %s\n", info->display);
9269 printf_filtered ("other: %s\n\n", info->more_display);
9273 get_and_display_threadinfo (threadref *ref)
9277 struct gdb_ext_thread_info threadinfo;
9279 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9280 | TAG_MOREDISPLAY | TAG_DISPLAY;
9281 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9282 display_thread_info (&threadinfo);
9287 threadinfo_test_cmd (char *cmd, int tty)
9289 int athread = SAMPLE_THREAD;
9293 int_to_threadref (&thread, athread);
9294 printf_filtered ("Remote Threadinfo test\n");
9295 if (!get_and_display_threadinfo (&thread))
9296 printf_filtered ("FAIL cannot get thread info\n");
9300 thread_display_step (threadref *ref, void *context)
9302 /* output_threadid(" threadstep ",ref); *//* simple test */
9303 return get_and_display_threadinfo (ref);
9307 threadlist_update_test_cmd (char *cmd, int tty)
9309 printf_filtered ("Remote Threadlist update test\n");
9310 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9314 init_remote_threadtests (void)
9316 add_com ("tlist", class_obscure, threadlist_test_cmd,
9317 _("Fetch and print the remote list of "
9318 "thread identifiers, one pkt only"));
9319 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9320 _("Fetch and display info about one thread"));
9321 add_com ("tset", class_obscure, threadset_test_cmd,
9322 _("Test setting to a different thread"));
9323 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9324 _("Iterate through updating all remote thread info"));
9325 add_com ("talive", class_obscure, threadalive_test,
9326 _(" Remote thread alive test "));
9331 /* Convert a thread ID to a string. Returns the string in a static
9335 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9337 static char buf[64];
9338 struct remote_state *rs = get_remote_state ();
9340 if (ptid_equal (ptid, null_ptid))
9341 return normal_pid_to_str (ptid);
9342 else if (ptid_is_pid (ptid))
9344 /* Printing an inferior target id. */
9346 /* When multi-process extensions are off, there's no way in the
9347 remote protocol to know the remote process id, if there's any
9348 at all. There's one exception --- when we're connected with
9349 target extended-remote, and we manually attached to a process
9350 with "attach PID". We don't record anywhere a flag that
9351 allows us to distinguish that case from the case of
9352 connecting with extended-remote and the stub already being
9353 attached to a process, and reporting yes to qAttached, hence
9354 no smart special casing here. */
9355 if (!remote_multi_process_p (rs))
9357 xsnprintf (buf, sizeof buf, "Remote target");
9361 return normal_pid_to_str (ptid);
9365 if (ptid_equal (magic_null_ptid, ptid))
9366 xsnprintf (buf, sizeof buf, "Thread <main>");
9367 else if (rs->extended && remote_multi_process_p (rs))
9368 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9369 ptid_get_pid (ptid), ptid_get_tid (ptid));
9371 xsnprintf (buf, sizeof buf, "Thread %ld",
9372 ptid_get_tid (ptid));
9377 /* Get the address of the thread local variable in OBJFILE which is
9378 stored at OFFSET within the thread local storage for thread PTID. */
9381 remote_get_thread_local_address (struct target_ops *ops,
9382 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9384 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
9386 struct remote_state *rs = get_remote_state ();
9388 char *endp = rs->buf + get_remote_packet_size ();
9389 enum packet_result result;
9391 strcpy (p, "qGetTLSAddr:");
9393 p = write_ptid (p, endp, ptid);
9395 p += hexnumstr (p, offset);
9397 p += hexnumstr (p, lm);
9401 getpkt (&rs->buf, &rs->buf_size, 0);
9402 result = packet_ok (rs->buf,
9403 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9404 if (result == PACKET_OK)
9408 unpack_varlen_hex (rs->buf, &result);
9411 else if (result == PACKET_UNKNOWN)
9412 throw_error (TLS_GENERIC_ERROR,
9413 _("Remote target doesn't support qGetTLSAddr packet"));
9415 throw_error (TLS_GENERIC_ERROR,
9416 _("Remote target failed to process qGetTLSAddr request"));
9419 throw_error (TLS_GENERIC_ERROR,
9420 _("TLS not supported or disabled on this target"));
9425 /* Provide thread local base, i.e. Thread Information Block address.
9426 Returns 1 if ptid is found and thread_local_base is non zero. */
9429 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
9431 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
9433 struct remote_state *rs = get_remote_state ();
9435 char *endp = rs->buf + get_remote_packet_size ();
9436 enum packet_result result;
9438 strcpy (p, "qGetTIBAddr:");
9440 p = write_ptid (p, endp, ptid);
9444 getpkt (&rs->buf, &rs->buf_size, 0);
9445 result = packet_ok (rs->buf,
9446 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9447 if (result == PACKET_OK)
9451 unpack_varlen_hex (rs->buf, &result);
9453 *addr = (CORE_ADDR) result;
9456 else if (result == PACKET_UNKNOWN)
9457 error (_("Remote target doesn't support qGetTIBAddr packet"));
9459 error (_("Remote target failed to process qGetTIBAddr request"));
9462 error (_("qGetTIBAddr not supported or disabled on this target"));
9467 /* Support for inferring a target description based on the current
9468 architecture and the size of a 'g' packet. While the 'g' packet
9469 can have any size (since optional registers can be left off the
9470 end), some sizes are easily recognizable given knowledge of the
9471 approximate architecture. */
9473 struct remote_g_packet_guess
9476 const struct target_desc *tdesc;
9478 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9479 DEF_VEC_O(remote_g_packet_guess_s);
9481 struct remote_g_packet_data
9483 VEC(remote_g_packet_guess_s) *guesses;
9486 static struct gdbarch_data *remote_g_packet_data_handle;
9489 remote_g_packet_data_init (struct obstack *obstack)
9491 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9495 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9496 const struct target_desc *tdesc)
9498 struct remote_g_packet_data *data
9499 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9500 struct remote_g_packet_guess new_guess, *guess;
9503 gdb_assert (tdesc != NULL);
9506 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9508 if (guess->bytes == bytes)
9509 internal_error (__FILE__, __LINE__,
9510 _("Duplicate g packet description added for size %d"),
9513 new_guess.bytes = bytes;
9514 new_guess.tdesc = tdesc;
9515 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9518 /* Return 1 if remote_read_description would do anything on this target
9519 and architecture, 0 otherwise. */
9522 remote_read_description_p (struct target_ops *target)
9524 struct remote_g_packet_data *data
9525 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9527 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9533 static const struct target_desc *
9534 remote_read_description (struct target_ops *target)
9536 struct remote_g_packet_data *data
9537 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9539 /* Do not try this during initial connection, when we do not know
9540 whether there is a running but stopped thread. */
9541 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9544 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9546 struct remote_g_packet_guess *guess;
9548 int bytes = send_g_packet ();
9551 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9553 if (guess->bytes == bytes)
9554 return guess->tdesc;
9556 /* We discard the g packet. A minor optimization would be to
9557 hold on to it, and fill the register cache once we have selected
9558 an architecture, but it's too tricky to do safely. */
9564 /* Remote file transfer support. This is host-initiated I/O, not
9565 target-initiated; for target-initiated, see remote-fileio.c. */
9567 /* If *LEFT is at least the length of STRING, copy STRING to
9568 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9569 decrease *LEFT. Otherwise raise an error. */
9572 remote_buffer_add_string (char **buffer, int *left, char *string)
9574 int len = strlen (string);
9577 error (_("Packet too long for target."));
9579 memcpy (*buffer, string, len);
9583 /* NUL-terminate the buffer as a convenience, if there is
9589 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9590 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9591 decrease *LEFT. Otherwise raise an error. */
9594 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9597 if (2 * len > *left)
9598 error (_("Packet too long for target."));
9600 bin2hex (bytes, *buffer, len);
9604 /* NUL-terminate the buffer as a convenience, if there is
9610 /* If *LEFT is large enough, convert VALUE to hex and add it to
9611 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9612 decrease *LEFT. Otherwise raise an error. */
9615 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9617 int len = hexnumlen (value);
9620 error (_("Packet too long for target."));
9622 hexnumstr (*buffer, value);
9626 /* NUL-terminate the buffer as a convenience, if there is
9632 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9633 value, *REMOTE_ERRNO to the remote error number or zero if none
9634 was included, and *ATTACHMENT to point to the start of the annex
9635 if any. The length of the packet isn't needed here; there may
9636 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9638 Return 0 if the packet could be parsed, -1 if it could not. If
9639 -1 is returned, the other variables may not be initialized. */
9642 remote_hostio_parse_result (char *buffer, int *retcode,
9643 int *remote_errno, char **attachment)
9650 if (buffer[0] != 'F')
9654 *retcode = strtol (&buffer[1], &p, 16);
9655 if (errno != 0 || p == &buffer[1])
9658 /* Check for ",errno". */
9662 *remote_errno = strtol (p + 1, &p2, 16);
9663 if (errno != 0 || p + 1 == p2)
9668 /* Check for ";attachment". If there is no attachment, the
9669 packet should end here. */
9672 *attachment = p + 1;
9675 else if (*p == '\0')
9681 /* Send a prepared I/O packet to the target and read its response.
9682 The prepared packet is in the global RS->BUF before this function
9683 is called, and the answer is there when we return.
9685 COMMAND_BYTES is the length of the request to send, which may include
9686 binary data. WHICH_PACKET is the packet configuration to check
9687 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9688 is set to the error number and -1 is returned. Otherwise the value
9689 returned by the function is returned.
9691 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9692 attachment is expected; an error will be reported if there's a
9693 mismatch. If one is found, *ATTACHMENT will be set to point into
9694 the packet buffer and *ATTACHMENT_LEN will be set to the
9695 attachment's length. */
9698 remote_hostio_send_command (int command_bytes, int which_packet,
9699 int *remote_errno, char **attachment,
9700 int *attachment_len)
9702 struct remote_state *rs = get_remote_state ();
9703 int ret, bytes_read;
9704 char *attachment_tmp;
9707 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
9709 *remote_errno = FILEIO_ENOSYS;
9713 putpkt_binary (rs->buf, command_bytes);
9714 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9716 /* If it timed out, something is wrong. Don't try to parse the
9720 *remote_errno = FILEIO_EINVAL;
9724 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9727 *remote_errno = FILEIO_EINVAL;
9729 case PACKET_UNKNOWN:
9730 *remote_errno = FILEIO_ENOSYS;
9736 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9739 *remote_errno = FILEIO_EINVAL;
9743 /* Make sure we saw an attachment if and only if we expected one. */
9744 if ((attachment_tmp == NULL && attachment != NULL)
9745 || (attachment_tmp != NULL && attachment == NULL))
9747 *remote_errno = FILEIO_EINVAL;
9751 /* If an attachment was found, it must point into the packet buffer;
9752 work out how many bytes there were. */
9753 if (attachment_tmp != NULL)
9755 *attachment = attachment_tmp;
9756 *attachment_len = bytes_read - (*attachment - rs->buf);
9762 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9763 remote file descriptor, or -1 if an error occurs (and set
9767 remote_hostio_open (const char *filename, int flags, int mode,
9770 struct remote_state *rs = get_remote_state ();
9772 int left = get_remote_packet_size () - 1;
9774 remote_buffer_add_string (&p, &left, "vFile:open:");
9776 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9778 remote_buffer_add_string (&p, &left, ",");
9780 remote_buffer_add_int (&p, &left, flags);
9781 remote_buffer_add_string (&p, &left, ",");
9783 remote_buffer_add_int (&p, &left, mode);
9785 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9786 remote_errno, NULL, NULL);
9789 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9790 Return the number of bytes written, or -1 if an error occurs (and
9791 set *REMOTE_ERRNO). */
9794 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9795 ULONGEST offset, int *remote_errno)
9797 struct remote_state *rs = get_remote_state ();
9799 int left = get_remote_packet_size ();
9802 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9804 remote_buffer_add_int (&p, &left, fd);
9805 remote_buffer_add_string (&p, &left, ",");
9807 remote_buffer_add_int (&p, &left, offset);
9808 remote_buffer_add_string (&p, &left, ",");
9810 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9811 get_remote_packet_size () - (p - rs->buf));
9813 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9814 remote_errno, NULL, NULL);
9817 /* Read up to LEN bytes FD on the remote target into READ_BUF
9818 Return the number of bytes read, or -1 if an error occurs (and
9819 set *REMOTE_ERRNO). */
9822 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9823 ULONGEST offset, int *remote_errno)
9825 struct remote_state *rs = get_remote_state ();
9828 int left = get_remote_packet_size ();
9829 int ret, attachment_len;
9832 remote_buffer_add_string (&p, &left, "vFile:pread:");
9834 remote_buffer_add_int (&p, &left, fd);
9835 remote_buffer_add_string (&p, &left, ",");
9837 remote_buffer_add_int (&p, &left, len);
9838 remote_buffer_add_string (&p, &left, ",");
9840 remote_buffer_add_int (&p, &left, offset);
9842 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9843 remote_errno, &attachment,
9849 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9851 if (read_len != ret)
9852 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9857 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9858 (and set *REMOTE_ERRNO). */
9861 remote_hostio_close (int fd, int *remote_errno)
9863 struct remote_state *rs = get_remote_state ();
9865 int left = get_remote_packet_size () - 1;
9867 remote_buffer_add_string (&p, &left, "vFile:close:");
9869 remote_buffer_add_int (&p, &left, fd);
9871 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9872 remote_errno, NULL, NULL);
9875 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9876 occurs (and set *REMOTE_ERRNO). */
9879 remote_hostio_unlink (const char *filename, int *remote_errno)
9881 struct remote_state *rs = get_remote_state ();
9883 int left = get_remote_packet_size () - 1;
9885 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9887 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9890 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9891 remote_errno, NULL, NULL);
9894 /* Read value of symbolic link FILENAME on the remote target. Return
9895 a null-terminated string allocated via xmalloc, or NULL if an error
9896 occurs (and set *REMOTE_ERRNO). */
9899 remote_hostio_readlink (const char *filename, int *remote_errno)
9901 struct remote_state *rs = get_remote_state ();
9904 int left = get_remote_packet_size ();
9905 int len, attachment_len;
9909 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9911 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9914 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9915 remote_errno, &attachment,
9921 ret = xmalloc (len + 1);
9923 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9924 (gdb_byte *) ret, len);
9925 if (read_len != len)
9926 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9933 remote_fileio_errno_to_host (int errnum)
9957 case FILEIO_ENOTDIR:
9977 case FILEIO_ENAMETOOLONG:
9978 return ENAMETOOLONG;
9984 remote_hostio_error (int errnum)
9986 int host_error = remote_fileio_errno_to_host (errnum);
9988 if (host_error == -1)
9989 error (_("Unknown remote I/O error %d"), errnum);
9991 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9995 remote_hostio_close_cleanup (void *opaque)
9997 int fd = *(int *) opaque;
10000 remote_hostio_close (fd, &remote_errno);
10005 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10007 const char *filename = bfd_get_filename (abfd);
10008 int fd, remote_errno;
10011 gdb_assert (remote_filename_p (filename));
10013 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
10016 errno = remote_fileio_errno_to_host (remote_errno);
10017 bfd_set_error (bfd_error_system_call);
10021 stream = xmalloc (sizeof (int));
10027 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10029 int fd = *(int *)stream;
10034 /* Ignore errors on close; these may happen if the remote
10035 connection was already torn down. */
10036 remote_hostio_close (fd, &remote_errno);
10038 /* Zero means success. */
10043 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10044 file_ptr nbytes, file_ptr offset)
10046 int fd = *(int *)stream;
10048 file_ptr pos, bytes;
10051 while (nbytes > pos)
10053 bytes = remote_hostio_pread (fd, (gdb_byte *) buf + pos, nbytes - pos,
10054 offset + pos, &remote_errno);
10056 /* Success, but no bytes, means end-of-file. */
10060 errno = remote_fileio_errno_to_host (remote_errno);
10061 bfd_set_error (bfd_error_system_call);
10072 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10074 /* FIXME: We should probably implement remote_hostio_stat. */
10075 sb->st_size = INT_MAX;
10080 remote_filename_p (const char *filename)
10082 return strncmp (filename, "remote:", 7) == 0;
10086 remote_bfd_open (const char *remote_file, const char *target)
10088 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10089 remote_bfd_iovec_open, NULL,
10090 remote_bfd_iovec_pread,
10091 remote_bfd_iovec_close,
10092 remote_bfd_iovec_stat);
10098 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10100 struct cleanup *back_to, *close_cleanup;
10101 int retcode, fd, remote_errno, bytes, io_size;
10104 int bytes_in_buffer;
10109 error (_("command can only be used with remote target"));
10111 file = gdb_fopen_cloexec (local_file, "rb");
10113 perror_with_name (local_file);
10114 back_to = make_cleanup_fclose (file);
10116 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10118 0700, &remote_errno);
10120 remote_hostio_error (remote_errno);
10122 /* Send up to this many bytes at once. They won't all fit in the
10123 remote packet limit, so we'll transfer slightly fewer. */
10124 io_size = get_remote_packet_size ();
10125 buffer = xmalloc (io_size);
10126 make_cleanup (xfree, buffer);
10128 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10130 bytes_in_buffer = 0;
10133 while (bytes_in_buffer || !saw_eof)
10137 bytes = fread (buffer + bytes_in_buffer, 1,
10138 io_size - bytes_in_buffer,
10143 error (_("Error reading %s."), local_file);
10146 /* EOF. Unless there is something still in the
10147 buffer from the last iteration, we are done. */
10149 if (bytes_in_buffer == 0)
10157 bytes += bytes_in_buffer;
10158 bytes_in_buffer = 0;
10160 retcode = remote_hostio_pwrite (fd, buffer, bytes,
10161 offset, &remote_errno);
10164 remote_hostio_error (remote_errno);
10165 else if (retcode == 0)
10166 error (_("Remote write of %d bytes returned 0!"), bytes);
10167 else if (retcode < bytes)
10169 /* Short write. Save the rest of the read data for the next
10171 bytes_in_buffer = bytes - retcode;
10172 memmove (buffer, buffer + retcode, bytes_in_buffer);
10178 discard_cleanups (close_cleanup);
10179 if (remote_hostio_close (fd, &remote_errno))
10180 remote_hostio_error (remote_errno);
10183 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10184 do_cleanups (back_to);
10188 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10190 struct cleanup *back_to, *close_cleanup;
10191 int fd, remote_errno, bytes, io_size;
10197 error (_("command can only be used with remote target"));
10199 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10201 remote_hostio_error (remote_errno);
10203 file = gdb_fopen_cloexec (local_file, "wb");
10205 perror_with_name (local_file);
10206 back_to = make_cleanup_fclose (file);
10208 /* Send up to this many bytes at once. They won't all fit in the
10209 remote packet limit, so we'll transfer slightly fewer. */
10210 io_size = get_remote_packet_size ();
10211 buffer = xmalloc (io_size);
10212 make_cleanup (xfree, buffer);
10214 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10219 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
10221 /* Success, but no bytes, means end-of-file. */
10224 remote_hostio_error (remote_errno);
10228 bytes = fwrite (buffer, 1, bytes, file);
10230 perror_with_name (local_file);
10233 discard_cleanups (close_cleanup);
10234 if (remote_hostio_close (fd, &remote_errno))
10235 remote_hostio_error (remote_errno);
10238 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10239 do_cleanups (back_to);
10243 remote_file_delete (const char *remote_file, int from_tty)
10245 int retcode, remote_errno;
10248 error (_("command can only be used with remote target"));
10250 retcode = remote_hostio_unlink (remote_file, &remote_errno);
10252 remote_hostio_error (remote_errno);
10255 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10259 remote_put_command (char *args, int from_tty)
10261 struct cleanup *back_to;
10265 error_no_arg (_("file to put"));
10267 argv = gdb_buildargv (args);
10268 back_to = make_cleanup_freeargv (argv);
10269 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10270 error (_("Invalid parameters to remote put"));
10272 remote_file_put (argv[0], argv[1], from_tty);
10274 do_cleanups (back_to);
10278 remote_get_command (char *args, int from_tty)
10280 struct cleanup *back_to;
10284 error_no_arg (_("file to get"));
10286 argv = gdb_buildargv (args);
10287 back_to = make_cleanup_freeargv (argv);
10288 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10289 error (_("Invalid parameters to remote get"));
10291 remote_file_get (argv[0], argv[1], from_tty);
10293 do_cleanups (back_to);
10297 remote_delete_command (char *args, int from_tty)
10299 struct cleanup *back_to;
10303 error_no_arg (_("file to delete"));
10305 argv = gdb_buildargv (args);
10306 back_to = make_cleanup_freeargv (argv);
10307 if (argv[0] == NULL || argv[1] != NULL)
10308 error (_("Invalid parameters to remote delete"));
10310 remote_file_delete (argv[0], from_tty);
10312 do_cleanups (back_to);
10316 remote_command (char *args, int from_tty)
10318 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
10322 remote_can_execute_reverse (void)
10324 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
10325 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
10332 remote_supports_non_stop (void)
10338 remote_supports_disable_randomization (void)
10340 /* Only supported in extended mode. */
10345 remote_supports_multi_process (void)
10347 struct remote_state *rs = get_remote_state ();
10349 /* Only extended-remote handles being attached to multiple
10350 processes, even though plain remote can use the multi-process
10351 thread id extensions, so that GDB knows the target process's
10353 return rs->extended && remote_multi_process_p (rs);
10357 remote_supports_cond_tracepoints (void)
10359 struct remote_state *rs = get_remote_state ();
10361 return rs->cond_tracepoints;
10365 remote_supports_cond_breakpoints (void)
10367 struct remote_state *rs = get_remote_state ();
10369 return rs->cond_breakpoints;
10373 remote_supports_fast_tracepoints (void)
10375 struct remote_state *rs = get_remote_state ();
10377 return rs->fast_tracepoints;
10381 remote_supports_static_tracepoints (void)
10383 struct remote_state *rs = get_remote_state ();
10385 return rs->static_tracepoints;
10389 remote_supports_install_in_trace (void)
10391 struct remote_state *rs = get_remote_state ();
10393 return rs->install_in_trace;
10397 remote_supports_enable_disable_tracepoint (void)
10399 struct remote_state *rs = get_remote_state ();
10401 return rs->enable_disable_tracepoints;
10405 remote_supports_string_tracing (void)
10407 struct remote_state *rs = get_remote_state ();
10409 return rs->string_tracing;
10413 remote_can_run_breakpoint_commands (void)
10415 struct remote_state *rs = get_remote_state ();
10417 return rs->breakpoint_commands;
10421 remote_trace_init (void)
10424 remote_get_noisy_reply (&target_buf, &target_buf_size);
10425 if (strcmp (target_buf, "OK") != 0)
10426 error (_("Target does not support this command."));
10429 static void free_actions_list (char **actions_list);
10430 static void free_actions_list_cleanup_wrapper (void *);
10432 free_actions_list_cleanup_wrapper (void *al)
10434 free_actions_list (al);
10438 free_actions_list (char **actions_list)
10442 if (actions_list == 0)
10445 for (ndx = 0; actions_list[ndx]; ndx++)
10446 xfree (actions_list[ndx]);
10448 xfree (actions_list);
10451 /* Recursive routine to walk through command list including loops, and
10452 download packets for each command. */
10455 remote_download_command_source (int num, ULONGEST addr,
10456 struct command_line *cmds)
10458 struct remote_state *rs = get_remote_state ();
10459 struct command_line *cmd;
10461 for (cmd = cmds; cmd; cmd = cmd->next)
10463 QUIT; /* Allow user to bail out with ^C. */
10464 strcpy (rs->buf, "QTDPsrc:");
10465 encode_source_string (num, addr, "cmd", cmd->line,
10466 rs->buf + strlen (rs->buf),
10467 rs->buf_size - strlen (rs->buf));
10469 remote_get_noisy_reply (&target_buf, &target_buf_size);
10470 if (strcmp (target_buf, "OK"))
10471 warning (_("Target does not support source download."));
10473 if (cmd->control_type == while_control
10474 || cmd->control_type == while_stepping_control)
10476 remote_download_command_source (num, addr, *cmd->body_list);
10478 QUIT; /* Allow user to bail out with ^C. */
10479 strcpy (rs->buf, "QTDPsrc:");
10480 encode_source_string (num, addr, "cmd", "end",
10481 rs->buf + strlen (rs->buf),
10482 rs->buf_size - strlen (rs->buf));
10484 remote_get_noisy_reply (&target_buf, &target_buf_size);
10485 if (strcmp (target_buf, "OK"))
10486 warning (_("Target does not support source download."));
10492 remote_download_tracepoint (struct bp_location *loc)
10494 #define BUF_SIZE 2048
10498 char buf[BUF_SIZE];
10499 char **tdp_actions;
10500 char **stepping_actions;
10502 struct cleanup *old_chain = NULL;
10503 struct agent_expr *aexpr;
10504 struct cleanup *aexpr_chain = NULL;
10506 struct breakpoint *b = loc->owner;
10507 struct tracepoint *t = (struct tracepoint *) b;
10509 encode_actions (loc->owner, loc, &tdp_actions, &stepping_actions);
10510 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10512 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10515 tpaddr = loc->address;
10516 sprintf_vma (addrbuf, tpaddr);
10517 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10518 addrbuf, /* address */
10519 (b->enable_state == bp_enabled ? 'E' : 'D'),
10520 t->step_count, t->pass_count);
10521 /* Fast tracepoints are mostly handled by the target, but we can
10522 tell the target how big of an instruction block should be moved
10524 if (b->type == bp_fast_tracepoint)
10526 /* Only test for support at download time; we may not know
10527 target capabilities at definition time. */
10528 if (remote_supports_fast_tracepoints ())
10532 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10533 tpaddr, &isize, NULL))
10534 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10537 /* If it passed validation at definition but fails now,
10538 something is very wrong. */
10539 internal_error (__FILE__, __LINE__,
10540 _("Fast tracepoint not "
10541 "valid during download"));
10544 /* Fast tracepoints are functionally identical to regular
10545 tracepoints, so don't take lack of support as a reason to
10546 give up on the trace run. */
10547 warning (_("Target does not support fast tracepoints, "
10548 "downloading %d as regular tracepoint"), b->number);
10550 else if (b->type == bp_static_tracepoint)
10552 /* Only test for support at download time; we may not know
10553 target capabilities at definition time. */
10554 if (remote_supports_static_tracepoints ())
10556 struct static_tracepoint_marker marker;
10558 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10559 strcat (buf, ":S");
10561 error (_("Static tracepoint not valid during download"));
10564 /* Fast tracepoints are functionally identical to regular
10565 tracepoints, so don't take lack of support as a reason
10566 to give up on the trace run. */
10567 error (_("Target does not support static tracepoints"));
10569 /* If the tracepoint has a conditional, make it into an agent
10570 expression and append to the definition. */
10573 /* Only test support at download time, we may not know target
10574 capabilities at definition time. */
10575 if (remote_supports_cond_tracepoints ())
10577 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10578 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10579 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10581 pkt = buf + strlen (buf);
10582 for (ndx = 0; ndx < aexpr->len; ++ndx)
10583 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10585 do_cleanups (aexpr_chain);
10588 warning (_("Target does not support conditional tracepoints, "
10589 "ignoring tp %d cond"), b->number);
10592 if (b->commands || *default_collect)
10595 remote_get_noisy_reply (&target_buf, &target_buf_size);
10596 if (strcmp (target_buf, "OK"))
10597 error (_("Target does not support tracepoints."));
10599 /* do_single_steps (t); */
10602 for (ndx = 0; tdp_actions[ndx]; ndx++)
10604 QUIT; /* Allow user to bail out with ^C. */
10605 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10606 b->number, addrbuf, /* address */
10608 ((tdp_actions[ndx + 1] || stepping_actions)
10611 remote_get_noisy_reply (&target_buf,
10613 if (strcmp (target_buf, "OK"))
10614 error (_("Error on target while setting tracepoints."));
10617 if (stepping_actions)
10619 for (ndx = 0; stepping_actions[ndx]; ndx++)
10621 QUIT; /* Allow user to bail out with ^C. */
10622 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10623 b->number, addrbuf, /* address */
10624 ((ndx == 0) ? "S" : ""),
10625 stepping_actions[ndx],
10626 (stepping_actions[ndx + 1] ? "-" : ""));
10628 remote_get_noisy_reply (&target_buf,
10630 if (strcmp (target_buf, "OK"))
10631 error (_("Error on target while setting tracepoints."));
10635 if (remote_protocol_packets[PACKET_TracepointSource].support
10638 if (b->addr_string)
10640 strcpy (buf, "QTDPsrc:");
10641 encode_source_string (b->number, loc->address,
10642 "at", b->addr_string, buf + strlen (buf),
10643 2048 - strlen (buf));
10646 remote_get_noisy_reply (&target_buf, &target_buf_size);
10647 if (strcmp (target_buf, "OK"))
10648 warning (_("Target does not support source download."));
10650 if (b->cond_string)
10652 strcpy (buf, "QTDPsrc:");
10653 encode_source_string (b->number, loc->address,
10654 "cond", b->cond_string, buf + strlen (buf),
10655 2048 - strlen (buf));
10657 remote_get_noisy_reply (&target_buf, &target_buf_size);
10658 if (strcmp (target_buf, "OK"))
10659 warning (_("Target does not support source download."));
10661 remote_download_command_source (b->number, loc->address,
10662 breakpoint_commands (b));
10665 do_cleanups (old_chain);
10669 remote_can_download_tracepoint (void)
10671 struct remote_state *rs = get_remote_state ();
10672 struct trace_status *ts;
10675 /* Don't try to install tracepoints until we've relocated our
10676 symbols, and fetched and merged the target's tracepoint list with
10678 if (rs->starting_up)
10681 ts = current_trace_status ();
10682 status = remote_get_trace_status (ts);
10684 if (status == -1 || !ts->running_known || !ts->running)
10687 /* If we are in a tracing experiment, but remote stub doesn't support
10688 installing tracepoint in trace, we have to return. */
10689 if (!remote_supports_install_in_trace ())
10697 remote_download_trace_state_variable (struct trace_state_variable *tsv)
10699 struct remote_state *rs = get_remote_state ();
10702 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10703 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10705 p = rs->buf + strlen (rs->buf);
10706 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10707 error (_("Trace state variable name too long for tsv definition packet"));
10708 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10711 remote_get_noisy_reply (&target_buf, &target_buf_size);
10712 if (*target_buf == '\0')
10713 error (_("Target does not support this command."));
10714 if (strcmp (target_buf, "OK") != 0)
10715 error (_("Error on target while downloading trace state variable."));
10719 remote_enable_tracepoint (struct bp_location *location)
10721 struct remote_state *rs = get_remote_state ();
10724 sprintf_vma (addr_buf, location->address);
10725 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10726 location->owner->number, addr_buf);
10728 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10729 if (*rs->buf == '\0')
10730 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10731 if (strcmp (rs->buf, "OK") != 0)
10732 error (_("Error on target while enabling tracepoint."));
10736 remote_disable_tracepoint (struct bp_location *location)
10738 struct remote_state *rs = get_remote_state ();
10741 sprintf_vma (addr_buf, location->address);
10742 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10743 location->owner->number, addr_buf);
10745 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10746 if (*rs->buf == '\0')
10747 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10748 if (strcmp (rs->buf, "OK") != 0)
10749 error (_("Error on target while disabling tracepoint."));
10753 remote_trace_set_readonly_regions (void)
10757 bfd_size_type size;
10763 return; /* No information to give. */
10765 strcpy (target_buf, "QTro");
10766 offset = strlen (target_buf);
10767 for (s = exec_bfd->sections; s; s = s->next)
10769 char tmp1[40], tmp2[40];
10772 if ((s->flags & SEC_LOAD) == 0 ||
10773 /* (s->flags & SEC_CODE) == 0 || */
10774 (s->flags & SEC_READONLY) == 0)
10778 vma = bfd_get_section_vma (abfd, s);
10779 size = bfd_get_section_size (s);
10780 sprintf_vma (tmp1, vma);
10781 sprintf_vma (tmp2, vma + size);
10782 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10783 if (offset + sec_length + 1 > target_buf_size)
10785 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10788 Too many sections for read-only sections definition packet."));
10791 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10793 offset += sec_length;
10797 putpkt (target_buf);
10798 getpkt (&target_buf, &target_buf_size, 0);
10803 remote_trace_start (void)
10805 putpkt ("QTStart");
10806 remote_get_noisy_reply (&target_buf, &target_buf_size);
10807 if (*target_buf == '\0')
10808 error (_("Target does not support this command."));
10809 if (strcmp (target_buf, "OK") != 0)
10810 error (_("Bogus reply from target: %s"), target_buf);
10814 remote_get_trace_status (struct trace_status *ts)
10816 /* Initialize it just to avoid a GCC false warning. */
10818 /* FIXME we need to get register block size some other way. */
10819 extern int trace_regblock_size;
10820 volatile struct gdb_exception ex;
10821 enum packet_result result;
10823 if (remote_protocol_packets[PACKET_qTStatus].support == PACKET_DISABLE)
10826 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10828 putpkt ("qTStatus");
10830 TRY_CATCH (ex, RETURN_MASK_ERROR)
10832 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10836 if (ex.error != TARGET_CLOSE_ERROR)
10838 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10841 throw_exception (ex);
10844 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10846 /* If the remote target doesn't do tracing, flag it. */
10847 if (result == PACKET_UNKNOWN)
10850 /* We're working with a live target. */
10851 ts->filename = NULL;
10854 error (_("Bogus trace status reply from target: %s"), target_buf);
10856 /* Function 'parse_trace_status' sets default value of each field of
10857 'ts' at first, so we don't have to do it here. */
10858 parse_trace_status (p, ts);
10860 return ts->running;
10864 remote_get_tracepoint_status (struct breakpoint *bp,
10865 struct uploaded_tp *utp)
10867 struct remote_state *rs = get_remote_state ();
10869 struct bp_location *loc;
10870 struct tracepoint *tp = (struct tracepoint *) bp;
10871 size_t size = get_remote_packet_size ();
10875 tp->base.hit_count = 0;
10876 tp->traceframe_usage = 0;
10877 for (loc = tp->base.loc; loc; loc = loc->next)
10879 /* If the tracepoint was never downloaded, don't go asking for
10881 if (tp->number_on_target == 0)
10883 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10884 phex_nz (loc->address, 0));
10886 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10887 if (reply && *reply)
10890 parse_tracepoint_status (reply + 1, bp, utp);
10896 utp->hit_count = 0;
10897 utp->traceframe_usage = 0;
10898 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10899 phex_nz (utp->addr, 0));
10901 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10902 if (reply && *reply)
10905 parse_tracepoint_status (reply + 1, bp, utp);
10911 remote_trace_stop (void)
10914 remote_get_noisy_reply (&target_buf, &target_buf_size);
10915 if (*target_buf == '\0')
10916 error (_("Target does not support this command."));
10917 if (strcmp (target_buf, "OK") != 0)
10918 error (_("Bogus reply from target: %s"), target_buf);
10922 remote_trace_find (enum trace_find_type type, int num,
10923 CORE_ADDR addr1, CORE_ADDR addr2,
10926 struct remote_state *rs = get_remote_state ();
10927 char *endbuf = rs->buf + get_remote_packet_size ();
10929 int target_frameno = -1, target_tracept = -1;
10931 /* Lookups other than by absolute frame number depend on the current
10932 trace selected, so make sure it is correct on the remote end
10934 if (type != tfind_number)
10935 set_remote_traceframe ();
10938 strcpy (p, "QTFrame:");
10939 p = strchr (p, '\0');
10943 xsnprintf (p, endbuf - p, "%x", num);
10946 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
10949 xsnprintf (p, endbuf - p, "tdp:%x", num);
10952 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10953 phex_nz (addr2, 0));
10955 case tfind_outside:
10956 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10957 phex_nz (addr2, 0));
10960 error (_("Unknown trace find type %d"), type);
10964 reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
10965 if (*reply == '\0')
10966 error (_("Target does not support this command."));
10968 while (reply && *reply)
10973 target_frameno = (int) strtol (p, &reply, 16);
10975 error (_("Unable to parse trace frame number"));
10976 /* Don't update our remote traceframe number cache on failure
10977 to select a remote traceframe. */
10978 if (target_frameno == -1)
10983 target_tracept = (int) strtol (p, &reply, 16);
10985 error (_("Unable to parse tracepoint number"));
10987 case 'O': /* "OK"? */
10988 if (reply[1] == 'K' && reply[2] == '\0')
10991 error (_("Bogus reply from target: %s"), reply);
10994 error (_("Bogus reply from target: %s"), reply);
10997 *tpp = target_tracept;
10999 remote_traceframe_number = target_frameno;
11000 return target_frameno;
11004 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
11006 struct remote_state *rs = get_remote_state ();
11010 set_remote_traceframe ();
11012 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11014 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11015 if (reply && *reply)
11019 unpack_varlen_hex (reply + 1, &uval);
11020 *val = (LONGEST) uval;
11028 remote_save_trace_data (const char *filename)
11030 struct remote_state *rs = get_remote_state ();
11034 strcpy (p, "QTSave:");
11036 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11037 error (_("Remote file name too long for trace save packet"));
11038 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
11041 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11042 if (*reply == '\0')
11043 error (_("Target does not support this command."));
11044 if (strcmp (reply, "OK") != 0)
11045 error (_("Bogus reply from target: %s"), reply);
11049 /* This is basically a memory transfer, but needs to be its own packet
11050 because we don't know how the target actually organizes its trace
11051 memory, plus we want to be able to ask for as much as possible, but
11052 not be unhappy if we don't get as much as we ask for. */
11055 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
11057 struct remote_state *rs = get_remote_state ();
11063 strcpy (p, "qTBuffer:");
11065 p += hexnumstr (p, offset);
11067 p += hexnumstr (p, len);
11071 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11072 if (reply && *reply)
11074 /* 'l' by itself means we're at the end of the buffer and
11075 there is nothing more to get. */
11079 /* Convert the reply into binary. Limit the number of bytes to
11080 convert according to our passed-in buffer size, rather than
11081 what was returned in the packet; if the target is
11082 unexpectedly generous and gives us a bigger reply than we
11083 asked for, we don't want to crash. */
11084 rslt = hex2bin (target_buf, buf, len);
11088 /* Something went wrong, flag as an error. */
11093 remote_set_disconnected_tracing (int val)
11095 struct remote_state *rs = get_remote_state ();
11097 if (rs->disconnected_tracing)
11101 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11103 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11104 if (*reply == '\0')
11105 error (_("Target does not support this command."));
11106 if (strcmp (reply, "OK") != 0)
11107 error (_("Bogus reply from target: %s"), reply);
11110 warning (_("Target does not support disconnected tracing."));
11114 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11116 struct thread_info *info = find_thread_ptid (ptid);
11118 if (info && info->private)
11119 return info->private->core;
11124 remote_set_circular_trace_buffer (int val)
11126 struct remote_state *rs = get_remote_state ();
11129 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11131 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11132 if (*reply == '\0')
11133 error (_("Target does not support this command."));
11134 if (strcmp (reply, "OK") != 0)
11135 error (_("Bogus reply from target: %s"), reply);
11138 static struct traceframe_info *
11139 remote_traceframe_info (void)
11143 text = target_read_stralloc (¤t_target,
11144 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11147 struct traceframe_info *info;
11148 struct cleanup *back_to = make_cleanup (xfree, text);
11150 info = parse_traceframe_info (text);
11151 do_cleanups (back_to);
11158 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11159 instruction on which a fast tracepoint may be placed. Returns -1
11160 if the packet is not supported, and 0 if the minimum instruction
11161 length is unknown. */
11164 remote_get_min_fast_tracepoint_insn_len (void)
11166 struct remote_state *rs = get_remote_state ();
11169 /* If we're not debugging a process yet, the IPA can't be
11171 if (!target_has_execution)
11174 /* Make sure the remote is pointing at the right process. */
11175 set_general_process ();
11177 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11179 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11180 if (*reply == '\0')
11184 ULONGEST min_insn_len;
11186 unpack_varlen_hex (reply, &min_insn_len);
11188 return (int) min_insn_len;
11193 remote_set_trace_buffer_size (LONGEST val)
11195 if (remote_protocol_packets[PACKET_QTBuffer_size].support
11198 struct remote_state *rs = get_remote_state ();
11199 char *buf = rs->buf;
11200 char *endbuf = rs->buf + get_remote_packet_size ();
11201 enum packet_result result;
11203 gdb_assert (val >= 0 || val == -1);
11204 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11205 /* Send -1 as literal "-1" to avoid host size dependency. */
11209 buf += hexnumstr (buf, (ULONGEST) -val);
11212 buf += hexnumstr (buf, (ULONGEST) val);
11215 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11216 result = packet_ok (rs->buf,
11217 &remote_protocol_packets[PACKET_QTBuffer_size]);
11219 if (result != PACKET_OK)
11220 warning (_("Bogus reply from target: %s"), rs->buf);
11225 remote_set_trace_notes (const char *user, const char *notes,
11226 const char *stop_notes)
11228 struct remote_state *rs = get_remote_state ();
11230 char *buf = rs->buf;
11231 char *endbuf = rs->buf + get_remote_packet_size ();
11234 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11237 buf += xsnprintf (buf, endbuf - buf, "user:");
11238 nbytes = bin2hex ((gdb_byte *) user, buf, 0);
11244 buf += xsnprintf (buf, endbuf - buf, "notes:");
11245 nbytes = bin2hex ((gdb_byte *) notes, buf, 0);
11251 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11252 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, 0);
11256 /* Ensure the buffer is terminated. */
11260 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11261 if (*reply == '\0')
11264 if (strcmp (reply, "OK") != 0)
11265 error (_("Bogus reply from target: %s"), reply);
11271 remote_use_agent (int use)
11273 if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
11275 struct remote_state *rs = get_remote_state ();
11277 /* If the stub supports QAgent. */
11278 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11280 getpkt (&rs->buf, &rs->buf_size, 0);
11282 if (strcmp (rs->buf, "OK") == 0)
11293 remote_can_use_agent (void)
11295 return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
11298 struct btrace_target_info
11300 /* The ptid of the traced thread. */
11304 /* Check whether the target supports branch tracing. */
11307 remote_supports_btrace (void)
11309 if (remote_protocol_packets[PACKET_Qbtrace_off].support != PACKET_ENABLE)
11311 if (remote_protocol_packets[PACKET_Qbtrace_bts].support != PACKET_ENABLE)
11313 if (remote_protocol_packets[PACKET_qXfer_btrace].support != PACKET_ENABLE)
11319 /* Enable branch tracing. */
11321 static struct btrace_target_info *
11322 remote_enable_btrace (ptid_t ptid)
11324 struct btrace_target_info *tinfo = NULL;
11325 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11326 struct remote_state *rs = get_remote_state ();
11327 char *buf = rs->buf;
11328 char *endbuf = rs->buf + get_remote_packet_size ();
11330 if (packet->support != PACKET_ENABLE)
11331 error (_("Target does not support branch tracing."));
11333 set_general_thread (ptid);
11335 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11337 getpkt (&rs->buf, &rs->buf_size, 0);
11339 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11341 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11342 error (_("Could not enable branch tracing for %s: %s"),
11343 target_pid_to_str (ptid), rs->buf + 2);
11345 error (_("Could not enable branch tracing for %s."),
11346 target_pid_to_str (ptid));
11349 tinfo = xzalloc (sizeof (*tinfo));
11350 tinfo->ptid = ptid;
11355 /* Disable branch tracing. */
11358 remote_disable_btrace (struct btrace_target_info *tinfo)
11360 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11361 struct remote_state *rs = get_remote_state ();
11362 char *buf = rs->buf;
11363 char *endbuf = rs->buf + get_remote_packet_size ();
11365 if (packet->support != PACKET_ENABLE)
11366 error (_("Target does not support branch tracing."));
11368 set_general_thread (tinfo->ptid);
11370 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11372 getpkt (&rs->buf, &rs->buf_size, 0);
11374 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11376 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11377 error (_("Could not disable branch tracing for %s: %s"),
11378 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11380 error (_("Could not disable branch tracing for %s."),
11381 target_pid_to_str (tinfo->ptid));
11387 /* Teardown branch tracing. */
11390 remote_teardown_btrace (struct btrace_target_info *tinfo)
11392 /* We must not talk to the target during teardown. */
11396 /* Read the branch trace. */
11398 static VEC (btrace_block_s) *
11399 remote_read_btrace (struct btrace_target_info *tinfo,
11400 enum btrace_read_type type)
11402 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11403 struct remote_state *rs = get_remote_state ();
11404 VEC (btrace_block_s) *btrace = NULL;
11408 if (packet->support != PACKET_ENABLE)
11409 error (_("Target does not support branch tracing."));
11411 #if !defined(HAVE_LIBEXPAT)
11412 error (_("Cannot process branch tracing result. XML parsing not supported."));
11417 case btrace_read_all:
11420 case btrace_read_new:
11424 internal_error (__FILE__, __LINE__,
11425 _("Bad branch tracing read type: %u."),
11426 (unsigned int) type);
11429 xml = target_read_stralloc (¤t_target,
11430 TARGET_OBJECT_BTRACE, annex);
11433 struct cleanup *cleanup = make_cleanup (xfree, xml);
11435 btrace = parse_xml_btrace (xml);
11436 do_cleanups (cleanup);
11443 init_remote_ops (void)
11445 remote_ops.to_shortname = "remote";
11446 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11447 remote_ops.to_doc =
11448 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11449 Specify the serial device it is connected to\n\
11450 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11451 remote_ops.to_open = remote_open;
11452 remote_ops.to_close = remote_close;
11453 remote_ops.to_detach = remote_detach;
11454 remote_ops.to_disconnect = remote_disconnect;
11455 remote_ops.to_resume = remote_resume;
11456 remote_ops.to_wait = remote_wait;
11457 remote_ops.to_fetch_registers = remote_fetch_registers;
11458 remote_ops.to_store_registers = remote_store_registers;
11459 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11460 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
11461 remote_ops.to_files_info = remote_files_info;
11462 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11463 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11464 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11465 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11466 remote_ops.to_watchpoint_addr_within_range =
11467 remote_watchpoint_addr_within_range;
11468 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11469 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11470 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11471 remote_ops.to_region_ok_for_hw_watchpoint
11472 = remote_region_ok_for_hw_watchpoint;
11473 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11474 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11475 remote_ops.to_kill = remote_kill;
11476 remote_ops.to_load = generic_load;
11477 remote_ops.to_mourn_inferior = remote_mourn;
11478 remote_ops.to_pass_signals = remote_pass_signals;
11479 remote_ops.to_program_signals = remote_program_signals;
11480 remote_ops.to_thread_alive = remote_thread_alive;
11481 remote_ops.to_find_new_threads = remote_threads_info;
11482 remote_ops.to_pid_to_str = remote_pid_to_str;
11483 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11484 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11485 remote_ops.to_stop = remote_stop;
11486 remote_ops.to_xfer_partial = remote_xfer_partial;
11487 remote_ops.to_rcmd = remote_rcmd;
11488 remote_ops.to_log_command = serial_log_command;
11489 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11490 remote_ops.to_stratum = process_stratum;
11491 remote_ops.to_has_all_memory = default_child_has_all_memory;
11492 remote_ops.to_has_memory = default_child_has_memory;
11493 remote_ops.to_has_stack = default_child_has_stack;
11494 remote_ops.to_has_registers = default_child_has_registers;
11495 remote_ops.to_has_execution = default_child_has_execution;
11496 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11497 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11498 remote_ops.to_magic = OPS_MAGIC;
11499 remote_ops.to_memory_map = remote_memory_map;
11500 remote_ops.to_flash_erase = remote_flash_erase;
11501 remote_ops.to_flash_done = remote_flash_done;
11502 remote_ops.to_read_description = remote_read_description;
11503 remote_ops.to_search_memory = remote_search_memory;
11504 remote_ops.to_can_async_p = remote_can_async_p;
11505 remote_ops.to_is_async_p = remote_is_async_p;
11506 remote_ops.to_async = remote_async;
11507 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11508 remote_ops.to_terminal_ours = remote_terminal_ours;
11509 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11510 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11511 remote_ops.to_supports_disable_randomization
11512 = remote_supports_disable_randomization;
11513 remote_ops.to_fileio_open = remote_hostio_open;
11514 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11515 remote_ops.to_fileio_pread = remote_hostio_pread;
11516 remote_ops.to_fileio_close = remote_hostio_close;
11517 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11518 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11519 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11520 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11521 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11522 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11523 remote_ops.to_trace_init = remote_trace_init;
11524 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11525 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11526 remote_ops.to_download_trace_state_variable
11527 = remote_download_trace_state_variable;
11528 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11529 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11530 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11531 remote_ops.to_trace_start = remote_trace_start;
11532 remote_ops.to_get_trace_status = remote_get_trace_status;
11533 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11534 remote_ops.to_trace_stop = remote_trace_stop;
11535 remote_ops.to_trace_find = remote_trace_find;
11536 remote_ops.to_get_trace_state_variable_value
11537 = remote_get_trace_state_variable_value;
11538 remote_ops.to_save_trace_data = remote_save_trace_data;
11539 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11540 remote_ops.to_upload_trace_state_variables
11541 = remote_upload_trace_state_variables;
11542 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11543 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11544 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11545 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11546 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11547 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11548 remote_ops.to_core_of_thread = remote_core_of_thread;
11549 remote_ops.to_verify_memory = remote_verify_memory;
11550 remote_ops.to_get_tib_address = remote_get_tib_address;
11551 remote_ops.to_set_permissions = remote_set_permissions;
11552 remote_ops.to_static_tracepoint_marker_at
11553 = remote_static_tracepoint_marker_at;
11554 remote_ops.to_static_tracepoint_markers_by_strid
11555 = remote_static_tracepoint_markers_by_strid;
11556 remote_ops.to_traceframe_info = remote_traceframe_info;
11557 remote_ops.to_use_agent = remote_use_agent;
11558 remote_ops.to_can_use_agent = remote_can_use_agent;
11559 remote_ops.to_supports_btrace = remote_supports_btrace;
11560 remote_ops.to_enable_btrace = remote_enable_btrace;
11561 remote_ops.to_disable_btrace = remote_disable_btrace;
11562 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11563 remote_ops.to_read_btrace = remote_read_btrace;
11566 /* Set up the extended remote vector by making a copy of the standard
11567 remote vector and adding to it. */
11570 init_extended_remote_ops (void)
11572 extended_remote_ops = remote_ops;
11574 extended_remote_ops.to_shortname = "extended-remote";
11575 extended_remote_ops.to_longname =
11576 "Extended remote serial target in gdb-specific protocol";
11577 extended_remote_ops.to_doc =
11578 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11579 Specify the serial device it is connected to (e.g. /dev/ttya).";
11580 extended_remote_ops.to_open = extended_remote_open;
11581 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11582 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11583 extended_remote_ops.to_detach = extended_remote_detach;
11584 extended_remote_ops.to_attach = extended_remote_attach;
11585 extended_remote_ops.to_kill = extended_remote_kill;
11586 extended_remote_ops.to_supports_disable_randomization
11587 = extended_remote_supports_disable_randomization;
11591 remote_can_async_p (void)
11593 if (!target_async_permitted)
11594 /* We only enable async when the user specifically asks for it. */
11597 /* We're async whenever the serial device is. */
11598 return serial_can_async_p (remote_desc);
11602 remote_is_async_p (void)
11604 if (!target_async_permitted)
11605 /* We only enable async when the user specifically asks for it. */
11608 /* We're async whenever the serial device is. */
11609 return serial_is_async_p (remote_desc);
11612 /* Pass the SERIAL event on and up to the client. One day this code
11613 will be able to delay notifying the client of an event until the
11614 point where an entire packet has been received. */
11616 static void (*async_client_callback) (enum inferior_event_type event_type,
11618 static void *async_client_context;
11619 static serial_event_ftype remote_async_serial_handler;
11622 remote_async_serial_handler (struct serial *scb, void *context)
11624 /* Don't propogate error information up to the client. Instead let
11625 the client find out about the error by querying the target. */
11626 async_client_callback (INF_REG_EVENT, async_client_context);
11630 remote_async_inferior_event_handler (gdb_client_data data)
11632 inferior_event_handler (INF_REG_EVENT, NULL);
11636 remote_async (void (*callback) (enum inferior_event_type event_type,
11637 void *context), void *context)
11639 if (callback != NULL)
11641 serial_async (remote_desc, remote_async_serial_handler, NULL);
11642 async_client_callback = callback;
11643 async_client_context = context;
11646 serial_async (remote_desc, NULL, NULL);
11650 set_remote_cmd (char *args, int from_tty)
11652 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
11656 show_remote_cmd (char *args, int from_tty)
11658 /* We can't just use cmd_show_list here, because we want to skip
11659 the redundant "show remote Z-packet" and the legacy aliases. */
11660 struct cleanup *showlist_chain;
11661 struct cmd_list_element *list = remote_show_cmdlist;
11662 struct ui_out *uiout = current_uiout;
11664 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11665 for (; list != NULL; list = list->next)
11666 if (strcmp (list->name, "Z-packet") == 0)
11668 else if (list->type == not_set_cmd)
11669 /* Alias commands are exactly like the original, except they
11670 don't have the normal type. */
11674 struct cleanup *option_chain
11675 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11677 ui_out_field_string (uiout, "name", list->name);
11678 ui_out_text (uiout, ": ");
11679 if (list->type == show_cmd)
11680 do_show_command ((char *) NULL, from_tty, list);
11682 cmd_func (list, NULL, from_tty);
11683 /* Close the tuple. */
11684 do_cleanups (option_chain);
11687 /* Close the tuple. */
11688 do_cleanups (showlist_chain);
11692 /* Function to be called whenever a new objfile (shlib) is detected. */
11694 remote_new_objfile (struct objfile *objfile)
11696 if (remote_desc != 0) /* Have a remote connection. */
11697 remote_check_symbols ();
11700 /* Pull all the tracepoints defined on the target and create local
11701 data structures representing them. We don't want to create real
11702 tracepoints yet, we don't want to mess up the user's existing
11706 remote_upload_tracepoints (struct uploaded_tp **utpp)
11708 struct remote_state *rs = get_remote_state ();
11711 /* Ask for a first packet of tracepoint definition. */
11713 getpkt (&rs->buf, &rs->buf_size, 0);
11715 while (*p && *p != 'l')
11717 parse_tracepoint_definition (p, utpp);
11718 /* Ask for another packet of tracepoint definition. */
11720 getpkt (&rs->buf, &rs->buf_size, 0);
11727 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
11729 struct remote_state *rs = get_remote_state ();
11732 /* Ask for a first packet of variable definition. */
11734 getpkt (&rs->buf, &rs->buf_size, 0);
11736 while (*p && *p != 'l')
11738 parse_tsv_definition (p, utsvp);
11739 /* Ask for another packet of variable definition. */
11741 getpkt (&rs->buf, &rs->buf_size, 0);
11747 /* The "set/show range-stepping" show hook. */
11750 show_range_stepping (struct ui_file *file, int from_tty,
11751 struct cmd_list_element *c,
11754 fprintf_filtered (file,
11755 _("Debugger's willingness to use range stepping "
11756 "is %s.\n"), value);
11759 /* The "set/show range-stepping" set hook. */
11762 set_range_stepping (char *ignore_args, int from_tty,
11763 struct cmd_list_element *c)
11765 /* Whene enabling, check whether range stepping is actually
11766 supported by the target, and warn if not. */
11767 if (use_range_stepping)
11769 if (remote_desc != NULL)
11771 struct remote_state *rs = get_remote_state ();
11773 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
11774 remote_vcont_probe (rs);
11776 if (remote_protocol_packets[PACKET_vCont].support == PACKET_ENABLE
11777 && rs->supports_vCont.r)
11781 warning (_("Range stepping is not supported by the current target"));
11786 _initialize_remote (void)
11788 struct remote_state *rs;
11789 struct cmd_list_element *cmd;
11790 const char *cmd_name;
11792 /* architecture specific data */
11793 remote_gdbarch_data_handle =
11794 gdbarch_data_register_post_init (init_remote_state);
11795 remote_g_packet_data_handle =
11796 gdbarch_data_register_pre_init (remote_g_packet_data_init);
11798 /* Initialize the per-target state. At the moment there is only one
11799 of these, not one per target. Only one target is active at a
11800 time. The default buffer size is unimportant; it will be expanded
11801 whenever a larger buffer is needed. */
11802 rs = get_remote_state_raw ();
11803 rs->buf_size = 400;
11804 rs->buf = xmalloc (rs->buf_size);
11806 init_remote_ops ();
11807 add_target (&remote_ops);
11809 init_extended_remote_ops ();
11810 add_target (&extended_remote_ops);
11812 /* Hook into new objfile notification. */
11813 observer_attach_new_objfile (remote_new_objfile);
11814 /* We're no longer interested in notification events of an inferior
11816 observer_attach_inferior_exit (discard_pending_stop_replies);
11818 /* Set up signal handlers. */
11819 sigint_remote_token =
11820 create_async_signal_handler (async_remote_interrupt, NULL);
11821 sigint_remote_twice_token =
11822 create_async_signal_handler (async_remote_interrupt_twice, NULL);
11825 init_remote_threadtests ();
11828 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
11829 /* set/show remote ... */
11831 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
11832 Remote protocol specific variables\n\
11833 Configure various remote-protocol specific variables such as\n\
11834 the packets being used"),
11835 &remote_set_cmdlist, "set remote ",
11836 0 /* allow-unknown */, &setlist);
11837 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
11838 Remote protocol specific variables\n\
11839 Configure various remote-protocol specific variables such as\n\
11840 the packets being used"),
11841 &remote_show_cmdlist, "show remote ",
11842 0 /* allow-unknown */, &showlist);
11844 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11845 Compare section data on target to the exec file.\n\
11846 Argument is a single section name (default: all loaded sections)."),
11849 add_cmd ("packet", class_maintenance, packet_command, _("\
11850 Send an arbitrary packet to a remote target.\n\
11851 maintenance packet TEXT\n\
11852 If GDB is talking to an inferior via the GDB serial protocol, then\n\
11853 this command sends the string TEXT to the inferior, and displays the\n\
11854 response packet. GDB supplies the initial `$' character, and the\n\
11855 terminating `#' character and checksum."),
11858 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11859 Set whether to send break if interrupted."), _("\
11860 Show whether to send break if interrupted."), _("\
11861 If set, a break, instead of a cntrl-c, is sent to the remote target."),
11862 set_remotebreak, show_remotebreak,
11863 &setlist, &showlist);
11864 cmd_name = "remotebreak";
11865 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11866 deprecate_cmd (cmd, "set remote interrupt-sequence");
11867 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11868 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11869 deprecate_cmd (cmd, "show remote interrupt-sequence");
11871 add_setshow_enum_cmd ("interrupt-sequence", class_support,
11872 interrupt_sequence_modes, &interrupt_sequence_mode,
11874 Set interrupt sequence to remote target."), _("\
11875 Show interrupt sequence to remote target."), _("\
11876 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11877 NULL, show_interrupt_sequence,
11878 &remote_set_cmdlist,
11879 &remote_show_cmdlist);
11881 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11882 &interrupt_on_connect, _("\
11883 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11884 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11885 If set, interrupt sequence is sent to remote target."),
11887 &remote_set_cmdlist, &remote_show_cmdlist);
11889 /* Install commands for configuring memory read/write packets. */
11891 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11892 Set the maximum number of bytes per memory write packet (deprecated)."),
11894 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11895 Show the maximum number of bytes per memory write packet (deprecated)."),
11897 add_cmd ("memory-write-packet-size", no_class,
11898 set_memory_write_packet_size, _("\
11899 Set the maximum number of bytes per memory-write packet.\n\
11900 Specify the number of bytes in a packet or 0 (zero) for the\n\
11901 default packet size. The actual limit is further reduced\n\
11902 dependent on the target. Specify ``fixed'' to disable the\n\
11903 further restriction and ``limit'' to enable that restriction."),
11904 &remote_set_cmdlist);
11905 add_cmd ("memory-read-packet-size", no_class,
11906 set_memory_read_packet_size, _("\
11907 Set the maximum number of bytes per memory-read packet.\n\
11908 Specify the number of bytes in a packet or 0 (zero) for the\n\
11909 default packet size. The actual limit is further reduced\n\
11910 dependent on the target. Specify ``fixed'' to disable the\n\
11911 further restriction and ``limit'' to enable that restriction."),
11912 &remote_set_cmdlist);
11913 add_cmd ("memory-write-packet-size", no_class,
11914 show_memory_write_packet_size,
11915 _("Show the maximum number of bytes per memory-write packet."),
11916 &remote_show_cmdlist);
11917 add_cmd ("memory-read-packet-size", no_class,
11918 show_memory_read_packet_size,
11919 _("Show the maximum number of bytes per memory-read packet."),
11920 &remote_show_cmdlist);
11922 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
11923 &remote_hw_watchpoint_limit, _("\
11924 Set the maximum number of target hardware watchpoints."), _("\
11925 Show the maximum number of target hardware watchpoints."), _("\
11926 Specify a negative limit for unlimited."),
11927 NULL, NULL, /* FIXME: i18n: The maximum
11928 number of target hardware
11929 watchpoints is %s. */
11930 &remote_set_cmdlist, &remote_show_cmdlist);
11931 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11932 &remote_hw_watchpoint_length_limit, _("\
11933 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11934 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11935 Specify a negative limit for unlimited."),
11936 NULL, NULL, /* FIXME: i18n: The maximum
11937 length (in bytes) of a target
11938 hardware watchpoint is %s. */
11939 &remote_set_cmdlist, &remote_show_cmdlist);
11940 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
11941 &remote_hw_breakpoint_limit, _("\
11942 Set the maximum number of target hardware breakpoints."), _("\
11943 Show the maximum number of target hardware breakpoints."), _("\
11944 Specify a negative limit for unlimited."),
11945 NULL, NULL, /* FIXME: i18n: The maximum
11946 number of target hardware
11947 breakpoints is %s. */
11948 &remote_set_cmdlist, &remote_show_cmdlist);
11950 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
11951 &remote_address_size, _("\
11952 Set the maximum size of the address (in bits) in a memory packet."), _("\
11953 Show the maximum size of the address (in bits) in a memory packet."), NULL,
11955 NULL, /* FIXME: i18n: */
11956 &setlist, &showlist);
11958 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
11959 "X", "binary-download", 1);
11961 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
11962 "vCont", "verbose-resume", 0);
11964 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11965 "QPassSignals", "pass-signals", 0);
11967 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
11968 "QProgramSignals", "program-signals", 0);
11970 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
11971 "qSymbol", "symbol-lookup", 0);
11973 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
11974 "P", "set-register", 1);
11976 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
11977 "p", "fetch-register", 1);
11979 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
11980 "Z0", "software-breakpoint", 0);
11982 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
11983 "Z1", "hardware-breakpoint", 0);
11985 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
11986 "Z2", "write-watchpoint", 0);
11988 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
11989 "Z3", "read-watchpoint", 0);
11991 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
11992 "Z4", "access-watchpoint", 0);
11994 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
11995 "qXfer:auxv:read", "read-aux-vector", 0);
11997 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
11998 "qXfer:features:read", "target-features", 0);
12000 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12001 "qXfer:libraries:read", "library-info", 0);
12003 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12004 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12006 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12007 "qXfer:memory-map:read", "memory-map", 0);
12009 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12010 "qXfer:spu:read", "read-spu-object", 0);
12012 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12013 "qXfer:spu:write", "write-spu-object", 0);
12015 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12016 "qXfer:osdata:read", "osdata", 0);
12018 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12019 "qXfer:threads:read", "threads", 0);
12021 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12022 "qXfer:siginfo:read", "read-siginfo-object", 0);
12024 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12025 "qXfer:siginfo:write", "write-siginfo-object", 0);
12027 add_packet_config_cmd
12028 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12029 "qXfer:traceframe-info:read", "traceframe-info", 0);
12031 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12032 "qXfer:uib:read", "unwind-info-block", 0);
12034 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12035 "qGetTLSAddr", "get-thread-local-storage-address",
12038 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12039 "qGetTIBAddr", "get-thread-information-block-address",
12042 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12043 "bc", "reverse-continue", 0);
12045 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12046 "bs", "reverse-step", 0);
12048 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12049 "qSupported", "supported-packets", 0);
12051 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12052 "qSearch:memory", "search-memory", 0);
12054 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12055 "qTStatus", "trace-status", 0);
12057 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12058 "vFile:open", "hostio-open", 0);
12060 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12061 "vFile:pread", "hostio-pread", 0);
12063 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12064 "vFile:pwrite", "hostio-pwrite", 0);
12066 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12067 "vFile:close", "hostio-close", 0);
12069 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12070 "vFile:unlink", "hostio-unlink", 0);
12072 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12073 "vFile:readlink", "hostio-readlink", 0);
12075 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12076 "vAttach", "attach", 0);
12078 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12081 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12082 "QStartNoAckMode", "noack", 0);
12084 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12085 "vKill", "kill", 0);
12087 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12088 "qAttached", "query-attached", 0);
12090 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12091 "ConditionalTracepoints",
12092 "conditional-tracepoints", 0);
12094 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12095 "ConditionalBreakpoints",
12096 "conditional-breakpoints", 0);
12098 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12099 "BreakpointCommands",
12100 "breakpoint-commands", 0);
12102 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12103 "FastTracepoints", "fast-tracepoints", 0);
12105 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12106 "TracepointSource", "TracepointSource", 0);
12108 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12109 "QAllow", "allow", 0);
12111 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12112 "StaticTracepoints", "static-tracepoints", 0);
12114 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12115 "InstallInTrace", "install-in-trace", 0);
12117 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12118 "qXfer:statictrace:read", "read-sdata-object", 0);
12120 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12121 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12123 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12124 "QDisableRandomization", "disable-randomization", 0);
12126 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12127 "QAgent", "agent", 0);
12129 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12130 "QTBuffer:size", "trace-buffer-size", 0);
12132 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12133 "Qbtrace:off", "disable-btrace", 0);
12135 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12136 "Qbtrace:bts", "enable-btrace", 0);
12138 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12139 "qXfer:btrace", "read-btrace", 0);
12141 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12142 Z sub-packet has its own set and show commands, but users may
12143 have sets to this variable in their .gdbinit files (or in their
12145 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12146 &remote_Z_packet_detect, _("\
12147 Set use of remote protocol `Z' packets"), _("\
12148 Show use of remote protocol `Z' packets "), _("\
12149 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12151 set_remote_protocol_Z_packet_cmd,
12152 show_remote_protocol_Z_packet_cmd,
12153 /* FIXME: i18n: Use of remote protocol
12154 `Z' packets is %s. */
12155 &remote_set_cmdlist, &remote_show_cmdlist);
12157 add_prefix_cmd ("remote", class_files, remote_command, _("\
12158 Manipulate files on the remote system\n\
12159 Transfer files to and from the remote target system."),
12160 &remote_cmdlist, "remote ",
12161 0 /* allow-unknown */, &cmdlist);
12163 add_cmd ("put", class_files, remote_put_command,
12164 _("Copy a local file to the remote system."),
12167 add_cmd ("get", class_files, remote_get_command,
12168 _("Copy a remote file to the local system."),
12171 add_cmd ("delete", class_files, remote_delete_command,
12172 _("Delete a remote file."),
12175 remote_exec_file = xstrdup ("");
12176 add_setshow_string_noescape_cmd ("exec-file", class_files,
12177 &remote_exec_file, _("\
12178 Set the remote pathname for \"run\""), _("\
12179 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12180 &remote_set_cmdlist, &remote_show_cmdlist);
12182 add_setshow_boolean_cmd ("range-stepping", class_run,
12183 &use_range_stepping, _("\
12184 Enable or disable range stepping."), _("\
12185 Show whether target-assisted range stepping is enabled."), _("\
12186 If on, and the target supports it, when stepping a source line, GDB\n\
12187 tells the target to step the corresponding range of addresses itself instead\n\
12188 of issuing multiple single-steps. This speeds up source level\n\
12189 stepping. If off, GDB always issues single-steps, even if range\n\
12190 stepping is supported by the target. The default is on."),
12191 set_range_stepping,
12192 show_range_stepping,
12196 /* Eventually initialize fileio. See fileio.c */
12197 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12199 /* Take advantage of the fact that the LWP field is not used, to tag
12200 special ptids with it set to != 0. */
12201 magic_null_ptid = ptid_build (42000, 1, -1);
12202 not_sent_ptid = ptid_build (42000, 1, -2);
12203 any_thread_ptid = ptid_build (42000, 1, 0);
12205 target_buf_size = 2048;
12206 target_buf = xmalloc (target_buf_size);