1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2014 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. */
30 /*#include "terminal.h" */
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
36 #include "remote-notif.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
45 #include "filestuff.h"
50 #include "event-loop.h"
51 #include "event-top.h"
57 #include "gdbcore.h" /* for exec_bfd */
59 #include "remote-fileio.h"
60 #include "gdb/fileio.h"
62 #include "xml-support.h"
64 #include "memory-map.h"
66 #include "tracepoint.h"
72 /* Temp hacks for tracepoint encoding migration. */
73 static char *target_buf;
74 static long target_buf_size;
76 /* The size to align memory write packets, when practical. The protocol
77 does not guarantee any alignment, and gdb will generate short
78 writes and unaligned writes, but even as a best-effort attempt this
79 can improve bulk transfers. For instance, if a write is misaligned
80 relative to the target's data bus, the stub may need to make an extra
81 round trip fetching data from the target. This doesn't make a
82 huge difference, but it's easy to do, so we try to be helpful.
84 The alignment chosen is arbitrary; usually data bus width is
85 important here, not the possibly larger cache line size. */
86 enum { REMOTE_ALIGN_WRITES = 16 };
88 /* Prototypes for local functions. */
89 static void async_cleanup_sigint_signal_handler (void *dummy);
90 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
91 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
92 int forever, int *is_notif);
94 static void async_handle_remote_sigint (int);
95 static void async_handle_remote_sigint_twice (int);
97 static void remote_files_info (struct target_ops *ignore);
99 static void remote_prepare_to_store (struct target_ops *self,
100 struct regcache *regcache);
102 static void remote_open_1 (const char *, int, struct target_ops *,
105 static void remote_close (struct target_ops *self);
107 static void remote_mourn (struct target_ops *ops);
109 static void extended_remote_restart (void);
111 static void extended_remote_mourn (struct target_ops *);
113 static void remote_mourn_1 (struct target_ops *);
115 static void remote_send (char **buf, long *sizeof_buf_p);
117 static int readchar (int timeout);
119 static void remote_serial_write (const char *str, int len);
121 static void remote_kill (struct target_ops *ops);
123 static int remote_can_async_p (struct target_ops *);
125 static int remote_is_async_p (struct target_ops *);
127 static void remote_async (struct target_ops *ops,
128 void (*callback) (enum inferior_event_type event_type,
132 static void sync_remote_interrupt_twice (int signo);
134 static void interrupt_query (void);
136 static void set_general_thread (struct ptid ptid);
137 static void set_continue_thread (struct ptid ptid);
139 static void get_offsets (void);
141 static void skip_frame (void);
143 static long read_frame (char **buf_p, long *sizeof_buf);
145 static int hexnumlen (ULONGEST num);
147 static void init_remote_ops (void);
149 static void init_extended_remote_ops (void);
151 static void remote_stop (struct target_ops *self, ptid_t);
153 static int stubhex (int ch);
155 static int hexnumstr (char *, ULONGEST);
157 static int hexnumnstr (char *, ULONGEST, int);
159 static CORE_ADDR remote_address_masked (CORE_ADDR);
161 static void print_packet (const char *);
163 static void compare_sections_command (char *, int);
165 static void packet_command (char *, int);
167 static int stub_unpack_int (char *buff, int fieldlength);
169 static ptid_t remote_current_thread (ptid_t oldptid);
171 static int putpkt_binary (const char *buf, int cnt);
173 static void check_binary_download (CORE_ADDR addr);
175 struct packet_config;
177 static void show_packet_config_cmd (struct packet_config *config);
179 static void show_remote_protocol_packet_cmd (struct ui_file *file,
181 struct cmd_list_element *c,
184 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
185 static ptid_t read_ptid (char *buf, char **obuf);
187 static void remote_set_permissions (struct target_ops *self);
190 static int remote_get_trace_status (struct target_ops *self,
191 struct trace_status *ts);
193 static int remote_upload_tracepoints (struct target_ops *self,
194 struct uploaded_tp **utpp);
196 static int remote_upload_trace_state_variables (struct target_ops *self,
197 struct uploaded_tsv **utsvp);
199 static void remote_query_supported (void);
201 static void remote_check_symbols (void);
203 void _initialize_remote (void);
206 static void stop_reply_xfree (struct stop_reply *);
207 static void remote_parse_stop_reply (char *, struct stop_reply *);
208 static void push_stop_reply (struct stop_reply *);
209 static void discard_pending_stop_replies_in_queue (struct remote_state *);
210 static int peek_stop_reply (ptid_t ptid);
212 static void remote_async_inferior_event_handler (gdb_client_data);
214 static void remote_terminal_ours (struct target_ops *self);
216 static int remote_read_description_p (struct target_ops *target);
218 static void remote_console_output (char *msg);
220 static int remote_supports_cond_breakpoints (struct target_ops *self);
222 static int remote_can_run_breakpoint_commands (struct target_ops *self);
226 static struct cmd_list_element *remote_cmdlist;
228 /* For "set remote" and "show remote". */
230 static struct cmd_list_element *remote_set_cmdlist;
231 static struct cmd_list_element *remote_show_cmdlist;
233 /* Stub vCont actions support.
235 Each field is a boolean flag indicating whether the stub reports
236 support for the corresponding action. */
238 struct vCont_action_support
247 /* Controls whether GDB is willing to use range stepping. */
249 static int use_range_stepping = 1;
251 #define OPAQUETHREADBYTES 8
253 /* a 64 bit opaque identifier */
254 typedef unsigned char threadref[OPAQUETHREADBYTES];
256 /* About this many threadisds fit in a packet. */
258 #define MAXTHREADLISTRESULTS 32
260 /* Description of the remote protocol state for the currently
261 connected target. This is per-target state, and independent of the
262 selected architecture. */
266 /* A buffer to use for incoming packets, and its current size. The
267 buffer is grown dynamically for larger incoming packets.
268 Outgoing packets may also be constructed in this buffer.
269 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
270 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
275 /* True if we're going through initial connection setup (finding out
276 about the remote side's threads, relocating symbols, etc.). */
279 /* If we negotiated packet size explicitly (and thus can bypass
280 heuristics for the largest packet size that will not overflow
281 a buffer in the stub), this will be set to that packet size.
282 Otherwise zero, meaning to use the guessed size. */
283 long explicit_packet_size;
285 /* remote_wait is normally called when the target is running and
286 waits for a stop reply packet. But sometimes we need to call it
287 when the target is already stopped. We can send a "?" packet
288 and have remote_wait read the response. Or, if we already have
289 the response, we can stash it in BUF and tell remote_wait to
290 skip calling getpkt. This flag is set when BUF contains a
291 stop reply packet and the target is not waiting. */
292 int cached_wait_status;
294 /* True, if in no ack mode. That is, neither GDB nor the stub will
295 expect acks from each other. The connection is assumed to be
299 /* True if we're connected in extended remote mode. */
302 /* True if we resumed the target and we're waiting for the target to
303 stop. In the mean time, we can't start another command/query.
304 The remote server wouldn't be ready to process it, so we'd
305 timeout waiting for a reply that would never come and eventually
306 we'd close the connection. This can happen in asynchronous mode
307 because we allow GDB commands while the target is running. */
308 int waiting_for_stop_reply;
310 /* The status of the stub support for the various vCont actions. */
311 struct vCont_action_support supports_vCont;
313 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
314 responded to that. */
317 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
318 remote_open knows that we don't have a file open when the program
320 struct serial *remote_desc;
322 /* These are the threads which we last sent to the remote system. The
323 TID member will be -1 for all or -2 for not sent yet. */
324 ptid_t general_thread;
325 ptid_t continue_thread;
327 /* This is the traceframe which we last selected on the remote system.
328 It will be -1 if no traceframe is selected. */
329 int remote_traceframe_number;
331 char *last_pass_packet;
333 /* The last QProgramSignals packet sent to the target. We bypass
334 sending a new program signals list down to the target if the new
335 packet is exactly the same as the last we sent. IOW, we only let
336 the target know about program signals list changes. */
337 char *last_program_signals_packet;
339 enum gdb_signal last_sent_signal;
343 char *finished_object;
344 char *finished_annex;
345 ULONGEST finished_offset;
347 /* Should we try the 'ThreadInfo' query packet?
349 This variable (NOT available to the user: auto-detect only!)
350 determines whether GDB will use the new, simpler "ThreadInfo"
351 query or the older, more complex syntax for thread queries.
352 This is an auto-detect variable (set to true at each connect,
353 and set to false when the target fails to recognize it). */
354 int use_threadinfo_query;
355 int use_threadextra_query;
357 void (*async_client_callback) (enum inferior_event_type event_type,
359 void *async_client_context;
361 /* This is set to the data address of the access causing the target
362 to stop for a watchpoint. */
363 CORE_ADDR remote_watch_data_address;
365 /* This is non-zero if target stopped for a watchpoint. */
366 int remote_stopped_by_watchpoint_p;
368 threadref echo_nextthread;
369 threadref nextthread;
370 threadref resultthreadlist[MAXTHREADLISTRESULTS];
372 /* The state of remote notification. */
373 struct remote_notif_state *notif_state;
376 /* Private data that we'll store in (struct thread_info)->private. */
377 struct private_thread_info
384 free_private_thread_info (struct private_thread_info *info)
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)
402 /* Allocate a new struct remote_state with xmalloc, initialize it, and
405 static struct remote_state *
406 new_remote_state (void)
408 struct remote_state *result = XCNEW (struct remote_state);
410 /* The default buffer size is unimportant; it will be expanded
411 whenever a larger buffer is needed. */
412 result->buf_size = 400;
413 result->buf = xmalloc (result->buf_size);
414 result->remote_traceframe_number = -1;
415 result->last_sent_signal = GDB_SIGNAL_0;
420 /* Description of the remote protocol for a given architecture. */
424 long offset; /* Offset into G packet. */
425 long regnum; /* GDB's internal register number. */
426 LONGEST pnum; /* Remote protocol register number. */
427 int in_g_packet; /* Always part of G packet. */
428 /* long size in bytes; == register_size (target_gdbarch (), regnum);
430 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
434 struct remote_arch_state
436 /* Description of the remote protocol registers. */
437 long sizeof_g_packet;
439 /* Description of the remote protocol registers indexed by REGNUM
440 (making an array gdbarch_num_regs in size). */
441 struct packet_reg *regs;
443 /* This is the size (in chars) of the first response to the ``g''
444 packet. It is used as a heuristic when determining the maximum
445 size of memory-read and memory-write packets. A target will
446 typically only reserve a buffer large enough to hold the ``g''
447 packet. The size does not include packet overhead (headers and
449 long actual_register_packet_size;
451 /* This is the maximum size (in chars) of a non read/write packet.
452 It is also used as a cap on the size of read/write packets. */
453 long remote_packet_size;
456 /* Utility: generate error from an incoming stub packet. */
458 trace_error (char *buf)
461 return; /* not an error msg */
464 case '1': /* malformed packet error */
465 if (*++buf == '0') /* general case: */
466 error (_("remote.c: error in outgoing packet."));
468 error (_("remote.c: error in outgoing packet at field #%ld."),
469 strtol (buf, NULL, 16));
471 error (_("Target returns error code '%s'."), buf);
475 /* Utility: wait for reply from stub, while accepting "O" packets. */
477 remote_get_noisy_reply (char **buf_p,
480 do /* Loop on reply from remote stub. */
484 QUIT; /* Allow user to bail out with ^C. */
485 getpkt (buf_p, sizeof_buf, 0);
489 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
492 CORE_ADDR from, to, org_to;
494 int adjusted_size = 0;
495 volatile struct gdb_exception ex;
497 p = buf + strlen ("qRelocInsn:");
498 pp = unpack_varlen_hex (p, &ul);
500 error (_("invalid qRelocInsn packet: %s"), buf);
504 unpack_varlen_hex (p, &ul);
509 TRY_CATCH (ex, RETURN_MASK_ALL)
511 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
515 adjusted_size = to - org_to;
517 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
520 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
522 /* Propagate memory errors silently back to the target.
523 The stub may have limited the range of addresses we
524 can write to, for example. */
529 /* Something unexpectedly bad happened. Be verbose so
530 we can tell what, and propagate the error back to the
531 stub, so it doesn't get stuck waiting for a
533 exception_fprintf (gdb_stderr, ex,
534 _("warning: relocating instruction: "));
538 else if (buf[0] == 'O' && buf[1] != 'K')
539 remote_console_output (buf + 1); /* 'O' message from stub */
541 return buf; /* Here's the actual reply. */
546 /* Handle for retreving the remote protocol data from gdbarch. */
547 static struct gdbarch_data *remote_gdbarch_data_handle;
549 static struct remote_arch_state *
550 get_remote_arch_state (void)
552 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
555 /* Fetch the global remote target state. */
557 static struct remote_state *
558 get_remote_state (void)
560 /* Make sure that the remote architecture state has been
561 initialized, because doing so might reallocate rs->buf. Any
562 function which calls getpkt also needs to be mindful of changes
563 to rs->buf, but this call limits the number of places which run
565 get_remote_arch_state ();
567 return get_remote_state_raw ();
571 compare_pnums (const void *lhs_, const void *rhs_)
573 const struct packet_reg * const *lhs = lhs_;
574 const struct packet_reg * const *rhs = rhs_;
576 if ((*lhs)->pnum < (*rhs)->pnum)
578 else if ((*lhs)->pnum == (*rhs)->pnum)
585 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
587 int regnum, num_remote_regs, offset;
588 struct packet_reg **remote_regs;
590 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
592 struct packet_reg *r = ®s[regnum];
594 if (register_size (gdbarch, regnum) == 0)
595 /* Do not try to fetch zero-sized (placeholder) registers. */
598 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
603 /* Define the g/G packet format as the contents of each register
604 with a remote protocol number, in order of ascending protocol
607 remote_regs = alloca (gdbarch_num_regs (gdbarch)
608 * sizeof (struct packet_reg *));
609 for (num_remote_regs = 0, regnum = 0;
610 regnum < gdbarch_num_regs (gdbarch);
612 if (regs[regnum].pnum != -1)
613 remote_regs[num_remote_regs++] = ®s[regnum];
615 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
618 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
620 remote_regs[regnum]->in_g_packet = 1;
621 remote_regs[regnum]->offset = offset;
622 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
628 /* Given the architecture described by GDBARCH, return the remote
629 protocol register's number and the register's offset in the g/G
630 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
631 If the target does not have a mapping for REGNUM, return false,
632 otherwise, return true. */
635 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
636 int *pnum, int *poffset)
639 struct packet_reg *regs;
640 struct cleanup *old_chain;
642 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
644 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
645 old_chain = make_cleanup (xfree, regs);
647 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
649 *pnum = regs[regnum].pnum;
650 *poffset = regs[regnum].offset;
652 do_cleanups (old_chain);
658 init_remote_state (struct gdbarch *gdbarch)
660 struct remote_state *rs = get_remote_state_raw ();
661 struct remote_arch_state *rsa;
663 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
665 /* Use the architecture to build a regnum<->pnum table, which will be
666 1:1 unless a feature set specifies otherwise. */
667 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
668 gdbarch_num_regs (gdbarch),
671 /* Record the maximum possible size of the g packet - it may turn out
673 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
675 /* Default maximum number of characters in a packet body. Many
676 remote stubs have a hardwired buffer size of 400 bytes
677 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
678 as the maximum packet-size to ensure that the packet and an extra
679 NUL character can always fit in the buffer. This stops GDB
680 trashing stubs that try to squeeze an extra NUL into what is
681 already a full buffer (As of 1999-12-04 that was most stubs). */
682 rsa->remote_packet_size = 400 - 1;
684 /* This one is filled in when a ``g'' packet is received. */
685 rsa->actual_register_packet_size = 0;
687 /* Should rsa->sizeof_g_packet needs more space than the
688 default, adjust the size accordingly. Remember that each byte is
689 encoded as two characters. 32 is the overhead for the packet
690 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
691 (``$NN:G...#NN'') is a better guess, the below has been padded a
693 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
694 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
696 /* Make sure that the packet buffer is plenty big enough for
697 this architecture. */
698 if (rs->buf_size < rsa->remote_packet_size)
700 rs->buf_size = 2 * rsa->remote_packet_size;
701 rs->buf = xrealloc (rs->buf, rs->buf_size);
707 /* Return the current allowed size of a remote packet. This is
708 inferred from the current architecture, and should be used to
709 limit the length of outgoing packets. */
711 get_remote_packet_size (void)
713 struct remote_state *rs = get_remote_state ();
714 struct remote_arch_state *rsa = get_remote_arch_state ();
716 if (rs->explicit_packet_size)
717 return rs->explicit_packet_size;
719 return rsa->remote_packet_size;
722 static struct packet_reg *
723 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
725 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
729 struct packet_reg *r = &rsa->regs[regnum];
731 gdb_assert (r->regnum == regnum);
736 static struct packet_reg *
737 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
741 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
743 struct packet_reg *r = &rsa->regs[i];
751 static struct target_ops remote_ops;
753 static struct target_ops extended_remote_ops;
755 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
756 ``forever'' still use the normal timeout mechanism. This is
757 currently used by the ASYNC code to guarentee that target reads
758 during the initial connect always time-out. Once getpkt has been
759 modified to return a timeout indication and, in turn
760 remote_wait()/wait_for_inferior() have gained a timeout parameter
762 static int wait_forever_enabled_p = 1;
764 /* Allow the user to specify what sequence to send to the remote
765 when he requests a program interruption: Although ^C is usually
766 what remote systems expect (this is the default, here), it is
767 sometimes preferable to send a break. On other systems such
768 as the Linux kernel, a break followed by g, which is Magic SysRq g
769 is required in order to interrupt the execution. */
770 const char interrupt_sequence_control_c[] = "Ctrl-C";
771 const char interrupt_sequence_break[] = "BREAK";
772 const char interrupt_sequence_break_g[] = "BREAK-g";
773 static const char *const interrupt_sequence_modes[] =
775 interrupt_sequence_control_c,
776 interrupt_sequence_break,
777 interrupt_sequence_break_g,
780 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
783 show_interrupt_sequence (struct ui_file *file, int from_tty,
784 struct cmd_list_element *c,
787 if (interrupt_sequence_mode == interrupt_sequence_control_c)
788 fprintf_filtered (file,
789 _("Send the ASCII ETX character (Ctrl-c) "
790 "to the remote target to interrupt the "
791 "execution of the program.\n"));
792 else if (interrupt_sequence_mode == interrupt_sequence_break)
793 fprintf_filtered (file,
794 _("send a break signal to the remote target "
795 "to interrupt the execution of the program.\n"));
796 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
797 fprintf_filtered (file,
798 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
799 "the remote target to interrupt the execution "
800 "of Linux kernel.\n"));
802 internal_error (__FILE__, __LINE__,
803 _("Invalid value for interrupt_sequence_mode: %s."),
804 interrupt_sequence_mode);
807 /* This boolean variable specifies whether interrupt_sequence is sent
808 to the remote target when gdb connects to it.
809 This is mostly needed when you debug the Linux kernel: The Linux kernel
810 expects BREAK g which is Magic SysRq g for connecting gdb. */
811 static int interrupt_on_connect = 0;
813 /* This variable is used to implement the "set/show remotebreak" commands.
814 Since these commands are now deprecated in favor of "set/show remote
815 interrupt-sequence", it no longer has any effect on the code. */
816 static int remote_break;
819 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
822 interrupt_sequence_mode = interrupt_sequence_break;
824 interrupt_sequence_mode = interrupt_sequence_control_c;
828 show_remotebreak (struct ui_file *file, int from_tty,
829 struct cmd_list_element *c,
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
1060 /* If auto, GDB auto-detects support for this packet or feature,
1061 either through qSupported, or by trying the packet and looking
1062 at the response. If true, GDB assumes the target supports this
1063 packet. If false, the packet is disabled. Configs that don't
1064 have an associated command always have this set to auto. */
1065 enum auto_boolean detect;
1067 /* Does the target support this packet? */
1068 enum packet_support support;
1071 /* Analyze a packet's return value and update the packet config
1081 static enum packet_support packet_config_support (struct packet_config *config);
1082 static enum packet_support packet_support (int packet);
1085 show_packet_config_cmd (struct packet_config *config)
1087 char *support = "internal-error";
1089 switch (packet_config_support (config))
1092 support = "enabled";
1094 case PACKET_DISABLE:
1095 support = "disabled";
1097 case PACKET_SUPPORT_UNKNOWN:
1098 support = "unknown";
1101 switch (config->detect)
1103 case AUTO_BOOLEAN_AUTO:
1104 printf_filtered (_("Support for the `%s' packet "
1105 "is auto-detected, currently %s.\n"),
1106 config->name, support);
1108 case AUTO_BOOLEAN_TRUE:
1109 case AUTO_BOOLEAN_FALSE:
1110 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1111 config->name, support);
1117 add_packet_config_cmd (struct packet_config *config, const char *name,
1118 const char *title, int legacy)
1124 config->name = name;
1125 config->title = title;
1126 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1128 show_doc = xstrprintf ("Show current use of remote "
1129 "protocol `%s' (%s) packet",
1131 /* set/show TITLE-packet {auto,on,off} */
1132 cmd_name = xstrprintf ("%s-packet", title);
1133 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1134 &config->detect, set_doc,
1135 show_doc, NULL, /* help_doc */
1137 show_remote_protocol_packet_cmd,
1138 &remote_set_cmdlist, &remote_show_cmdlist);
1139 /* The command code copies the documentation strings. */
1142 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1147 legacy_name = xstrprintf ("%s-packet", name);
1148 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1149 &remote_set_cmdlist);
1150 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1151 &remote_show_cmdlist);
1155 static enum packet_result
1156 packet_check_result (const char *buf)
1160 /* The stub recognized the packet request. Check that the
1161 operation succeeded. */
1163 && isxdigit (buf[1]) && isxdigit (buf[2])
1165 /* "Enn" - definitly an error. */
1166 return PACKET_ERROR;
1168 /* Always treat "E." as an error. This will be used for
1169 more verbose error messages, such as E.memtypes. */
1170 if (buf[0] == 'E' && buf[1] == '.')
1171 return PACKET_ERROR;
1173 /* The packet may or may not be OK. Just assume it is. */
1177 /* The stub does not support the packet. */
1178 return PACKET_UNKNOWN;
1181 static enum packet_result
1182 packet_ok (const char *buf, struct packet_config *config)
1184 enum packet_result result;
1186 if (config->detect != AUTO_BOOLEAN_TRUE
1187 && config->support == PACKET_DISABLE)
1188 internal_error (__FILE__, __LINE__,
1189 _("packet_ok: attempt to use a disabled packet"));
1191 result = packet_check_result (buf);
1196 /* The stub recognized the packet request. */
1197 if (config->support == PACKET_SUPPORT_UNKNOWN)
1200 fprintf_unfiltered (gdb_stdlog,
1201 "Packet %s (%s) is supported\n",
1202 config->name, config->title);
1203 config->support = PACKET_ENABLE;
1206 case PACKET_UNKNOWN:
1207 /* The stub does not support the packet. */
1208 if (config->detect == AUTO_BOOLEAN_AUTO
1209 && config->support == PACKET_ENABLE)
1211 /* If the stub previously indicated that the packet was
1212 supported then there is a protocol error. */
1213 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1214 config->name, config->title);
1216 else if (config->detect == AUTO_BOOLEAN_TRUE)
1218 /* The user set it wrong. */
1219 error (_("Enabled packet %s (%s) not recognized by stub"),
1220 config->name, config->title);
1224 fprintf_unfiltered (gdb_stdlog,
1225 "Packet %s (%s) is NOT supported\n",
1226 config->name, config->title);
1227 config->support = PACKET_DISABLE;
1247 PACKET_vFile_pwrite,
1249 PACKET_vFile_unlink,
1250 PACKET_vFile_readlink,
1252 PACKET_qXfer_features,
1253 PACKET_qXfer_libraries,
1254 PACKET_qXfer_libraries_svr4,
1255 PACKET_qXfer_memory_map,
1256 PACKET_qXfer_spu_read,
1257 PACKET_qXfer_spu_write,
1258 PACKET_qXfer_osdata,
1259 PACKET_qXfer_threads,
1260 PACKET_qXfer_statictrace_read,
1261 PACKET_qXfer_traceframe_info,
1267 PACKET_QPassSignals,
1268 PACKET_QProgramSignals,
1270 PACKET_qSearch_memory,
1273 PACKET_QStartNoAckMode,
1275 PACKET_qXfer_siginfo_read,
1276 PACKET_qXfer_siginfo_write,
1279 /* Support for conditional tracepoints. */
1280 PACKET_ConditionalTracepoints,
1282 /* Support for target-side breakpoint conditions. */
1283 PACKET_ConditionalBreakpoints,
1285 /* Support for target-side breakpoint commands. */
1286 PACKET_BreakpointCommands,
1288 /* Support for fast tracepoints. */
1289 PACKET_FastTracepoints,
1291 /* Support for static tracepoints. */
1292 PACKET_StaticTracepoints,
1294 /* Support for installing tracepoints while a trace experiment is
1296 PACKET_InstallInTrace,
1300 PACKET_TracepointSource,
1303 PACKET_QDisableRandomization,
1305 PACKET_QTBuffer_size,
1308 PACKET_qXfer_btrace,
1310 /* Support for the QNonStop packet. */
1313 /* Support for multi-process extensions. */
1314 PACKET_multiprocess_feature,
1316 /* Support for enabling and disabling tracepoints while a trace
1317 experiment is running. */
1318 PACKET_EnableDisableTracepoints_feature,
1320 /* Support for collecting strings using the tracenz bytecode. */
1321 PACKET_tracenz_feature,
1323 /* Support for continuing to run a trace experiment while GDB is
1325 PACKET_DisconnectedTracing_feature,
1327 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1328 PACKET_augmented_libraries_svr4_read_feature,
1333 static struct packet_config remote_protocol_packets[PACKET_MAX];
1335 /* Returns whether a given packet or feature is supported. This takes
1336 into account the state of the corresponding "set remote foo-packet"
1337 command, which may be used to bypass auto-detection. */
1339 static enum packet_support
1340 packet_config_support (struct packet_config *config)
1342 switch (config->detect)
1344 case AUTO_BOOLEAN_TRUE:
1345 return PACKET_ENABLE;
1346 case AUTO_BOOLEAN_FALSE:
1347 return PACKET_DISABLE;
1348 case AUTO_BOOLEAN_AUTO:
1349 return config->support;
1351 gdb_assert_not_reached (_("bad switch"));
1355 /* Same as packet_config_support, but takes the packet's enum value as
1358 static enum packet_support
1359 packet_support (int packet)
1361 struct packet_config *config = &remote_protocol_packets[packet];
1363 return packet_config_support (config);
1367 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1368 struct cmd_list_element *c,
1371 struct packet_config *packet;
1373 for (packet = remote_protocol_packets;
1374 packet < &remote_protocol_packets[PACKET_MAX];
1377 if (&packet->detect == c->var)
1379 show_packet_config_cmd (packet);
1383 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1387 /* Should we try one of the 'Z' requests? */
1391 Z_PACKET_SOFTWARE_BP,
1392 Z_PACKET_HARDWARE_BP,
1399 /* For compatibility with older distributions. Provide a ``set remote
1400 Z-packet ...'' command that updates all the Z packet types. */
1402 static enum auto_boolean remote_Z_packet_detect;
1405 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1406 struct cmd_list_element *c)
1410 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1411 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1415 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1416 struct cmd_list_element *c,
1421 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1423 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1427 /* Returns true if the multi-process extensions are in effect. */
1430 remote_multi_process_p (struct remote_state *rs)
1432 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1435 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1436 static struct async_signal_handler *async_sigint_remote_twice_token;
1437 static struct async_signal_handler *async_sigint_remote_token;
1440 /* Asynchronous signal handle registered as event loop source for
1441 when we have pending events ready to be passed to the core. */
1443 static struct async_event_handler *remote_async_inferior_event_token;
1447 static ptid_t magic_null_ptid;
1448 static ptid_t not_sent_ptid;
1449 static ptid_t any_thread_ptid;
1451 /* Find out if the stub attached to PID (and hence GDB should offer to
1452 detach instead of killing it when bailing out). */
1455 remote_query_attached (int pid)
1457 struct remote_state *rs = get_remote_state ();
1458 size_t size = get_remote_packet_size ();
1460 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1463 if (remote_multi_process_p (rs))
1464 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1466 xsnprintf (rs->buf, size, "qAttached");
1469 getpkt (&rs->buf, &rs->buf_size, 0);
1471 switch (packet_ok (rs->buf,
1472 &remote_protocol_packets[PACKET_qAttached]))
1475 if (strcmp (rs->buf, "1") == 0)
1479 warning (_("Remote failure reply: %s"), rs->buf);
1481 case PACKET_UNKNOWN:
1488 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1489 has been invented by GDB, instead of reported by the target. Since
1490 we can be connected to a remote system before before knowing about
1491 any inferior, mark the target with execution when we find the first
1492 inferior. If ATTACHED is 1, then we had just attached to this
1493 inferior. If it is 0, then we just created this inferior. If it
1494 is -1, then try querying the remote stub to find out if it had
1495 attached to the inferior or not. */
1497 static struct inferior *
1498 remote_add_inferior (int fake_pid_p, int pid, int attached)
1500 struct inferior *inf;
1502 /* Check whether this process we're learning about is to be
1503 considered attached, or if is to be considered to have been
1504 spawned by the stub. */
1506 attached = remote_query_attached (pid);
1508 if (gdbarch_has_global_solist (target_gdbarch ()))
1510 /* If the target shares code across all inferiors, then every
1511 attach adds a new inferior. */
1512 inf = add_inferior (pid);
1514 /* ... and every inferior is bound to the same program space.
1515 However, each inferior may still have its own address
1517 inf->aspace = maybe_new_address_space ();
1518 inf->pspace = current_program_space;
1522 /* In the traditional debugging scenario, there's a 1-1 match
1523 between program/address spaces. We simply bind the inferior
1524 to the program space's address space. */
1525 inf = current_inferior ();
1526 inferior_appeared (inf, pid);
1529 inf->attach_flag = attached;
1530 inf->fake_pid_p = fake_pid_p;
1535 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1536 according to RUNNING. */
1539 remote_add_thread (ptid_t ptid, int running)
1541 struct remote_state *rs = get_remote_state ();
1543 /* GDB historically didn't pull threads in the initial connection
1544 setup. If the remote target doesn't even have a concept of
1545 threads (e.g., a bare-metal target), even if internally we
1546 consider that a single-threaded target, mentioning a new thread
1547 might be confusing to the user. Be silent then, preserving the
1548 age old behavior. */
1549 if (rs->starting_up)
1550 add_thread_silent (ptid);
1554 set_executing (ptid, running);
1555 set_running (ptid, running);
1558 /* Come here when we learn about a thread id from the remote target.
1559 It may be the first time we hear about such thread, so take the
1560 opportunity to add it to GDB's thread list. In case this is the
1561 first time we're noticing its corresponding inferior, add it to
1562 GDB's inferior list as well. */
1565 remote_notice_new_inferior (ptid_t currthread, int running)
1567 /* If this is a new thread, add it to GDB's thread list.
1568 If we leave it up to WFI to do this, bad things will happen. */
1570 if (in_thread_list (currthread) && is_exited (currthread))
1572 /* We're seeing an event on a thread id we knew had exited.
1573 This has to be a new thread reusing the old id. Add it. */
1574 remote_add_thread (currthread, running);
1578 if (!in_thread_list (currthread))
1580 struct inferior *inf = NULL;
1581 int pid = ptid_get_pid (currthread);
1583 if (ptid_is_pid (inferior_ptid)
1584 && pid == ptid_get_pid (inferior_ptid))
1586 /* inferior_ptid has no thread member yet. This can happen
1587 with the vAttach -> remote_wait,"TAAthread:" path if the
1588 stub doesn't support qC. This is the first stop reported
1589 after an attach, so this is the main thread. Update the
1590 ptid in the thread list. */
1591 if (in_thread_list (pid_to_ptid (pid)))
1592 thread_change_ptid (inferior_ptid, currthread);
1595 remote_add_thread (currthread, running);
1596 inferior_ptid = currthread;
1601 if (ptid_equal (magic_null_ptid, inferior_ptid))
1603 /* inferior_ptid is not set yet. This can happen with the
1604 vRun -> remote_wait,"TAAthread:" path if the stub
1605 doesn't support qC. This is the first stop reported
1606 after an attach, so this is the main thread. Update the
1607 ptid in the thread list. */
1608 thread_change_ptid (inferior_ptid, currthread);
1612 /* When connecting to a target remote, or to a target
1613 extended-remote which already was debugging an inferior, we
1614 may not know about it yet. Add it before adding its child
1615 thread, so notifications are emitted in a sensible order. */
1616 if (!in_inferior_list (ptid_get_pid (currthread)))
1618 struct remote_state *rs = get_remote_state ();
1619 int fake_pid_p = !remote_multi_process_p (rs);
1621 inf = remote_add_inferior (fake_pid_p,
1622 ptid_get_pid (currthread), -1);
1625 /* This is really a new thread. Add it. */
1626 remote_add_thread (currthread, running);
1628 /* If we found a new inferior, let the common code do whatever
1629 it needs to with it (e.g., read shared libraries, insert
1630 breakpoints), unless we're just setting up an all-stop
1634 struct remote_state *rs = get_remote_state ();
1636 if (non_stop || !rs->starting_up)
1637 notice_new_inferior (currthread, running, 0);
1642 /* Return the private thread data, creating it if necessary. */
1644 static struct private_thread_info *
1645 demand_private_info (ptid_t ptid)
1647 struct thread_info *info = find_thread_ptid (ptid);
1653 info->private = xmalloc (sizeof (*(info->private)));
1654 info->private_dtor = free_private_thread_info;
1655 info->private->core = -1;
1656 info->private->extra = 0;
1659 return info->private;
1662 /* Call this function as a result of
1663 1) A halt indication (T packet) containing a thread id
1664 2) A direct query of currthread
1665 3) Successful execution of set thread */
1668 record_currthread (struct remote_state *rs, ptid_t currthread)
1670 rs->general_thread = currthread;
1673 /* If 'QPassSignals' is supported, tell the remote stub what signals
1674 it can simply pass through to the inferior without reporting. */
1677 remote_pass_signals (struct target_ops *self,
1678 int numsigs, unsigned char *pass_signals)
1680 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1682 char *pass_packet, *p;
1684 struct remote_state *rs = get_remote_state ();
1686 gdb_assert (numsigs < 256);
1687 for (i = 0; i < numsigs; i++)
1689 if (pass_signals[i])
1692 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1693 strcpy (pass_packet, "QPassSignals:");
1694 p = pass_packet + strlen (pass_packet);
1695 for (i = 0; i < numsigs; i++)
1697 if (pass_signals[i])
1700 *p++ = tohex (i >> 4);
1701 *p++ = tohex (i & 15);
1710 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1712 putpkt (pass_packet);
1713 getpkt (&rs->buf, &rs->buf_size, 0);
1714 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1715 if (rs->last_pass_packet)
1716 xfree (rs->last_pass_packet);
1717 rs->last_pass_packet = pass_packet;
1720 xfree (pass_packet);
1724 /* If 'QProgramSignals' is supported, tell the remote stub what
1725 signals it should pass through to the inferior when detaching. */
1728 remote_program_signals (struct target_ops *self,
1729 int numsigs, unsigned char *signals)
1731 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1735 struct remote_state *rs = get_remote_state ();
1737 gdb_assert (numsigs < 256);
1738 for (i = 0; i < numsigs; i++)
1743 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1744 strcpy (packet, "QProgramSignals:");
1745 p = packet + strlen (packet);
1746 for (i = 0; i < numsigs; i++)
1748 if (signal_pass_state (i))
1751 *p++ = tohex (i >> 4);
1752 *p++ = tohex (i & 15);
1761 if (!rs->last_program_signals_packet
1762 || strcmp (rs->last_program_signals_packet, packet) != 0)
1765 getpkt (&rs->buf, &rs->buf_size, 0);
1766 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1767 xfree (rs->last_program_signals_packet);
1768 rs->last_program_signals_packet = packet;
1775 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1776 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1777 thread. If GEN is set, set the general thread, if not, then set
1778 the step/continue thread. */
1780 set_thread (struct ptid ptid, int gen)
1782 struct remote_state *rs = get_remote_state ();
1783 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1784 char *buf = rs->buf;
1785 char *endbuf = rs->buf + get_remote_packet_size ();
1787 if (ptid_equal (state, ptid))
1791 *buf++ = gen ? 'g' : 'c';
1792 if (ptid_equal (ptid, magic_null_ptid))
1793 xsnprintf (buf, endbuf - buf, "0");
1794 else if (ptid_equal (ptid, any_thread_ptid))
1795 xsnprintf (buf, endbuf - buf, "0");
1796 else if (ptid_equal (ptid, minus_one_ptid))
1797 xsnprintf (buf, endbuf - buf, "-1");
1799 write_ptid (buf, endbuf, ptid);
1801 getpkt (&rs->buf, &rs->buf_size, 0);
1803 rs->general_thread = ptid;
1805 rs->continue_thread = ptid;
1809 set_general_thread (struct ptid ptid)
1811 set_thread (ptid, 1);
1815 set_continue_thread (struct ptid ptid)
1817 set_thread (ptid, 0);
1820 /* Change the remote current process. Which thread within the process
1821 ends up selected isn't important, as long as it is the same process
1822 as what INFERIOR_PTID points to.
1824 This comes from that fact that there is no explicit notion of
1825 "selected process" in the protocol. The selected process for
1826 general operations is the process the selected general thread
1830 set_general_process (void)
1832 struct remote_state *rs = get_remote_state ();
1834 /* If the remote can't handle multiple processes, don't bother. */
1835 if (!rs->extended || !remote_multi_process_p (rs))
1838 /* We only need to change the remote current thread if it's pointing
1839 at some other process. */
1840 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1841 set_general_thread (inferior_ptid);
1845 /* Return nonzero if this is the main thread that we made up ourselves
1846 to model non-threaded targets as single-threaded. */
1849 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
1851 struct remote_state *rs = get_remote_state ();
1854 if (ptid_equal (ptid, magic_null_ptid))
1855 /* The main thread is always alive. */
1858 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
1859 /* The main thread is always alive. This can happen after a
1860 vAttach, if the remote side doesn't support
1867 /* Return nonzero if the thread PTID is still alive on the remote
1871 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1873 struct remote_state *rs = get_remote_state ();
1876 /* Check if this is a thread that we made up ourselves to model
1877 non-threaded targets as single-threaded. */
1878 if (remote_thread_always_alive (ops, ptid))
1882 endp = rs->buf + get_remote_packet_size ();
1885 write_ptid (p, endp, ptid);
1888 getpkt (&rs->buf, &rs->buf_size, 0);
1889 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1892 /* About these extended threadlist and threadinfo packets. They are
1893 variable length packets but, the fields within them are often fixed
1894 length. They are redundent enough to send over UDP as is the
1895 remote protocol in general. There is a matching unit test module
1898 /* WARNING: This threadref data structure comes from the remote O.S.,
1899 libstub protocol encoding, and remote.c. It is not particularly
1902 /* Right now, the internal structure is int. We want it to be bigger.
1903 Plan to fix this. */
1905 typedef int gdb_threadref; /* Internal GDB thread reference. */
1907 /* gdb_ext_thread_info is an internal GDB data structure which is
1908 equivalent to the reply of the remote threadinfo packet. */
1910 struct gdb_ext_thread_info
1912 threadref threadid; /* External form of thread reference. */
1913 int active; /* Has state interesting to GDB?
1915 char display[256]; /* Brief state display, name,
1916 blocked/suspended. */
1917 char shortname[32]; /* To be used to name threads. */
1918 char more_display[256]; /* Long info, statistics, queue depth,
1922 /* The volume of remote transfers can be limited by submitting
1923 a mask containing bits specifying the desired information.
1924 Use a union of these values as the 'selection' parameter to
1925 get_thread_info. FIXME: Make these TAG names more thread specific. */
1927 #define TAG_THREADID 1
1928 #define TAG_EXISTS 2
1929 #define TAG_DISPLAY 4
1930 #define TAG_THREADNAME 8
1931 #define TAG_MOREDISPLAY 16
1933 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1935 static char *unpack_nibble (char *buf, int *val);
1937 static char *unpack_byte (char *buf, int *value);
1939 static char *pack_int (char *buf, int value);
1941 static char *unpack_int (char *buf, int *value);
1943 static char *unpack_string (char *src, char *dest, int length);
1945 static char *pack_threadid (char *pkt, threadref *id);
1947 static char *unpack_threadid (char *inbuf, threadref *id);
1949 void int_to_threadref (threadref *id, int value);
1951 static int threadref_to_int (threadref *ref);
1953 static void copy_threadref (threadref *dest, threadref *src);
1955 static int threadmatch (threadref *dest, threadref *src);
1957 static char *pack_threadinfo_request (char *pkt, int mode,
1960 static int remote_unpack_thread_info_response (char *pkt,
1961 threadref *expectedref,
1962 struct gdb_ext_thread_info
1966 static int remote_get_threadinfo (threadref *threadid,
1967 int fieldset, /*TAG mask */
1968 struct gdb_ext_thread_info *info);
1970 static char *pack_threadlist_request (char *pkt, int startflag,
1972 threadref *nextthread);
1974 static int parse_threadlist_response (char *pkt,
1976 threadref *original_echo,
1977 threadref *resultlist,
1980 static int remote_get_threadlist (int startflag,
1981 threadref *nextthread,
1985 threadref *threadlist);
1987 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1989 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1990 void *context, int looplimit);
1992 static int remote_newthread_step (threadref *ref, void *context);
1995 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1996 buffer we're allowed to write to. Returns
1997 BUF+CHARACTERS_WRITTEN. */
2000 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2003 struct remote_state *rs = get_remote_state ();
2005 if (remote_multi_process_p (rs))
2007 pid = ptid_get_pid (ptid);
2009 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2011 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2013 tid = ptid_get_lwp (ptid);
2015 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2017 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2022 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2023 passed the last parsed char. Returns null_ptid on error. */
2026 read_ptid (char *buf, char **obuf)
2030 ULONGEST pid = 0, tid = 0;
2034 /* Multi-process ptid. */
2035 pp = unpack_varlen_hex (p + 1, &pid);
2037 error (_("invalid remote ptid: %s"), p);
2040 pp = unpack_varlen_hex (p + 1, &tid);
2043 return ptid_build (pid, tid, 0);
2046 /* No multi-process. Just a tid. */
2047 pp = unpack_varlen_hex (p, &tid);
2049 /* Since the stub is not sending a process id, then default to
2050 what's in inferior_ptid, unless it's null at this point. If so,
2051 then since there's no way to know the pid of the reported
2052 threads, use the magic number. */
2053 if (ptid_equal (inferior_ptid, null_ptid))
2054 pid = ptid_get_pid (magic_null_ptid);
2056 pid = ptid_get_pid (inferior_ptid);
2060 return ptid_build (pid, tid, 0);
2066 if (ch >= 'a' && ch <= 'f')
2067 return ch - 'a' + 10;
2068 if (ch >= '0' && ch <= '9')
2070 if (ch >= 'A' && ch <= 'F')
2071 return ch - 'A' + 10;
2076 stub_unpack_int (char *buff, int fieldlength)
2083 nibble = stubhex (*buff++);
2087 retval = retval << 4;
2093 unpack_nibble (char *buf, int *val)
2095 *val = fromhex (*buf++);
2100 unpack_byte (char *buf, int *value)
2102 *value = stub_unpack_int (buf, 2);
2107 pack_int (char *buf, int value)
2109 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2110 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2111 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2112 buf = pack_hex_byte (buf, (value & 0xff));
2117 unpack_int (char *buf, int *value)
2119 *value = stub_unpack_int (buf, 8);
2123 #if 0 /* Currently unused, uncomment when needed. */
2124 static char *pack_string (char *pkt, char *string);
2127 pack_string (char *pkt, char *string)
2132 len = strlen (string);
2134 len = 200; /* Bigger than most GDB packets, junk??? */
2135 pkt = pack_hex_byte (pkt, len);
2139 if ((ch == '\0') || (ch == '#'))
2140 ch = '*'; /* Protect encapsulation. */
2145 #endif /* 0 (unused) */
2148 unpack_string (char *src, char *dest, int length)
2157 pack_threadid (char *pkt, threadref *id)
2160 unsigned char *altid;
2162 altid = (unsigned char *) id;
2163 limit = pkt + BUF_THREAD_ID_SIZE;
2165 pkt = pack_hex_byte (pkt, *altid++);
2171 unpack_threadid (char *inbuf, threadref *id)
2174 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2177 altref = (char *) id;
2179 while (inbuf < limit)
2181 x = stubhex (*inbuf++);
2182 y = stubhex (*inbuf++);
2183 *altref++ = (x << 4) | y;
2188 /* Externally, threadrefs are 64 bits but internally, they are still
2189 ints. This is due to a mismatch of specifications. We would like
2190 to use 64bit thread references internally. This is an adapter
2194 int_to_threadref (threadref *id, int value)
2196 unsigned char *scan;
2198 scan = (unsigned char *) id;
2204 *scan++ = (value >> 24) & 0xff;
2205 *scan++ = (value >> 16) & 0xff;
2206 *scan++ = (value >> 8) & 0xff;
2207 *scan++ = (value & 0xff);
2211 threadref_to_int (threadref *ref)
2214 unsigned char *scan;
2220 value = (value << 8) | ((*scan++) & 0xff);
2225 copy_threadref (threadref *dest, threadref *src)
2228 unsigned char *csrc, *cdest;
2230 csrc = (unsigned char *) src;
2231 cdest = (unsigned char *) dest;
2238 threadmatch (threadref *dest, threadref *src)
2240 /* Things are broken right now, so just assume we got a match. */
2242 unsigned char *srcp, *destp;
2244 srcp = (char *) src;
2245 destp = (char *) dest;
2249 result &= (*srcp++ == *destp++) ? 1 : 0;
2256 threadid:1, # always request threadid
2263 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2266 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2268 *pkt++ = 'q'; /* Info Query */
2269 *pkt++ = 'P'; /* process or thread info */
2270 pkt = pack_int (pkt, mode); /* mode */
2271 pkt = pack_threadid (pkt, id); /* threadid */
2272 *pkt = '\0'; /* terminate */
2276 /* These values tag the fields in a thread info response packet. */
2277 /* Tagging the fields allows us to request specific fields and to
2278 add more fields as time goes by. */
2280 #define TAG_THREADID 1 /* Echo the thread identifier. */
2281 #define TAG_EXISTS 2 /* Is this process defined enough to
2282 fetch registers and its stack? */
2283 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2284 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2285 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2289 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2290 struct gdb_ext_thread_info *info)
2292 struct remote_state *rs = get_remote_state ();
2296 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2299 /* info->threadid = 0; FIXME: implement zero_threadref. */
2301 info->display[0] = '\0';
2302 info->shortname[0] = '\0';
2303 info->more_display[0] = '\0';
2305 /* Assume the characters indicating the packet type have been
2307 pkt = unpack_int (pkt, &mask); /* arg mask */
2308 pkt = unpack_threadid (pkt, &ref);
2311 warning (_("Incomplete response to threadinfo request."));
2312 if (!threadmatch (&ref, expectedref))
2313 { /* This is an answer to a different request. */
2314 warning (_("ERROR RMT Thread info mismatch."));
2317 copy_threadref (&info->threadid, &ref);
2319 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2321 /* Packets are terminated with nulls. */
2322 while ((pkt < limit) && mask && *pkt)
2324 pkt = unpack_int (pkt, &tag); /* tag */
2325 pkt = unpack_byte (pkt, &length); /* length */
2326 if (!(tag & mask)) /* Tags out of synch with mask. */
2328 warning (_("ERROR RMT: threadinfo tag mismatch."));
2332 if (tag == TAG_THREADID)
2336 warning (_("ERROR RMT: length of threadid is not 16."));
2340 pkt = unpack_threadid (pkt, &ref);
2341 mask = mask & ~TAG_THREADID;
2344 if (tag == TAG_EXISTS)
2346 info->active = stub_unpack_int (pkt, length);
2348 mask = mask & ~(TAG_EXISTS);
2351 warning (_("ERROR RMT: 'exists' length too long."));
2357 if (tag == TAG_THREADNAME)
2359 pkt = unpack_string (pkt, &info->shortname[0], length);
2360 mask = mask & ~TAG_THREADNAME;
2363 if (tag == TAG_DISPLAY)
2365 pkt = unpack_string (pkt, &info->display[0], length);
2366 mask = mask & ~TAG_DISPLAY;
2369 if (tag == TAG_MOREDISPLAY)
2371 pkt = unpack_string (pkt, &info->more_display[0], length);
2372 mask = mask & ~TAG_MOREDISPLAY;
2375 warning (_("ERROR RMT: unknown thread info tag."));
2376 break; /* Not a tag we know about. */
2382 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2383 struct gdb_ext_thread_info *info)
2385 struct remote_state *rs = get_remote_state ();
2388 pack_threadinfo_request (rs->buf, fieldset, threadid);
2390 getpkt (&rs->buf, &rs->buf_size, 0);
2392 if (rs->buf[0] == '\0')
2395 result = remote_unpack_thread_info_response (rs->buf + 2,
2400 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2403 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2404 threadref *nextthread)
2406 *pkt++ = 'q'; /* info query packet */
2407 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2408 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2409 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2410 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2415 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2418 parse_threadlist_response (char *pkt, int result_limit,
2419 threadref *original_echo, threadref *resultlist,
2422 struct remote_state *rs = get_remote_state ();
2424 int count, resultcount, done;
2427 /* Assume the 'q' and 'M chars have been stripped. */
2428 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2429 /* done parse past here */
2430 pkt = unpack_byte (pkt, &count); /* count field */
2431 pkt = unpack_nibble (pkt, &done);
2432 /* The first threadid is the argument threadid. */
2433 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2434 while ((count-- > 0) && (pkt < limit))
2436 pkt = unpack_threadid (pkt, resultlist++);
2437 if (resultcount++ >= result_limit)
2445 /* Fetch the next batch of threads from the remote. Returns -1 if the
2446 qL packet is not supported, 0 on error and 1 on success. */
2449 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2450 int *done, int *result_count, threadref *threadlist)
2452 struct remote_state *rs = get_remote_state ();
2455 /* Trancate result limit to be smaller than the packet size. */
2456 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2457 >= get_remote_packet_size ())
2458 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2460 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2462 getpkt (&rs->buf, &rs->buf_size, 0);
2463 if (*rs->buf == '\0')
2465 /* Packet not supported. */
2470 parse_threadlist_response (rs->buf + 2, result_limit,
2471 &rs->echo_nextthread, threadlist, done);
2473 if (!threadmatch (&rs->echo_nextthread, nextthread))
2475 /* FIXME: This is a good reason to drop the packet. */
2476 /* Possably, there is a duplicate response. */
2478 retransmit immediatly - race conditions
2479 retransmit after timeout - yes
2481 wait for packet, then exit
2483 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2484 return 0; /* I choose simply exiting. */
2486 if (*result_count <= 0)
2490 warning (_("RMT ERROR : failed to get remote thread list."));
2493 return result; /* break; */
2495 if (*result_count > result_limit)
2498 warning (_("RMT ERROR: threadlist response longer than requested."));
2504 /* Fetch the list of remote threads, with the qL packet, and call
2505 STEPFUNCTION for each thread found. Stops iterating and returns 1
2506 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2507 STEPFUNCTION returns false. If the packet is not supported,
2511 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2514 struct remote_state *rs = get_remote_state ();
2515 int done, i, result_count;
2523 if (loopcount++ > looplimit)
2526 warning (_("Remote fetch threadlist -infinite loop-."));
2529 result = remote_get_threadlist (startflag, &rs->nextthread,
2530 MAXTHREADLISTRESULTS,
2531 &done, &result_count,
2532 rs->resultthreadlist);
2535 /* Clear for later iterations. */
2537 /* Setup to resume next batch of thread references, set nextthread. */
2538 if (result_count >= 1)
2539 copy_threadref (&rs->nextthread,
2540 &rs->resultthreadlist[result_count - 1]);
2542 while (result_count--)
2544 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2554 /* A thread found on the remote target. */
2556 typedef struct thread_item
2558 /* The thread's PTID. */
2561 /* The thread's extra info. May be NULL. */
2564 /* The core the thread was running on. -1 if not known. */
2567 DEF_VEC_O(thread_item_t);
2569 /* Context passed around to the various methods listing remote
2570 threads. As new threads are found, they're added to the ITEMS
2573 struct threads_listing_context
2575 /* The threads found on the remote target. */
2576 VEC (thread_item_t) *items;
2579 /* Discard the contents of the constructed thread listing context. */
2582 clear_threads_listing_context (void *p)
2584 struct threads_listing_context *context = p;
2586 struct thread_item *item;
2588 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2589 xfree (item->extra);
2591 VEC_free (thread_item_t, context->items);
2595 remote_newthread_step (threadref *ref, void *data)
2597 struct threads_listing_context *context = data;
2598 struct thread_item item;
2599 int pid = ptid_get_pid (inferior_ptid);
2601 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2605 VEC_safe_push (thread_item_t, context->items, &item);
2607 return 1; /* continue iterator */
2610 #define CRAZY_MAX_THREADS 1000
2613 remote_current_thread (ptid_t oldpid)
2615 struct remote_state *rs = get_remote_state ();
2618 getpkt (&rs->buf, &rs->buf_size, 0);
2619 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2620 return read_ptid (&rs->buf[2], NULL);
2625 /* List remote threads using the deprecated qL packet. */
2628 remote_get_threads_with_ql (struct target_ops *ops,
2629 struct threads_listing_context *context)
2631 if (remote_threadlist_iterator (remote_newthread_step, context,
2632 CRAZY_MAX_THREADS) >= 0)
2638 #if defined(HAVE_LIBEXPAT)
2641 start_thread (struct gdb_xml_parser *parser,
2642 const struct gdb_xml_element *element,
2643 void *user_data, VEC(gdb_xml_value_s) *attributes)
2645 struct threads_listing_context *data = user_data;
2647 struct thread_item item;
2649 struct gdb_xml_value *attr;
2651 id = xml_find_attribute (attributes, "id")->value;
2652 item.ptid = read_ptid (id, NULL);
2654 attr = xml_find_attribute (attributes, "core");
2656 item.core = *(ULONGEST *) attr->value;
2662 VEC_safe_push (thread_item_t, data->items, &item);
2666 end_thread (struct gdb_xml_parser *parser,
2667 const struct gdb_xml_element *element,
2668 void *user_data, const char *body_text)
2670 struct threads_listing_context *data = user_data;
2672 if (body_text && *body_text)
2673 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2676 const struct gdb_xml_attribute thread_attributes[] = {
2677 { "id", GDB_XML_AF_NONE, NULL, NULL },
2678 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2679 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2682 const struct gdb_xml_element thread_children[] = {
2683 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2686 const struct gdb_xml_element threads_children[] = {
2687 { "thread", thread_attributes, thread_children,
2688 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2689 start_thread, end_thread },
2690 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2693 const struct gdb_xml_element threads_elements[] = {
2694 { "threads", NULL, threads_children,
2695 GDB_XML_EF_NONE, NULL, NULL },
2696 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2701 /* List remote threads using qXfer:threads:read. */
2704 remote_get_threads_with_qxfer (struct target_ops *ops,
2705 struct threads_listing_context *context)
2707 #if defined(HAVE_LIBEXPAT)
2708 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2710 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2711 struct cleanup *back_to = make_cleanup (xfree, xml);
2713 if (xml != NULL && *xml != '\0')
2715 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2716 threads_elements, xml, context);
2719 do_cleanups (back_to);
2727 /* List remote threads using qfThreadInfo/qsThreadInfo. */
2730 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2731 struct threads_listing_context *context)
2733 struct remote_state *rs = get_remote_state ();
2735 if (rs->use_threadinfo_query)
2739 putpkt ("qfThreadInfo");
2740 getpkt (&rs->buf, &rs->buf_size, 0);
2742 if (bufp[0] != '\0') /* q packet recognized */
2744 while (*bufp++ == 'm') /* reply contains one or more TID */
2748 struct thread_item item;
2750 item.ptid = read_ptid (bufp, &bufp);
2754 VEC_safe_push (thread_item_t, context->items, &item);
2756 while (*bufp++ == ','); /* comma-separated list */
2757 putpkt ("qsThreadInfo");
2758 getpkt (&rs->buf, &rs->buf_size, 0);
2765 /* Packet not recognized. */
2766 rs->use_threadinfo_query = 0;
2773 /* Implement the to_update_thread_list function for the remote
2777 remote_update_thread_list (struct target_ops *ops)
2779 struct remote_state *rs = get_remote_state ();
2780 struct threads_listing_context context;
2781 struct cleanup *old_chain;
2784 context.items = NULL;
2785 old_chain = make_cleanup (clear_threads_listing_context, &context);
2787 /* We have a few different mechanisms to fetch the thread list. Try
2788 them all, starting with the most preferred one first, falling
2789 back to older methods. */
2790 if (remote_get_threads_with_qxfer (ops, &context)
2791 || remote_get_threads_with_qthreadinfo (ops, &context)
2792 || remote_get_threads_with_ql (ops, &context))
2795 struct thread_item *item;
2796 struct thread_info *tp, *tmp;
2800 if (VEC_empty (thread_item_t, context.items)
2801 && remote_thread_always_alive (ops, inferior_ptid))
2803 /* Some targets don't really support threads, but still
2804 reply an (empty) thread list in response to the thread
2805 listing packets, instead of replying "packet not
2806 supported". Exit early so we don't delete the main
2808 do_cleanups (old_chain);
2812 /* CONTEXT now holds the current thread list on the remote
2813 target end. Delete GDB-side threads no longer found on the
2815 ALL_NON_EXITED_THREADS_SAFE (tp, tmp)
2818 VEC_iterate (thread_item_t, context.items, i, item);
2821 if (ptid_equal (item->ptid, tp->ptid))
2825 if (i == VEC_length (thread_item_t, context.items))
2828 delete_thread (tp->ptid);
2832 /* And now add threads we don't know about yet to our list. */
2834 VEC_iterate (thread_item_t, context.items, i, item);
2837 if (!ptid_equal (item->ptid, null_ptid))
2839 struct private_thread_info *info;
2840 /* In non-stop mode, we assume new found threads are
2841 running until proven otherwise with a stop reply. In
2842 all-stop, we can only get here if all threads are
2844 int running = non_stop ? 1 : 0;
2846 remote_notice_new_inferior (item->ptid, running);
2848 info = demand_private_info (item->ptid);
2849 info->core = item->core;
2850 info->extra = item->extra;
2858 /* If no thread listing method is supported, then query whether
2859 each known thread is alive, one by one, with the T packet.
2860 If the target doesn't support threads at all, then this is a
2861 no-op. See remote_thread_alive. */
2865 do_cleanups (old_chain);
2869 * Collect a descriptive string about the given thread.
2870 * The target may say anything it wants to about the thread
2871 * (typically info about its blocked / runnable state, name, etc.).
2872 * This string will appear in the info threads display.
2874 * Optional: targets are not required to implement this function.
2878 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
2880 struct remote_state *rs = get_remote_state ();
2884 struct gdb_ext_thread_info threadinfo;
2885 static char display_buf[100]; /* arbitrary... */
2886 int n = 0; /* position in display_buf */
2888 if (rs->remote_desc == 0) /* paranoia */
2889 internal_error (__FILE__, __LINE__,
2890 _("remote_threads_extra_info"));
2892 if (ptid_equal (tp->ptid, magic_null_ptid)
2893 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
2894 /* This is the main thread which was added by GDB. The remote
2895 server doesn't know about it. */
2898 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2900 struct thread_info *info = find_thread_ptid (tp->ptid);
2902 if (info && info->private)
2903 return info->private->extra;
2908 if (rs->use_threadextra_query)
2911 char *endb = rs->buf + get_remote_packet_size ();
2913 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2915 write_ptid (b, endb, tp->ptid);
2918 getpkt (&rs->buf, &rs->buf_size, 0);
2919 if (rs->buf[0] != 0)
2921 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2922 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2923 display_buf [result] = '\0';
2928 /* If the above query fails, fall back to the old method. */
2929 rs->use_threadextra_query = 0;
2930 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2931 | TAG_MOREDISPLAY | TAG_DISPLAY;
2932 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
2933 if (remote_get_threadinfo (&id, set, &threadinfo))
2934 if (threadinfo.active)
2936 if (*threadinfo.shortname)
2937 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2938 " Name: %s,", threadinfo.shortname);
2939 if (*threadinfo.display)
2940 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2941 " State: %s,", threadinfo.display);
2942 if (*threadinfo.more_display)
2943 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2944 " Priority: %s", threadinfo.more_display);
2948 /* For purely cosmetic reasons, clear up trailing commas. */
2949 if (',' == display_buf[n-1])
2950 display_buf[n-1] = ' ';
2959 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
2960 struct static_tracepoint_marker *marker)
2962 struct remote_state *rs = get_remote_state ();
2965 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
2967 p += hexnumstr (p, addr);
2969 getpkt (&rs->buf, &rs->buf_size, 0);
2973 error (_("Remote failure reply: %s"), p);
2977 parse_static_tracepoint_marker_definition (p, &p, marker);
2984 static VEC(static_tracepoint_marker_p) *
2985 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
2988 struct remote_state *rs = get_remote_state ();
2989 VEC(static_tracepoint_marker_p) *markers = NULL;
2990 struct static_tracepoint_marker *marker = NULL;
2991 struct cleanup *old_chain;
2994 /* Ask for a first packet of static tracepoint marker
2997 getpkt (&rs->buf, &rs->buf_size, 0);
3000 error (_("Remote failure reply: %s"), p);
3002 old_chain = make_cleanup (free_current_marker, &marker);
3007 marker = XCNEW (struct static_tracepoint_marker);
3011 parse_static_tracepoint_marker_definition (p, &p, marker);
3013 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3015 VEC_safe_push (static_tracepoint_marker_p,
3021 release_static_tracepoint_marker (marker);
3022 memset (marker, 0, sizeof (*marker));
3025 while (*p++ == ','); /* comma-separated list */
3026 /* Ask for another packet of static tracepoint definition. */
3028 getpkt (&rs->buf, &rs->buf_size, 0);
3032 do_cleanups (old_chain);
3037 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3040 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3042 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3046 /* Restart the remote side; this is an extended protocol operation. */
3049 extended_remote_restart (void)
3051 struct remote_state *rs = get_remote_state ();
3053 /* Send the restart command; for reasons I don't understand the
3054 remote side really expects a number after the "R". */
3055 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3058 remote_fileio_reset ();
3061 /* Clean up connection to a remote debugger. */
3064 remote_close (struct target_ops *self)
3066 struct remote_state *rs = get_remote_state ();
3068 if (rs->remote_desc == NULL)
3069 return; /* already closed */
3071 /* Make sure we leave stdin registered in the event loop, and we
3072 don't leave the async SIGINT signal handler installed. */
3073 remote_terminal_ours (self);
3075 serial_close (rs->remote_desc);
3076 rs->remote_desc = NULL;
3078 /* We don't have a connection to the remote stub anymore. Get rid
3079 of all the inferiors and their threads we were controlling.
3080 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3081 will be unable to find the thread corresponding to (pid, 0, 0). */
3082 inferior_ptid = null_ptid;
3083 discard_all_inferiors ();
3085 /* We are closing the remote target, so we should discard
3086 everything of this target. */
3087 discard_pending_stop_replies_in_queue (rs);
3089 if (remote_async_inferior_event_token)
3090 delete_async_event_handler (&remote_async_inferior_event_token);
3092 remote_notif_state_xfree (rs->notif_state);
3094 trace_reset_local_state ();
3097 /* Query the remote side for the text, data and bss offsets. */
3102 struct remote_state *rs = get_remote_state ();
3105 int lose, num_segments = 0, do_sections, do_segments;
3106 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3107 struct section_offsets *offs;
3108 struct symfile_segment_data *data;
3110 if (symfile_objfile == NULL)
3113 putpkt ("qOffsets");
3114 getpkt (&rs->buf, &rs->buf_size, 0);
3117 if (buf[0] == '\000')
3118 return; /* Return silently. Stub doesn't support
3122 warning (_("Remote failure reply: %s"), buf);
3126 /* Pick up each field in turn. This used to be done with scanf, but
3127 scanf will make trouble if CORE_ADDR size doesn't match
3128 conversion directives correctly. The following code will work
3129 with any size of CORE_ADDR. */
3130 text_addr = data_addr = bss_addr = 0;
3134 if (strncmp (ptr, "Text=", 5) == 0)
3137 /* Don't use strtol, could lose on big values. */
3138 while (*ptr && *ptr != ';')
3139 text_addr = (text_addr << 4) + fromhex (*ptr++);
3141 if (strncmp (ptr, ";Data=", 6) == 0)
3144 while (*ptr && *ptr != ';')
3145 data_addr = (data_addr << 4) + fromhex (*ptr++);
3150 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3153 while (*ptr && *ptr != ';')
3154 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3156 if (bss_addr != data_addr)
3157 warning (_("Target reported unsupported offsets: %s"), buf);
3162 else if (strncmp (ptr, "TextSeg=", 8) == 0)
3165 /* Don't use strtol, could lose on big values. */
3166 while (*ptr && *ptr != ';')
3167 text_addr = (text_addr << 4) + fromhex (*ptr++);
3170 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3173 while (*ptr && *ptr != ';')
3174 data_addr = (data_addr << 4) + fromhex (*ptr++);
3182 error (_("Malformed response to offset query, %s"), buf);
3183 else if (*ptr != '\0')
3184 warning (_("Target reported unsupported offsets: %s"), buf);
3186 offs = ((struct section_offsets *)
3187 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3188 memcpy (offs, symfile_objfile->section_offsets,
3189 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3191 data = get_symfile_segment_data (symfile_objfile->obfd);
3192 do_segments = (data != NULL);
3193 do_sections = num_segments == 0;
3195 if (num_segments > 0)
3197 segments[0] = text_addr;
3198 segments[1] = data_addr;
3200 /* If we have two segments, we can still try to relocate everything
3201 by assuming that the .text and .data offsets apply to the whole
3202 text and data segments. Convert the offsets given in the packet
3203 to base addresses for symfile_map_offsets_to_segments. */
3204 else if (data && data->num_segments == 2)
3206 segments[0] = data->segment_bases[0] + text_addr;
3207 segments[1] = data->segment_bases[1] + data_addr;
3210 /* If the object file has only one segment, assume that it is text
3211 rather than data; main programs with no writable data are rare,
3212 but programs with no code are useless. Of course the code might
3213 have ended up in the data segment... to detect that we would need
3214 the permissions here. */
3215 else if (data && data->num_segments == 1)
3217 segments[0] = data->segment_bases[0] + text_addr;
3220 /* There's no way to relocate by segment. */
3226 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3227 offs, num_segments, segments);
3229 if (ret == 0 && !do_sections)
3230 error (_("Can not handle qOffsets TextSeg "
3231 "response with this symbol file"));
3238 free_symfile_segment_data (data);
3242 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3244 /* This is a temporary kludge to force data and bss to use the
3245 same offsets because that's what nlmconv does now. The real
3246 solution requires changes to the stub and remote.c that I
3247 don't have time to do right now. */
3249 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3250 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3253 objfile_relocate (symfile_objfile, offs);
3256 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3257 threads we know are stopped already. This is used during the
3258 initial remote connection in non-stop mode --- threads that are
3259 reported as already being stopped are left stopped. */
3262 set_stop_requested_callback (struct thread_info *thread, void *data)
3264 /* If we have a stop reply for this thread, it must be stopped. */
3265 if (peek_stop_reply (thread->ptid))
3266 set_stop_requested (thread->ptid, 1);
3271 /* Send interrupt_sequence to remote target. */
3273 send_interrupt_sequence (void)
3275 struct remote_state *rs = get_remote_state ();
3277 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3278 remote_serial_write ("\x03", 1);
3279 else if (interrupt_sequence_mode == interrupt_sequence_break)
3280 serial_send_break (rs->remote_desc);
3281 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3283 serial_send_break (rs->remote_desc);
3284 remote_serial_write ("g", 1);
3287 internal_error (__FILE__, __LINE__,
3288 _("Invalid value for interrupt_sequence_mode: %s."),
3289 interrupt_sequence_mode);
3293 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3294 and extract the PTID. Returns NULL_PTID if not found. */
3297 stop_reply_extract_thread (char *stop_reply)
3299 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3303 /* Txx r:val ; r:val (...) */
3306 /* Look for "register" named "thread". */
3311 p1 = strchr (p, ':');
3315 if (strncmp (p, "thread", p1 - p) == 0)
3316 return read_ptid (++p1, &p);
3318 p1 = strchr (p, ';');
3330 /* Determine the remote side's current thread. If we have a stop
3331 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3332 "thread" register we can extract the current thread from. If not,
3333 ask the remote which is the current thread with qC. The former
3334 method avoids a roundtrip. */
3337 get_current_thread (char *wait_status)
3341 /* Note we don't use remote_parse_stop_reply as that makes use of
3342 the target architecture, which we haven't yet fully determined at
3344 if (wait_status != NULL)
3345 ptid = stop_reply_extract_thread (wait_status);
3346 if (ptid_equal (ptid, null_ptid))
3347 ptid = remote_current_thread (inferior_ptid);
3352 /* Query the remote target for which is the current thread/process,
3353 add it to our tables, and update INFERIOR_PTID. The caller is
3354 responsible for setting the state such that the remote end is ready
3355 to return the current thread.
3357 This function is called after handling the '?' or 'vRun' packets,
3358 whose response is a stop reply from which we can also try
3359 extracting the thread. If the target doesn't support the explicit
3360 qC query, we infer the current thread from that stop reply, passed
3361 in in WAIT_STATUS, which may be NULL. */
3364 add_current_inferior_and_thread (char *wait_status)
3366 struct remote_state *rs = get_remote_state ();
3368 ptid_t ptid = null_ptid;
3370 inferior_ptid = null_ptid;
3372 /* Now, if we have thread information, update inferior_ptid. */
3373 ptid = get_current_thread (wait_status);
3375 if (!ptid_equal (ptid, null_ptid))
3377 if (!remote_multi_process_p (rs))
3380 inferior_ptid = ptid;
3384 /* Without this, some commands which require an active target
3385 (such as kill) won't work. This variable serves (at least)
3386 double duty as both the pid of the target process (if it has
3387 such), and as a flag indicating that a target is active. */
3388 inferior_ptid = magic_null_ptid;
3392 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3394 /* Add the main thread. */
3395 add_thread_silent (inferior_ptid);
3399 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3401 struct remote_state *rs = get_remote_state ();
3402 struct packet_config *noack_config;
3403 char *wait_status = NULL;
3405 immediate_quit++; /* Allow user to interrupt it. */
3408 if (interrupt_on_connect)
3409 send_interrupt_sequence ();
3411 /* Ack any packet which the remote side has already sent. */
3412 serial_write (rs->remote_desc, "+", 1);
3414 /* Signal other parts that we're going through the initial setup,
3415 and so things may not be stable yet. */
3416 rs->starting_up = 1;
3418 /* The first packet we send to the target is the optional "supported
3419 packets" request. If the target can answer this, it will tell us
3420 which later probes to skip. */
3421 remote_query_supported ();
3423 /* If the stub wants to get a QAllow, compose one and send it. */
3424 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3425 remote_set_permissions (target);
3427 /* Next, we possibly activate noack mode.
3429 If the QStartNoAckMode packet configuration is set to AUTO,
3430 enable noack mode if the stub reported a wish for it with
3433 If set to TRUE, then enable noack mode even if the stub didn't
3434 report it in qSupported. If the stub doesn't reply OK, the
3435 session ends with an error.
3437 If FALSE, then don't activate noack mode, regardless of what the
3438 stub claimed should be the default with qSupported. */
3440 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3441 if (packet_config_support (noack_config) != PACKET_DISABLE)
3443 putpkt ("QStartNoAckMode");
3444 getpkt (&rs->buf, &rs->buf_size, 0);
3445 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3451 /* Tell the remote that we are using the extended protocol. */
3453 getpkt (&rs->buf, &rs->buf_size, 0);
3456 /* Let the target know which signals it is allowed to pass down to
3458 update_signals_program_target ();
3460 /* Next, if the target can specify a description, read it. We do
3461 this before anything involving memory or registers. */
3462 target_find_description ();
3464 /* Next, now that we know something about the target, update the
3465 address spaces in the program spaces. */
3466 update_address_spaces ();
3468 /* On OSs where the list of libraries is global to all
3469 processes, we fetch them early. */
3470 if (gdbarch_has_global_solist (target_gdbarch ()))
3471 solib_add (NULL, from_tty, target, auto_solib_add);
3475 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3476 error (_("Non-stop mode requested, but remote "
3477 "does not support non-stop"));
3479 putpkt ("QNonStop:1");
3480 getpkt (&rs->buf, &rs->buf_size, 0);
3482 if (strcmp (rs->buf, "OK") != 0)
3483 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3485 /* Find about threads and processes the stub is already
3486 controlling. We default to adding them in the running state.
3487 The '?' query below will then tell us about which threads are
3489 remote_update_thread_list (target);
3491 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3493 /* Don't assume that the stub can operate in all-stop mode.
3494 Request it explicitly. */
3495 putpkt ("QNonStop:0");
3496 getpkt (&rs->buf, &rs->buf_size, 0);
3498 if (strcmp (rs->buf, "OK") != 0)
3499 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3502 /* Upload TSVs regardless of whether the target is running or not. The
3503 remote stub, such as GDBserver, may have some predefined or builtin
3504 TSVs, even if the target is not running. */
3505 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3507 struct uploaded_tsv *uploaded_tsvs = NULL;
3509 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3510 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3513 /* Check whether the target is running now. */
3515 getpkt (&rs->buf, &rs->buf_size, 0);
3521 struct inferior *inf;
3523 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3526 error (_("The target is not running (try extended-remote?)"));
3528 /* We're connected, but not running. Drop out before we
3529 call start_remote. */
3530 rs->starting_up = 0;
3535 /* Save the reply for later. */
3536 wait_status = alloca (strlen (rs->buf) + 1);
3537 strcpy (wait_status, rs->buf);
3540 /* Fetch thread list. */
3541 target_update_thread_list ();
3543 /* Let the stub know that we want it to return the thread. */
3544 set_continue_thread (minus_one_ptid);
3546 if (thread_count () == 0)
3548 /* Target has no concept of threads at all. GDB treats
3549 non-threaded target as single-threaded; add a main
3551 add_current_inferior_and_thread (wait_status);
3555 /* We have thread information; select the thread the target
3556 says should be current. If we're reconnecting to a
3557 multi-threaded program, this will ideally be the thread
3558 that last reported an event before GDB disconnected. */
3559 inferior_ptid = get_current_thread (wait_status);
3560 if (ptid_equal (inferior_ptid, null_ptid))
3562 /* Odd... The target was able to list threads, but not
3563 tell us which thread was current (no "thread"
3564 register in T stop reply?). Just pick the first
3565 thread in the thread list then. */
3566 inferior_ptid = thread_list->ptid;
3570 /* init_wait_for_inferior should be called before get_offsets in order
3571 to manage `inserted' flag in bp loc in a correct state.
3572 breakpoint_init_inferior, called from init_wait_for_inferior, set
3573 `inserted' flag to 0, while before breakpoint_re_set, called from
3574 start_remote, set `inserted' flag to 1. In the initialization of
3575 inferior, breakpoint_init_inferior should be called first, and then
3576 breakpoint_re_set can be called. If this order is broken, state of
3577 `inserted' flag is wrong, and cause some problems on breakpoint
3579 init_wait_for_inferior ();
3581 get_offsets (); /* Get text, data & bss offsets. */
3583 /* If we could not find a description using qXfer, and we know
3584 how to do it some other way, try again. This is not
3585 supported for non-stop; it could be, but it is tricky if
3586 there are no stopped threads when we connect. */
3587 if (remote_read_description_p (target)
3588 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3590 target_clear_description ();
3591 target_find_description ();
3594 /* Use the previously fetched status. */
3595 gdb_assert (wait_status != NULL);
3596 strcpy (rs->buf, wait_status);
3597 rs->cached_wait_status = 1;
3600 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3604 /* Clear WFI global state. Do this before finding about new
3605 threads and inferiors, and setting the current inferior.
3606 Otherwise we would clear the proceed status of the current
3607 inferior when we want its stop_soon state to be preserved
3608 (see notice_new_inferior). */
3609 init_wait_for_inferior ();
3611 /* In non-stop, we will either get an "OK", meaning that there
3612 are no stopped threads at this time; or, a regular stop
3613 reply. In the latter case, there may be more than one thread
3614 stopped --- we pull them all out using the vStopped
3616 if (strcmp (rs->buf, "OK") != 0)
3618 struct notif_client *notif = ¬if_client_stop;
3620 /* remote_notif_get_pending_replies acks this one, and gets
3622 rs->notif_state->pending_event[notif_client_stop.id]
3623 = remote_notif_parse (notif, rs->buf);
3624 remote_notif_get_pending_events (notif);
3626 /* Make sure that threads that were stopped remain
3628 iterate_over_threads (set_stop_requested_callback, NULL);
3631 if (target_can_async_p ())
3632 target_async (inferior_event_handler, 0);
3634 if (thread_count () == 0)
3637 error (_("The target is not running (try extended-remote?)"));
3639 /* We're connected, but not running. Drop out before we
3640 call start_remote. */
3641 rs->starting_up = 0;
3645 /* Let the stub know that we want it to return the thread. */
3647 /* Force the stub to choose a thread. */
3648 set_general_thread (null_ptid);
3651 inferior_ptid = remote_current_thread (minus_one_ptid);
3652 if (ptid_equal (inferior_ptid, minus_one_ptid))
3653 error (_("remote didn't report the current thread in non-stop mode"));
3655 get_offsets (); /* Get text, data & bss offsets. */
3657 /* In non-stop mode, any cached wait status will be stored in
3658 the stop reply queue. */
3659 gdb_assert (wait_status == NULL);
3661 /* Report all signals during attach/startup. */
3662 remote_pass_signals (target, 0, NULL);
3665 /* If we connected to a live target, do some additional setup. */
3666 if (target_has_execution)
3668 if (symfile_objfile) /* No use without a symbol-file. */
3669 remote_check_symbols ();
3672 /* Possibly the target has been engaged in a trace run started
3673 previously; find out where things are at. */
3674 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3676 struct uploaded_tp *uploaded_tps = NULL;
3678 if (current_trace_status ()->running)
3679 printf_filtered (_("Trace is already running on the target.\n"));
3681 remote_upload_tracepoints (target, &uploaded_tps);
3683 merge_uploaded_tracepoints (&uploaded_tps);
3686 /* The thread and inferior lists are now synchronized with the
3687 target, our symbols have been relocated, and we're merged the
3688 target's tracepoints with ours. We're done with basic start
3690 rs->starting_up = 0;
3692 /* Maybe breakpoints are global and need to be inserted now. */
3693 if (breakpoints_should_be_inserted_now ())
3694 insert_breakpoints ();
3697 /* Open a connection to a remote debugger.
3698 NAME is the filename used for communication. */
3701 remote_open (const char *name, int from_tty)
3703 remote_open_1 (name, from_tty, &remote_ops, 0);
3706 /* Open a connection to a remote debugger using the extended
3707 remote gdb protocol. NAME is the filename used for communication. */
3710 extended_remote_open (const char *name, int from_tty)
3712 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3715 /* Reset all packets back to "unknown support". Called when opening a
3716 new connection to a remote target. */
3719 reset_all_packet_configs_support (void)
3723 for (i = 0; i < PACKET_MAX; i++)
3724 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3727 /* Initialize all packet configs. */
3730 init_all_packet_configs (void)
3734 for (i = 0; i < PACKET_MAX; i++)
3736 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3737 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3741 /* Symbol look-up. */
3744 remote_check_symbols (void)
3746 struct remote_state *rs = get_remote_state ();
3747 char *msg, *reply, *tmp;
3748 struct bound_minimal_symbol sym;
3751 /* The remote side has no concept of inferiors that aren't running
3752 yet, it only knows about running processes. If we're connected
3753 but our current inferior is not running, we should not invite the
3754 remote target to request symbol lookups related to its
3755 (unrelated) current process. */
3756 if (!target_has_execution)
3759 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
3762 /* Make sure the remote is pointing at the right process. Note
3763 there's no way to select "no process". */
3764 set_general_process ();
3766 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3767 because we need both at the same time. */
3768 msg = alloca (get_remote_packet_size ());
3770 /* Invite target to request symbol lookups. */
3772 putpkt ("qSymbol::");
3773 getpkt (&rs->buf, &rs->buf_size, 0);
3774 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3777 while (strncmp (reply, "qSymbol:", 8) == 0)
3779 struct bound_minimal_symbol sym;
3782 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3784 sym = lookup_minimal_symbol (msg, NULL, NULL);
3785 if (sym.minsym == NULL)
3786 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3789 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3790 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
3792 /* If this is a function address, return the start of code
3793 instead of any data function descriptor. */
3794 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3798 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3799 phex_nz (sym_addr, addr_size), &reply[8]);
3803 getpkt (&rs->buf, &rs->buf_size, 0);
3808 static struct serial *
3809 remote_serial_open (const char *name)
3811 static int udp_warning = 0;
3813 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3814 of in ser-tcp.c, because it is the remote protocol assuming that the
3815 serial connection is reliable and not the serial connection promising
3817 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3819 warning (_("The remote protocol may be unreliable over UDP.\n"
3820 "Some events may be lost, rendering further debugging "
3825 return serial_open (name);
3828 /* Inform the target of our permission settings. The permission flags
3829 work without this, but if the target knows the settings, it can do
3830 a couple things. First, it can add its own check, to catch cases
3831 that somehow manage to get by the permissions checks in target
3832 methods. Second, if the target is wired to disallow particular
3833 settings (for instance, a system in the field that is not set up to
3834 be able to stop at a breakpoint), it can object to any unavailable
3838 remote_set_permissions (struct target_ops *self)
3840 struct remote_state *rs = get_remote_state ();
3842 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3843 "WriteReg:%x;WriteMem:%x;"
3844 "InsertBreak:%x;InsertTrace:%x;"
3845 "InsertFastTrace:%x;Stop:%x",
3846 may_write_registers, may_write_memory,
3847 may_insert_breakpoints, may_insert_tracepoints,
3848 may_insert_fast_tracepoints, may_stop);
3850 getpkt (&rs->buf, &rs->buf_size, 0);
3852 /* If the target didn't like the packet, warn the user. Do not try
3853 to undo the user's settings, that would just be maddening. */
3854 if (strcmp (rs->buf, "OK") != 0)
3855 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3858 /* This type describes each known response to the qSupported
3860 struct protocol_feature
3862 /* The name of this protocol feature. */
3865 /* The default for this protocol feature. */
3866 enum packet_support default_support;
3868 /* The function to call when this feature is reported, or after
3869 qSupported processing if the feature is not supported.
3870 The first argument points to this structure. The second
3871 argument indicates whether the packet requested support be
3872 enabled, disabled, or probed (or the default, if this function
3873 is being called at the end of processing and this feature was
3874 not reported). The third argument may be NULL; if not NULL, it
3875 is a NUL-terminated string taken from the packet following
3876 this feature's name and an equals sign. */
3877 void (*func) (const struct protocol_feature *, enum packet_support,
3880 /* The corresponding packet for this feature. Only used if
3881 FUNC is remote_supported_packet. */
3886 remote_supported_packet (const struct protocol_feature *feature,
3887 enum packet_support support,
3888 const char *argument)
3892 warning (_("Remote qSupported response supplied an unexpected value for"
3893 " \"%s\"."), feature->name);
3897 remote_protocol_packets[feature->packet].support = support;
3901 remote_packet_size (const struct protocol_feature *feature,
3902 enum packet_support support, const char *value)
3904 struct remote_state *rs = get_remote_state ();
3909 if (support != PACKET_ENABLE)
3912 if (value == NULL || *value == '\0')
3914 warning (_("Remote target reported \"%s\" without a size."),
3920 packet_size = strtol (value, &value_end, 16);
3921 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3923 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3924 feature->name, value);
3928 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3930 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3931 packet_size, MAX_REMOTE_PACKET_SIZE);
3932 packet_size = MAX_REMOTE_PACKET_SIZE;
3935 /* Record the new maximum packet size. */
3936 rs->explicit_packet_size = packet_size;
3939 static const struct protocol_feature remote_protocol_features[] = {
3940 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3941 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3942 PACKET_qXfer_auxv },
3943 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3944 PACKET_qXfer_features },
3945 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3946 PACKET_qXfer_libraries },
3947 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3948 PACKET_qXfer_libraries_svr4 },
3949 { "augmented-libraries-svr4-read", PACKET_DISABLE,
3950 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
3951 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3952 PACKET_qXfer_memory_map },
3953 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3954 PACKET_qXfer_spu_read },
3955 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3956 PACKET_qXfer_spu_write },
3957 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3958 PACKET_qXfer_osdata },
3959 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3960 PACKET_qXfer_threads },
3961 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3962 PACKET_qXfer_traceframe_info },
3963 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3964 PACKET_QPassSignals },
3965 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3966 PACKET_QProgramSignals },
3967 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3968 PACKET_QStartNoAckMode },
3969 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
3970 PACKET_multiprocess_feature },
3971 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
3972 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3973 PACKET_qXfer_siginfo_read },
3974 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3975 PACKET_qXfer_siginfo_write },
3976 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
3977 PACKET_ConditionalTracepoints },
3978 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3979 PACKET_ConditionalBreakpoints },
3980 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
3981 PACKET_BreakpointCommands },
3982 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
3983 PACKET_FastTracepoints },
3984 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
3985 PACKET_StaticTracepoints },
3986 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
3987 PACKET_InstallInTrace},
3988 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
3989 PACKET_DisconnectedTracing_feature },
3990 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
3992 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
3994 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
3995 PACKET_TracepointSource },
3996 { "QAllow", PACKET_DISABLE, remote_supported_packet,
3998 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
3999 PACKET_EnableDisableTracepoints_feature },
4000 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4001 PACKET_qXfer_fdpic },
4002 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4004 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4005 PACKET_QDisableRandomization },
4006 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4007 { "QTBuffer:size", PACKET_DISABLE,
4008 remote_supported_packet, PACKET_QTBuffer_size},
4009 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4010 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4011 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4012 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4013 PACKET_qXfer_btrace }
4016 static char *remote_support_xml;
4018 /* Register string appended to "xmlRegisters=" in qSupported query. */
4021 register_remote_support_xml (const char *xml)
4023 #if defined(HAVE_LIBEXPAT)
4024 if (remote_support_xml == NULL)
4025 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4028 char *copy = xstrdup (remote_support_xml + 13);
4029 char *p = strtok (copy, ",");
4033 if (strcmp (p, xml) == 0)
4040 while ((p = strtok (NULL, ",")) != NULL);
4043 remote_support_xml = reconcat (remote_support_xml,
4044 remote_support_xml, ",", xml,
4051 remote_query_supported_append (char *msg, const char *append)
4054 return reconcat (msg, msg, ";", append, (char *) NULL);
4056 return xstrdup (append);
4060 remote_query_supported (void)
4062 struct remote_state *rs = get_remote_state ();
4065 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4067 /* The packet support flags are handled differently for this packet
4068 than for most others. We treat an error, a disabled packet, and
4069 an empty response identically: any features which must be reported
4070 to be used will be automatically disabled. An empty buffer
4071 accomplishes this, since that is also the representation for a list
4072 containing no features. */
4075 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4078 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4080 q = remote_query_supported_append (q, "multiprocess+");
4082 if (remote_support_xml)
4083 q = remote_query_supported_append (q, remote_support_xml);
4085 q = remote_query_supported_append (q, "qRelocInsn+");
4087 q = reconcat (q, "qSupported:", q, (char *) NULL);
4090 do_cleanups (old_chain);
4092 getpkt (&rs->buf, &rs->buf_size, 0);
4094 /* If an error occured, warn, but do not return - just reset the
4095 buffer to empty and go on to disable features. */
4096 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4099 warning (_("Remote failure reply: %s"), rs->buf);
4104 memset (seen, 0, sizeof (seen));
4109 enum packet_support is_supported;
4110 char *p, *end, *name_end, *value;
4112 /* First separate out this item from the rest of the packet. If
4113 there's another item after this, we overwrite the separator
4114 (terminated strings are much easier to work with). */
4116 end = strchr (p, ';');
4119 end = p + strlen (p);
4129 warning (_("empty item in \"qSupported\" response"));
4134 name_end = strchr (p, '=');
4137 /* This is a name=value entry. */
4138 is_supported = PACKET_ENABLE;
4139 value = name_end + 1;
4148 is_supported = PACKET_ENABLE;
4152 is_supported = PACKET_DISABLE;
4156 is_supported = PACKET_SUPPORT_UNKNOWN;
4160 warning (_("unrecognized item \"%s\" "
4161 "in \"qSupported\" response"), p);
4167 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4168 if (strcmp (remote_protocol_features[i].name, p) == 0)
4170 const struct protocol_feature *feature;
4173 feature = &remote_protocol_features[i];
4174 feature->func (feature, is_supported, value);
4179 /* If we increased the packet size, make sure to increase the global
4180 buffer size also. We delay this until after parsing the entire
4181 qSupported packet, because this is the same buffer we were
4183 if (rs->buf_size < rs->explicit_packet_size)
4185 rs->buf_size = rs->explicit_packet_size;
4186 rs->buf = xrealloc (rs->buf, rs->buf_size);
4189 /* Handle the defaults for unmentioned features. */
4190 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4193 const struct protocol_feature *feature;
4195 feature = &remote_protocol_features[i];
4196 feature->func (feature, feature->default_support, NULL);
4200 /* Remove any of the remote.c targets from target stack. Upper targets depend
4201 on it so remove them first. */
4204 remote_unpush_target (void)
4206 pop_all_targets_above (process_stratum - 1);
4210 remote_open_1 (const char *name, int from_tty,
4211 struct target_ops *target, int extended_p)
4213 struct remote_state *rs = get_remote_state ();
4216 error (_("To open a remote debug connection, you need to specify what\n"
4217 "serial device is attached to the remote system\n"
4218 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4220 /* See FIXME above. */
4221 if (!target_async_permitted)
4222 wait_forever_enabled_p = 1;
4224 /* If we're connected to a running target, target_preopen will kill it.
4225 Ask this question first, before target_preopen has a chance to kill
4227 if (rs->remote_desc != NULL && !have_inferiors ())
4230 && !query (_("Already connected to a remote target. Disconnect? ")))
4231 error (_("Still connected."));
4234 /* Here the possibly existing remote target gets unpushed. */
4235 target_preopen (from_tty);
4237 /* Make sure we send the passed signals list the next time we resume. */
4238 xfree (rs->last_pass_packet);
4239 rs->last_pass_packet = NULL;
4241 /* Make sure we send the program signals list the next time we
4243 xfree (rs->last_program_signals_packet);
4244 rs->last_program_signals_packet = NULL;
4246 remote_fileio_reset ();
4247 reopen_exec_file ();
4250 rs->remote_desc = remote_serial_open (name);
4251 if (!rs->remote_desc)
4252 perror_with_name (name);
4254 if (baud_rate != -1)
4256 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4258 /* The requested speed could not be set. Error out to
4259 top level after closing remote_desc. Take care to
4260 set remote_desc to NULL to avoid closing remote_desc
4262 serial_close (rs->remote_desc);
4263 rs->remote_desc = NULL;
4264 perror_with_name (name);
4268 serial_raw (rs->remote_desc);
4270 /* If there is something sitting in the buffer we might take it as a
4271 response to a command, which would be bad. */
4272 serial_flush_input (rs->remote_desc);
4276 puts_filtered ("Remote debugging using ");
4277 puts_filtered (name);
4278 puts_filtered ("\n");
4280 push_target (target); /* Switch to using remote target now. */
4282 /* Register extra event sources in the event loop. */
4283 remote_async_inferior_event_token
4284 = create_async_event_handler (remote_async_inferior_event_handler,
4286 rs->notif_state = remote_notif_state_allocate ();
4288 /* Reset the target state; these things will be queried either by
4289 remote_query_supported or as they are needed. */
4290 reset_all_packet_configs_support ();
4291 rs->cached_wait_status = 0;
4292 rs->explicit_packet_size = 0;
4294 rs->extended = extended_p;
4295 rs->waiting_for_stop_reply = 0;
4296 rs->ctrlc_pending_p = 0;
4298 rs->general_thread = not_sent_ptid;
4299 rs->continue_thread = not_sent_ptid;
4300 rs->remote_traceframe_number = -1;
4302 /* Probe for ability to use "ThreadInfo" query, as required. */
4303 rs->use_threadinfo_query = 1;
4304 rs->use_threadextra_query = 1;
4306 if (target_async_permitted)
4308 /* With this target we start out by owning the terminal. */
4309 remote_async_terminal_ours_p = 1;
4311 /* FIXME: cagney/1999-09-23: During the initial connection it is
4312 assumed that the target is already ready and able to respond to
4313 requests. Unfortunately remote_start_remote() eventually calls
4314 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4315 around this. Eventually a mechanism that allows
4316 wait_for_inferior() to expect/get timeouts will be
4318 wait_forever_enabled_p = 0;
4321 /* First delete any symbols previously loaded from shared libraries. */
4322 no_shared_libraries (NULL, 0);
4325 init_thread_list ();
4327 /* Start the remote connection. If error() or QUIT, discard this
4328 target (we'd otherwise be in an inconsistent state) and then
4329 propogate the error on up the exception chain. This ensures that
4330 the caller doesn't stumble along blindly assuming that the
4331 function succeeded. The CLI doesn't have this problem but other
4332 UI's, such as MI do.
4334 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4335 this function should return an error indication letting the
4336 caller restore the previous state. Unfortunately the command
4337 ``target remote'' is directly wired to this function making that
4338 impossible. On a positive note, the CLI side of this problem has
4339 been fixed - the function set_cmd_context() makes it possible for
4340 all the ``target ....'' commands to share a common callback
4341 function. See cli-dump.c. */
4343 volatile struct gdb_exception ex;
4345 TRY_CATCH (ex, RETURN_MASK_ALL)
4347 remote_start_remote (from_tty, target, extended_p);
4351 /* Pop the partially set up target - unless something else did
4352 already before throwing the exception. */
4353 if (rs->remote_desc != NULL)
4354 remote_unpush_target ();
4355 if (target_async_permitted)
4356 wait_forever_enabled_p = 1;
4357 throw_exception (ex);
4361 if (target_async_permitted)
4362 wait_forever_enabled_p = 1;
4365 /* This takes a program previously attached to and detaches it. After
4366 this is done, GDB can be used to debug some other program. We
4367 better not have left any breakpoints in the target program or it'll
4368 die when it hits one. */
4371 remote_detach_1 (const char *args, int from_tty, int extended)
4373 int pid = ptid_get_pid (inferior_ptid);
4374 struct remote_state *rs = get_remote_state ();
4377 error (_("Argument given to \"detach\" when remotely debugging."));
4379 if (!target_has_execution)
4380 error (_("No process to detach from."));
4384 char *exec_file = get_exec_file (0);
4385 if (exec_file == NULL)
4387 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4388 target_pid_to_str (pid_to_ptid (pid)));
4389 gdb_flush (gdb_stdout);
4392 /* Tell the remote target to detach. */
4393 if (remote_multi_process_p (rs))
4394 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4396 strcpy (rs->buf, "D");
4399 getpkt (&rs->buf, &rs->buf_size, 0);
4401 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4403 else if (rs->buf[0] == '\0')
4404 error (_("Remote doesn't know how to detach"));
4406 error (_("Can't detach process."));
4408 if (from_tty && !extended)
4409 puts_filtered (_("Ending remote debugging.\n"));
4411 target_mourn_inferior ();
4415 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4417 remote_detach_1 (args, from_tty, 0);
4421 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4423 remote_detach_1 (args, from_tty, 1);
4426 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4429 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4432 error (_("Argument given to \"disconnect\" when remotely debugging."));
4434 /* Make sure we unpush even the extended remote targets; mourn
4435 won't do it. So call remote_mourn_1 directly instead of
4436 target_mourn_inferior. */
4437 remote_mourn_1 (target);
4440 puts_filtered ("Ending remote debugging.\n");
4443 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4444 be chatty about it. */
4447 extended_remote_attach_1 (struct target_ops *target, const char *args,
4450 struct remote_state *rs = get_remote_state ();
4452 char *wait_status = NULL;
4454 pid = parse_pid_to_attach (args);
4456 /* Remote PID can be freely equal to getpid, do not check it here the same
4457 way as in other targets. */
4459 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4460 error (_("This target does not support attaching to a process"));
4464 char *exec_file = get_exec_file (0);
4467 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4468 target_pid_to_str (pid_to_ptid (pid)));
4470 printf_unfiltered (_("Attaching to %s\n"),
4471 target_pid_to_str (pid_to_ptid (pid)));
4473 gdb_flush (gdb_stdout);
4476 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4478 getpkt (&rs->buf, &rs->buf_size, 0);
4480 switch (packet_ok (rs->buf,
4481 &remote_protocol_packets[PACKET_vAttach]))
4486 /* Save the reply for later. */
4487 wait_status = alloca (strlen (rs->buf) + 1);
4488 strcpy (wait_status, rs->buf);
4490 else if (strcmp (rs->buf, "OK") != 0)
4491 error (_("Attaching to %s failed with: %s"),
4492 target_pid_to_str (pid_to_ptid (pid)),
4495 case PACKET_UNKNOWN:
4496 error (_("This target does not support attaching to a process"));
4498 error (_("Attaching to %s failed"),
4499 target_pid_to_str (pid_to_ptid (pid)));
4502 set_current_inferior (remote_add_inferior (0, pid, 1));
4504 inferior_ptid = pid_to_ptid (pid);
4508 struct thread_info *thread;
4510 /* Get list of threads. */
4511 remote_update_thread_list (target);
4513 thread = first_thread_of_process (pid);
4515 inferior_ptid = thread->ptid;
4517 inferior_ptid = pid_to_ptid (pid);
4519 /* Invalidate our notion of the remote current thread. */
4520 record_currthread (rs, minus_one_ptid);
4524 /* Now, if we have thread information, update inferior_ptid. */
4525 inferior_ptid = remote_current_thread (inferior_ptid);
4527 /* Add the main thread to the thread list. */
4528 add_thread_silent (inferior_ptid);
4531 /* Next, if the target can specify a description, read it. We do
4532 this before anything involving memory or registers. */
4533 target_find_description ();
4537 /* Use the previously fetched status. */
4538 gdb_assert (wait_status != NULL);
4540 if (target_can_async_p ())
4542 struct notif_event *reply
4543 = remote_notif_parse (¬if_client_stop, wait_status);
4545 push_stop_reply ((struct stop_reply *) reply);
4547 target_async (inferior_event_handler, 0);
4551 gdb_assert (wait_status != NULL);
4552 strcpy (rs->buf, wait_status);
4553 rs->cached_wait_status = 1;
4557 gdb_assert (wait_status == NULL);
4561 extended_remote_attach (struct target_ops *ops, const char *args, int from_tty)
4563 extended_remote_attach_1 (ops, args, from_tty);
4566 /* Implementation of the to_post_attach method. */
4569 extended_remote_post_attach (struct target_ops *ops, int pid)
4571 /* In certain cases GDB might not have had the chance to start
4572 symbol lookup up until now. This could happen if the debugged
4573 binary is not using shared libraries, the vsyscall page is not
4574 present (on Linux) and the binary itself hadn't changed since the
4575 debugging process was started. */
4576 if (symfile_objfile != NULL)
4577 remote_check_symbols();
4581 /* Check for the availability of vCont. This function should also check
4585 remote_vcont_probe (struct remote_state *rs)
4589 strcpy (rs->buf, "vCont?");
4591 getpkt (&rs->buf, &rs->buf_size, 0);
4594 /* Make sure that the features we assume are supported. */
4595 if (strncmp (buf, "vCont", 5) == 0)
4598 int support_s, support_S, support_c, support_C;
4604 rs->supports_vCont.t = 0;
4605 rs->supports_vCont.r = 0;
4606 while (p && *p == ';')
4609 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4611 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4613 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4615 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4617 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4618 rs->supports_vCont.t = 1;
4619 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4620 rs->supports_vCont.r = 1;
4622 p = strchr (p, ';');
4625 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4626 BUF will make packet_ok disable the packet. */
4627 if (!support_s || !support_S || !support_c || !support_C)
4631 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4634 /* Helper function for building "vCont" resumptions. Write a
4635 resumption to P. ENDP points to one-passed-the-end of the buffer
4636 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4637 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4638 resumed thread should be single-stepped and/or signalled. If PTID
4639 equals minus_one_ptid, then all threads are resumed; if PTID
4640 represents a process, then all threads of the process are resumed;
4641 the thread to be stepped and/or signalled is given in the global
4645 append_resumption (char *p, char *endp,
4646 ptid_t ptid, int step, enum gdb_signal siggnal)
4648 struct remote_state *rs = get_remote_state ();
4650 if (step && siggnal != GDB_SIGNAL_0)
4651 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4653 /* GDB is willing to range step. */
4654 && use_range_stepping
4655 /* Target supports range stepping. */
4656 && rs->supports_vCont.r
4657 /* We don't currently support range stepping multiple
4658 threads with a wildcard (though the protocol allows it,
4659 so stubs shouldn't make an active effort to forbid
4661 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4663 struct thread_info *tp;
4665 if (ptid_equal (ptid, minus_one_ptid))
4667 /* If we don't know about the target thread's tid, then
4668 we're resuming magic_null_ptid (see caller). */
4669 tp = find_thread_ptid (magic_null_ptid);
4672 tp = find_thread_ptid (ptid);
4673 gdb_assert (tp != NULL);
4675 if (tp->control.may_range_step)
4677 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4679 p += xsnprintf (p, endp - p, ";r%s,%s",
4680 phex_nz (tp->control.step_range_start,
4682 phex_nz (tp->control.step_range_end,
4686 p += xsnprintf (p, endp - p, ";s");
4689 p += xsnprintf (p, endp - p, ";s");
4690 else if (siggnal != GDB_SIGNAL_0)
4691 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4693 p += xsnprintf (p, endp - p, ";c");
4695 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4699 /* All (-1) threads of process. */
4700 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
4702 p += xsnprintf (p, endp - p, ":");
4703 p = write_ptid (p, endp, nptid);
4705 else if (!ptid_equal (ptid, minus_one_ptid))
4707 p += xsnprintf (p, endp - p, ":");
4708 p = write_ptid (p, endp, ptid);
4714 /* Append a vCont continue-with-signal action for threads that have a
4715 non-zero stop signal. */
4718 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4720 struct thread_info *thread;
4722 ALL_NON_EXITED_THREADS (thread)
4723 if (ptid_match (thread->ptid, ptid)
4724 && !ptid_equal (inferior_ptid, thread->ptid)
4725 && thread->suspend.stop_signal != GDB_SIGNAL_0)
4727 p = append_resumption (p, endp, thread->ptid,
4728 0, thread->suspend.stop_signal);
4729 thread->suspend.stop_signal = GDB_SIGNAL_0;
4735 /* Resume the remote inferior by using a "vCont" packet. The thread
4736 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4737 resumed thread should be single-stepped and/or signalled. If PTID
4738 equals minus_one_ptid, then all threads are resumed; the thread to
4739 be stepped and/or signalled is given in the global INFERIOR_PTID.
4740 This function returns non-zero iff it resumes the inferior.
4742 This function issues a strict subset of all possible vCont commands at the
4746 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4748 struct remote_state *rs = get_remote_state ();
4752 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
4753 remote_vcont_probe (rs);
4755 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
4759 endp = rs->buf + get_remote_packet_size ();
4761 /* If we could generate a wider range of packets, we'd have to worry
4762 about overflowing BUF. Should there be a generic
4763 "multi-part-packet" packet? */
4765 p += xsnprintf (p, endp - p, "vCont");
4767 if (ptid_equal (ptid, magic_null_ptid))
4769 /* MAGIC_NULL_PTID means that we don't have any active threads,
4770 so we don't have any TID numbers the inferior will
4771 understand. Make sure to only send forms that do not specify
4773 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4775 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4777 /* Resume all threads (of all processes, or of a single
4778 process), with preference for INFERIOR_PTID. This assumes
4779 inferior_ptid belongs to the set of all threads we are about
4781 if (step || siggnal != GDB_SIGNAL_0)
4783 /* Step inferior_ptid, with or without signal. */
4784 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4787 /* Also pass down any pending signaled resumption for other
4788 threads not the current. */
4789 p = append_pending_thread_resumptions (p, endp, ptid);
4791 /* And continue others without a signal. */
4792 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4796 /* Scheduler locking; resume only PTID. */
4797 append_resumption (p, endp, ptid, step, siggnal);
4800 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4805 /* In non-stop, the stub replies to vCont with "OK". The stop
4806 reply will be reported asynchronously by means of a `%Stop'
4808 getpkt (&rs->buf, &rs->buf_size, 0);
4809 if (strcmp (rs->buf, "OK") != 0)
4810 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4816 /* Tell the remote machine to resume. */
4819 remote_resume (struct target_ops *ops,
4820 ptid_t ptid, int step, enum gdb_signal siggnal)
4822 struct remote_state *rs = get_remote_state ();
4825 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4826 (explained in remote-notif.c:handle_notification) so
4827 remote_notif_process is not called. We need find a place where
4828 it is safe to start a 'vNotif' sequence. It is good to do it
4829 before resuming inferior, because inferior was stopped and no RSP
4830 traffic at that moment. */
4832 remote_notif_process (rs->notif_state, ¬if_client_stop);
4834 rs->last_sent_signal = siggnal;
4835 rs->last_sent_step = step;
4837 /* The vCont packet doesn't need to specify threads via Hc. */
4838 /* No reverse support (yet) for vCont. */
4839 if (execution_direction != EXEC_REVERSE)
4840 if (remote_vcont_resume (ptid, step, siggnal))
4843 /* All other supported resume packets do use Hc, so set the continue
4845 if (ptid_equal (ptid, minus_one_ptid))
4846 set_continue_thread (any_thread_ptid);
4848 set_continue_thread (ptid);
4851 if (execution_direction == EXEC_REVERSE)
4853 /* We don't pass signals to the target in reverse exec mode. */
4854 if (info_verbose && siggnal != GDB_SIGNAL_0)
4855 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4858 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
4859 error (_("Remote reverse-step not supported."));
4860 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
4861 error (_("Remote reverse-continue not supported."));
4863 strcpy (buf, step ? "bs" : "bc");
4865 else if (siggnal != GDB_SIGNAL_0)
4867 buf[0] = step ? 'S' : 'C';
4868 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4869 buf[2] = tohex (((int) siggnal) & 0xf);
4873 strcpy (buf, step ? "s" : "c");
4878 /* We are about to start executing the inferior, let's register it
4879 with the event loop. NOTE: this is the one place where all the
4880 execution commands end up. We could alternatively do this in each
4881 of the execution commands in infcmd.c. */
4882 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4883 into infcmd.c in order to allow inferior function calls to work
4884 NOT asynchronously. */
4885 if (target_can_async_p ())
4886 target_async (inferior_event_handler, 0);
4888 /* We've just told the target to resume. The remote server will
4889 wait for the inferior to stop, and then send a stop reply. In
4890 the mean time, we can't start another command/query ourselves
4891 because the stub wouldn't be ready to process it. This applies
4892 only to the base all-stop protocol, however. In non-stop (which
4893 only supports vCont), the stub replies with an "OK", and is
4894 immediate able to process further serial input. */
4896 rs->waiting_for_stop_reply = 1;
4900 /* Set up the signal handler for SIGINT, while the target is
4901 executing, ovewriting the 'regular' SIGINT signal handler. */
4903 async_initialize_sigint_signal_handler (void)
4905 signal (SIGINT, async_handle_remote_sigint);
4908 /* Signal handler for SIGINT, while the target is executing. */
4910 async_handle_remote_sigint (int sig)
4912 signal (sig, async_handle_remote_sigint_twice);
4913 /* Note we need to go through gdb_call_async_signal_handler in order
4914 to wake up the event loop on Windows. */
4915 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
4918 /* Signal handler for SIGINT, installed after SIGINT has already been
4919 sent once. It will take effect the second time that the user sends
4922 async_handle_remote_sigint_twice (int sig)
4924 signal (sig, async_handle_remote_sigint);
4925 /* See note in async_handle_remote_sigint. */
4926 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
4929 /* Perform the real interruption of the target execution, in response
4932 async_remote_interrupt (gdb_client_data arg)
4935 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
4937 target_stop (inferior_ptid);
4940 /* Perform interrupt, if the first attempt did not succeed. Just give
4941 up on the target alltogether. */
4943 async_remote_interrupt_twice (gdb_client_data arg)
4946 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
4951 /* Reinstall the usual SIGINT handlers, after the target has
4954 async_cleanup_sigint_signal_handler (void *dummy)
4956 signal (SIGINT, handle_sigint);
4959 /* Send ^C to target to halt it. Target will respond, and send us a
4961 static void (*ofunc) (int);
4963 /* The command line interface's stop routine. This function is installed
4964 as a signal handler for SIGINT. The first time a user requests a
4965 stop, we call remote_stop to send a break or ^C. If there is no
4966 response from the target (it didn't stop when the user requested it),
4967 we ask the user if he'd like to detach from the target. */
4969 sync_remote_interrupt (int signo)
4971 /* If this doesn't work, try more severe steps. */
4972 signal (signo, sync_remote_interrupt_twice);
4974 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
4977 /* The user typed ^C twice. */
4980 sync_remote_interrupt_twice (int signo)
4982 signal (signo, ofunc);
4983 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
4984 signal (signo, sync_remote_interrupt);
4987 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
4988 thread, all threads of a remote process, or all threads of all
4992 remote_stop_ns (ptid_t ptid)
4994 struct remote_state *rs = get_remote_state ();
4996 char *endp = rs->buf + get_remote_packet_size ();
4998 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
4999 remote_vcont_probe (rs);
5001 if (!rs->supports_vCont.t)
5002 error (_("Remote server does not support stopping threads"));
5004 if (ptid_equal (ptid, minus_one_ptid)
5005 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5006 p += xsnprintf (p, endp - p, "vCont;t");
5011 p += xsnprintf (p, endp - p, "vCont;t:");
5013 if (ptid_is_pid (ptid))
5014 /* All (-1) threads of process. */
5015 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5018 /* Small optimization: if we already have a stop reply for
5019 this thread, no use in telling the stub we want this
5021 if (peek_stop_reply (ptid))
5027 write_ptid (p, endp, nptid);
5030 /* In non-stop, we get an immediate OK reply. The stop reply will
5031 come in asynchronously by notification. */
5033 getpkt (&rs->buf, &rs->buf_size, 0);
5034 if (strcmp (rs->buf, "OK") != 0)
5035 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5038 /* All-stop version of target_stop. Sends a break or a ^C to stop the
5039 remote target. It is undefined which thread of which process
5040 reports the stop. */
5043 remote_stop_as (ptid_t ptid)
5045 struct remote_state *rs = get_remote_state ();
5047 rs->ctrlc_pending_p = 1;
5049 /* If the inferior is stopped already, but the core didn't know
5050 about it yet, just ignore the request. The cached wait status
5051 will be collected in remote_wait. */
5052 if (rs->cached_wait_status)
5055 /* Send interrupt_sequence to remote target. */
5056 send_interrupt_sequence ();
5059 /* This is the generic stop called via the target vector. When a target
5060 interrupt is requested, either by the command line or the GUI, we
5061 will eventually end up here. */
5064 remote_stop (struct target_ops *self, ptid_t ptid)
5067 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5070 remote_stop_ns (ptid);
5072 remote_stop_as (ptid);
5075 /* Ask the user what to do when an interrupt is received. */
5078 interrupt_query (void)
5080 target_terminal_ours ();
5082 if (target_can_async_p ())
5084 signal (SIGINT, handle_sigint);
5089 if (query (_("Interrupted while waiting for the program.\n\
5090 Give up (and stop debugging it)? ")))
5092 remote_unpush_target ();
5097 target_terminal_inferior ();
5100 /* Enable/disable target terminal ownership. Most targets can use
5101 terminal groups to control terminal ownership. Remote targets are
5102 different in that explicit transfer of ownership to/from GDB/target
5106 remote_terminal_inferior (struct target_ops *self)
5108 if (!target_async_permitted)
5109 /* Nothing to do. */
5112 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5113 idempotent. The event-loop GDB talking to an asynchronous target
5114 with a synchronous command calls this function from both
5115 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5116 transfer the terminal to the target when it shouldn't this guard
5118 if (!remote_async_terminal_ours_p)
5120 delete_file_handler (input_fd);
5121 remote_async_terminal_ours_p = 0;
5122 async_initialize_sigint_signal_handler ();
5123 /* NOTE: At this point we could also register our selves as the
5124 recipient of all input. Any characters typed could then be
5125 passed on down to the target. */
5129 remote_terminal_ours (struct target_ops *self)
5131 if (!target_async_permitted)
5132 /* Nothing to do. */
5135 /* See FIXME in remote_terminal_inferior. */
5136 if (remote_async_terminal_ours_p)
5138 async_cleanup_sigint_signal_handler (NULL);
5139 add_file_handler (input_fd, stdin_event_handler, 0);
5140 remote_async_terminal_ours_p = 1;
5144 remote_console_output (char *msg)
5148 for (p = msg; p[0] && p[1]; p += 2)
5151 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5155 fputs_unfiltered (tb, gdb_stdtarg);
5157 gdb_flush (gdb_stdtarg);
5160 typedef struct cached_reg
5163 gdb_byte data[MAX_REGISTER_SIZE];
5166 DEF_VEC_O(cached_reg_t);
5168 typedef struct stop_reply
5170 struct notif_event base;
5172 /* The identifier of the thread about this event */
5175 /* The remote state this event is associated with. When the remote
5176 connection, represented by a remote_state object, is closed,
5177 all the associated stop_reply events should be released. */
5178 struct remote_state *rs;
5180 struct target_waitstatus ws;
5182 /* Expedited registers. This makes remote debugging a bit more
5183 efficient for those targets that provide critical registers as
5184 part of their normal status mechanism (as another roundtrip to
5185 fetch them is avoided). */
5186 VEC(cached_reg_t) *regcache;
5188 int stopped_by_watchpoint_p;
5189 CORE_ADDR watch_data_address;
5194 DECLARE_QUEUE_P (stop_reply_p);
5195 DEFINE_QUEUE_P (stop_reply_p);
5196 /* The list of already fetched and acknowledged stop events. This
5197 queue is used for notification Stop, and other notifications
5198 don't need queue for their events, because the notification events
5199 of Stop can't be consumed immediately, so that events should be
5200 queued first, and be consumed by remote_wait_{ns,as} one per
5201 time. Other notifications can consume their events immediately,
5202 so queue is not needed for them. */
5203 static QUEUE (stop_reply_p) *stop_reply_queue;
5206 stop_reply_xfree (struct stop_reply *r)
5208 notif_event_xfree ((struct notif_event *) r);
5212 remote_notif_stop_parse (struct notif_client *self, char *buf,
5213 struct notif_event *event)
5215 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5219 remote_notif_stop_ack (struct notif_client *self, char *buf,
5220 struct notif_event *event)
5222 struct stop_reply *stop_reply = (struct stop_reply *) event;
5225 putpkt ((char *) self->ack_command);
5227 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5228 /* We got an unknown stop reply. */
5229 error (_("Unknown stop reply"));
5231 push_stop_reply (stop_reply);
5235 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5237 /* We can't get pending events in remote_notif_process for
5238 notification stop, and we have to do this in remote_wait_ns
5239 instead. If we fetch all queued events from stub, remote stub
5240 may exit and we have no chance to process them back in
5242 mark_async_event_handler (remote_async_inferior_event_token);
5247 stop_reply_dtr (struct notif_event *event)
5249 struct stop_reply *r = (struct stop_reply *) event;
5251 VEC_free (cached_reg_t, r->regcache);
5254 static struct notif_event *
5255 remote_notif_stop_alloc_reply (void)
5257 struct notif_event *r
5258 = (struct notif_event *) XNEW (struct stop_reply);
5260 r->dtr = stop_reply_dtr;
5265 /* A client of notification Stop. */
5267 struct notif_client notif_client_stop =
5271 remote_notif_stop_parse,
5272 remote_notif_stop_ack,
5273 remote_notif_stop_can_get_pending_events,
5274 remote_notif_stop_alloc_reply,
5278 /* A parameter to pass data in and out. */
5280 struct queue_iter_param
5283 struct stop_reply *output;
5286 /* Remove stop replies in the queue if its pid is equal to the given
5290 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5291 QUEUE_ITER (stop_reply_p) *iter,
5295 struct queue_iter_param *param = data;
5296 struct inferior *inf = param->input;
5298 if (ptid_get_pid (event->ptid) == inf->pid)
5300 stop_reply_xfree (event);
5301 QUEUE_remove_elem (stop_reply_p, q, iter);
5307 /* Discard all pending stop replies of inferior INF. */
5310 discard_pending_stop_replies (struct inferior *inf)
5313 struct queue_iter_param param;
5314 struct stop_reply *reply;
5315 struct remote_state *rs = get_remote_state ();
5316 struct remote_notif_state *rns = rs->notif_state;
5318 /* This function can be notified when an inferior exists. When the
5319 target is not remote, the notification state is NULL. */
5320 if (rs->remote_desc == NULL)
5323 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5325 /* Discard the in-flight notification. */
5326 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5328 stop_reply_xfree (reply);
5329 rns->pending_event[notif_client_stop.id] = NULL;
5333 param.output = NULL;
5334 /* Discard the stop replies we have already pulled with
5336 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5337 remove_stop_reply_for_inferior, ¶m);
5340 /* If its remote state is equal to the given remote state,
5341 remove EVENT from the stop reply queue. */
5344 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5345 QUEUE_ITER (stop_reply_p) *iter,
5349 struct queue_iter_param *param = data;
5350 struct remote_state *rs = param->input;
5352 if (event->rs == rs)
5354 stop_reply_xfree (event);
5355 QUEUE_remove_elem (stop_reply_p, q, iter);
5361 /* Discard the stop replies for RS in stop_reply_queue. */
5364 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5366 struct queue_iter_param param;
5369 param.output = NULL;
5370 /* Discard the stop replies we have already pulled with
5372 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5373 remove_stop_reply_of_remote_state, ¶m);
5376 /* A parameter to pass data in and out. */
5379 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5380 QUEUE_ITER (stop_reply_p) *iter,
5384 struct queue_iter_param *param = data;
5385 ptid_t *ptid = param->input;
5387 if (ptid_match (event->ptid, *ptid))
5389 param->output = event;
5390 QUEUE_remove_elem (stop_reply_p, q, iter);
5397 /* Remove the first reply in 'stop_reply_queue' which matches
5400 static struct stop_reply *
5401 remote_notif_remove_queued_reply (ptid_t ptid)
5403 struct queue_iter_param param;
5405 param.input = &ptid;
5406 param.output = NULL;
5408 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5409 remote_notif_remove_once_on_match, ¶m);
5411 fprintf_unfiltered (gdb_stdlog,
5412 "notif: discard queued event: 'Stop' in %s\n",
5413 target_pid_to_str (ptid));
5415 return param.output;
5418 /* Look for a queued stop reply belonging to PTID. If one is found,
5419 remove it from the queue, and return it. Returns NULL if none is
5420 found. If there are still queued events left to process, tell the
5421 event loop to get back to target_wait soon. */
5423 static struct stop_reply *
5424 queued_stop_reply (ptid_t ptid)
5426 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5428 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5429 /* There's still at least an event left. */
5430 mark_async_event_handler (remote_async_inferior_event_token);
5435 /* Push a fully parsed stop reply in the stop reply queue. Since we
5436 know that we now have at least one queued event left to pass to the
5437 core side, tell the event loop to get back to target_wait soon. */
5440 push_stop_reply (struct stop_reply *new_event)
5442 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5445 fprintf_unfiltered (gdb_stdlog,
5446 "notif: push 'Stop' %s to queue %d\n",
5447 target_pid_to_str (new_event->ptid),
5448 QUEUE_length (stop_reply_p,
5451 mark_async_event_handler (remote_async_inferior_event_token);
5455 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5456 QUEUE_ITER (stop_reply_p) *iter,
5457 struct stop_reply *event,
5460 ptid_t *ptid = data;
5462 return !(ptid_equal (*ptid, event->ptid)
5463 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5466 /* Returns true if we have a stop reply for PTID. */
5469 peek_stop_reply (ptid_t ptid)
5471 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5472 stop_reply_match_ptid_and_ws, &ptid);
5475 /* Parse the stop reply in BUF. Either the function succeeds, and the
5476 result is stored in EVENT, or throws an error. */
5479 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5481 struct remote_arch_state *rsa = get_remote_arch_state ();
5485 event->ptid = null_ptid;
5486 event->rs = get_remote_state ();
5487 event->ws.kind = TARGET_WAITKIND_IGNORE;
5488 event->ws.value.integer = 0;
5489 event->stopped_by_watchpoint_p = 0;
5490 event->regcache = NULL;
5495 case 'T': /* Status with PC, SP, FP, ... */
5496 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5497 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5499 n... = register number
5500 r... = register contents
5503 p = &buf[3]; /* after Txx */
5511 /* If the packet contains a register number, save it in
5512 pnum and set p1 to point to the character following it.
5513 Otherwise p1 points to p. */
5515 /* If this packet is an awatch packet, don't parse the 'a'
5516 as a register number. */
5518 if (strncmp (p, "awatch", strlen("awatch")) != 0
5519 && strncmp (p, "core", strlen ("core") != 0))
5521 /* Read the ``P'' register number. */
5522 pnum = strtol (p, &p_temp, 16);
5528 if (p1 == p) /* No register number present here. */
5530 p1 = strchr (p, ':');
5532 error (_("Malformed packet(a) (missing colon): %s\n\
5535 if (strncmp (p, "thread", p1 - p) == 0)
5536 event->ptid = read_ptid (++p1, &p);
5537 else if ((strncmp (p, "watch", p1 - p) == 0)
5538 || (strncmp (p, "rwatch", p1 - p) == 0)
5539 || (strncmp (p, "awatch", p1 - p) == 0))
5541 event->stopped_by_watchpoint_p = 1;
5542 p = unpack_varlen_hex (++p1, &addr);
5543 event->watch_data_address = (CORE_ADDR) addr;
5545 else if (strncmp (p, "library", p1 - p) == 0)
5549 while (*p_temp && *p_temp != ';')
5552 event->ws.kind = TARGET_WAITKIND_LOADED;
5555 else if (strncmp (p, "replaylog", p1 - p) == 0)
5557 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5558 /* p1 will indicate "begin" or "end", but it makes
5559 no difference for now, so ignore it. */
5560 p_temp = strchr (p1 + 1, ';');
5564 else if (strncmp (p, "core", p1 - p) == 0)
5568 p = unpack_varlen_hex (++p1, &c);
5573 /* Silently skip unknown optional info. */
5574 p_temp = strchr (p1 + 1, ';');
5581 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5582 cached_reg_t cached_reg;
5587 error (_("Malformed packet(b) (missing colon): %s\n\
5593 error (_("Remote sent bad register number %s: %s\n\
5595 hex_string (pnum), p, buf);
5597 cached_reg.num = reg->regnum;
5599 fieldsize = hex2bin (p, cached_reg.data,
5600 register_size (target_gdbarch (),
5603 if (fieldsize < register_size (target_gdbarch (),
5605 warning (_("Remote reply is too short: %s"), buf);
5607 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5611 error (_("Remote register badly formatted: %s\nhere: %s"),
5616 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5620 case 'S': /* Old style status, just signal only. */
5624 event->ws.kind = TARGET_WAITKIND_STOPPED;
5625 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5626 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5627 event->ws.value.sig = (enum gdb_signal) sig;
5629 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5632 case 'W': /* Target exited. */
5639 /* GDB used to accept only 2 hex chars here. Stubs should
5640 only send more if they detect GDB supports multi-process
5642 p = unpack_varlen_hex (&buf[1], &value);
5646 /* The remote process exited. */
5647 event->ws.kind = TARGET_WAITKIND_EXITED;
5648 event->ws.value.integer = value;
5652 /* The remote process exited with a signal. */
5653 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5654 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5655 event->ws.value.sig = (enum gdb_signal) value;
5657 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5660 /* If no process is specified, assume inferior_ptid. */
5661 pid = ptid_get_pid (inferior_ptid);
5670 else if (strncmp (p,
5671 "process:", sizeof ("process:") - 1) == 0)
5675 p += sizeof ("process:") - 1;
5676 unpack_varlen_hex (p, &upid);
5680 error (_("unknown stop reply packet: %s"), buf);
5683 error (_("unknown stop reply packet: %s"), buf);
5684 event->ptid = pid_to_ptid (pid);
5689 if (non_stop && ptid_equal (event->ptid, null_ptid))
5690 error (_("No process or thread specified in stop reply: %s"), buf);
5693 /* When the stub wants to tell GDB about a new notification reply, it
5694 sends a notification (%Stop, for example). Those can come it at
5695 any time, hence, we have to make sure that any pending
5696 putpkt/getpkt sequence we're making is finished, before querying
5697 the stub for more events with the corresponding ack command
5698 (vStopped, for example). E.g., if we started a vStopped sequence
5699 immediately upon receiving the notification, something like this
5707 1.6) <-- (registers reply to step #1.3)
5709 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5712 To solve this, whenever we parse a %Stop notification successfully,
5713 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5714 doing whatever we were doing:
5720 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5721 2.5) <-- (registers reply to step #2.3)
5723 Eventualy after step #2.5, we return to the event loop, which
5724 notices there's an event on the
5725 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5726 associated callback --- the function below. At this point, we're
5727 always safe to start a vStopped sequence. :
5730 2.7) <-- T05 thread:2
5736 remote_notif_get_pending_events (struct notif_client *nc)
5738 struct remote_state *rs = get_remote_state ();
5740 if (rs->notif_state->pending_event[nc->id] != NULL)
5743 fprintf_unfiltered (gdb_stdlog,
5744 "notif: process: '%s' ack pending event\n",
5748 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5749 rs->notif_state->pending_event[nc->id] = NULL;
5753 getpkt (&rs->buf, &rs->buf_size, 0);
5754 if (strcmp (rs->buf, "OK") == 0)
5757 remote_notif_ack (nc, rs->buf);
5763 fprintf_unfiltered (gdb_stdlog,
5764 "notif: process: '%s' no pending reply\n",
5769 /* Called when it is decided that STOP_REPLY holds the info of the
5770 event that is to be returned to the core. This function always
5771 destroys STOP_REPLY. */
5774 process_stop_reply (struct stop_reply *stop_reply,
5775 struct target_waitstatus *status)
5779 *status = stop_reply->ws;
5780 ptid = stop_reply->ptid;
5782 /* If no thread/process was reported by the stub, assume the current
5784 if (ptid_equal (ptid, null_ptid))
5785 ptid = inferior_ptid;
5787 if (status->kind != TARGET_WAITKIND_EXITED
5788 && status->kind != TARGET_WAITKIND_SIGNALLED)
5790 struct remote_state *rs = get_remote_state ();
5792 /* Expedited registers. */
5793 if (stop_reply->regcache)
5795 struct regcache *regcache
5796 = get_thread_arch_regcache (ptid, target_gdbarch ());
5801 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5803 regcache_raw_supply (regcache, reg->num, reg->data);
5804 VEC_free (cached_reg_t, stop_reply->regcache);
5807 rs->remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5808 rs->remote_watch_data_address = stop_reply->watch_data_address;
5810 remote_notice_new_inferior (ptid, 0);
5811 demand_private_info (ptid)->core = stop_reply->core;
5814 stop_reply_xfree (stop_reply);
5818 /* The non-stop mode version of target_wait. */
5821 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5823 struct remote_state *rs = get_remote_state ();
5824 struct stop_reply *stop_reply;
5828 /* If in non-stop mode, get out of getpkt even if a
5829 notification is received. */
5831 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5832 0 /* forever */, &is_notif);
5835 if (ret != -1 && !is_notif)
5838 case 'E': /* Error of some sort. */
5839 /* We're out of sync with the target now. Did it continue
5840 or not? We can't tell which thread it was in non-stop,
5841 so just ignore this. */
5842 warning (_("Remote failure reply: %s"), rs->buf);
5844 case 'O': /* Console output. */
5845 remote_console_output (rs->buf + 1);
5848 warning (_("Invalid remote reply: %s"), rs->buf);
5852 /* Acknowledge a pending stop reply that may have arrived in the
5854 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
5855 remote_notif_get_pending_events (¬if_client_stop);
5857 /* If indeed we noticed a stop reply, we're done. */
5858 stop_reply = queued_stop_reply (ptid);
5859 if (stop_reply != NULL)
5860 return process_stop_reply (stop_reply, status);
5862 /* Still no event. If we're just polling for an event, then
5863 return to the event loop. */
5864 if (options & TARGET_WNOHANG)
5866 status->kind = TARGET_WAITKIND_IGNORE;
5867 return minus_one_ptid;
5870 /* Otherwise do a blocking wait. */
5871 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5872 1 /* forever */, &is_notif);
5876 /* Wait until the remote machine stops, then return, storing status in
5877 STATUS just as `wait' would. */
5880 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5882 struct remote_state *rs = get_remote_state ();
5883 ptid_t event_ptid = null_ptid;
5885 struct stop_reply *stop_reply;
5889 status->kind = TARGET_WAITKIND_IGNORE;
5890 status->value.integer = 0;
5892 stop_reply = queued_stop_reply (ptid);
5893 if (stop_reply != NULL)
5894 return process_stop_reply (stop_reply, status);
5896 if (rs->cached_wait_status)
5897 /* Use the cached wait status, but only once. */
5898 rs->cached_wait_status = 0;
5904 if (!target_is_async_p ())
5906 ofunc = signal (SIGINT, sync_remote_interrupt);
5907 /* If the user hit C-c before this packet, or between packets,
5908 pretend that it was hit right here. */
5909 if (check_quit_flag ())
5912 sync_remote_interrupt (SIGINT);
5916 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5917 _never_ wait for ever -> test on target_is_async_p().
5918 However, before we do that we need to ensure that the caller
5919 knows how to take the target into/out of async mode. */
5920 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5921 wait_forever_enabled_p, &is_notif);
5923 if (!target_is_async_p ())
5924 signal (SIGINT, ofunc);
5926 /* GDB gets a notification. Return to core as this event is
5928 if (ret != -1 && is_notif)
5929 return minus_one_ptid;
5934 rs->remote_stopped_by_watchpoint_p = 0;
5936 /* We got something. */
5937 rs->waiting_for_stop_reply = 0;
5939 /* Assume that the target has acknowledged Ctrl-C unless we receive
5940 an 'F' or 'O' packet. */
5941 if (buf[0] != 'F' && buf[0] != 'O')
5942 rs->ctrlc_pending_p = 0;
5946 case 'E': /* Error of some sort. */
5947 /* We're out of sync with the target now. Did it continue or
5948 not? Not is more likely, so report a stop. */
5949 warning (_("Remote failure reply: %s"), buf);
5950 status->kind = TARGET_WAITKIND_STOPPED;
5951 status->value.sig = GDB_SIGNAL_0;
5953 case 'F': /* File-I/O request. */
5954 remote_fileio_request (buf, rs->ctrlc_pending_p);
5955 rs->ctrlc_pending_p = 0;
5957 case 'T': case 'S': case 'X': case 'W':
5959 struct stop_reply *stop_reply
5960 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
5963 event_ptid = process_stop_reply (stop_reply, status);
5966 case 'O': /* Console output. */
5967 remote_console_output (buf + 1);
5969 /* The target didn't really stop; keep waiting. */
5970 rs->waiting_for_stop_reply = 1;
5974 if (rs->last_sent_signal != GDB_SIGNAL_0)
5976 /* Zero length reply means that we tried 'S' or 'C' and the
5977 remote system doesn't support it. */
5978 target_terminal_ours_for_output ();
5980 ("Can't send signals to this remote system. %s not sent.\n",
5981 gdb_signal_to_name (rs->last_sent_signal));
5982 rs->last_sent_signal = GDB_SIGNAL_0;
5983 target_terminal_inferior ();
5985 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
5986 putpkt ((char *) buf);
5988 /* We just told the target to resume, so a stop reply is in
5990 rs->waiting_for_stop_reply = 1;
5993 /* else fallthrough */
5995 warning (_("Invalid remote reply: %s"), buf);
5997 rs->waiting_for_stop_reply = 1;
6001 if (status->kind == TARGET_WAITKIND_IGNORE)
6003 /* Nothing interesting happened. If we're doing a non-blocking
6004 poll, we're done. Otherwise, go back to waiting. */
6005 if (options & TARGET_WNOHANG)
6006 return minus_one_ptid;
6010 else if (status->kind != TARGET_WAITKIND_EXITED
6011 && status->kind != TARGET_WAITKIND_SIGNALLED)
6013 if (!ptid_equal (event_ptid, null_ptid))
6014 record_currthread (rs, event_ptid);
6016 event_ptid = inferior_ptid;
6019 /* A process exit. Invalidate our notion of current thread. */
6020 record_currthread (rs, minus_one_ptid);
6025 /* Wait until the remote machine stops, then return, storing status in
6026 STATUS just as `wait' would. */
6029 remote_wait (struct target_ops *ops,
6030 ptid_t ptid, struct target_waitstatus *status, int options)
6035 event_ptid = remote_wait_ns (ptid, status, options);
6037 event_ptid = remote_wait_as (ptid, status, options);
6039 if (target_can_async_p ())
6041 /* If there are are events left in the queue tell the event loop
6043 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6044 mark_async_event_handler (remote_async_inferior_event_token);
6050 /* Fetch a single register using a 'p' packet. */
6053 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6055 struct remote_state *rs = get_remote_state ();
6057 char regp[MAX_REGISTER_SIZE];
6060 if (packet_support (PACKET_p) == PACKET_DISABLE)
6063 if (reg->pnum == -1)
6068 p += hexnumstr (p, reg->pnum);
6071 getpkt (&rs->buf, &rs->buf_size, 0);
6075 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6079 case PACKET_UNKNOWN:
6082 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6083 gdbarch_register_name (get_regcache_arch (regcache),
6088 /* If this register is unfetchable, tell the regcache. */
6091 regcache_raw_supply (regcache, reg->regnum, NULL);
6095 /* Otherwise, parse and supply the value. */
6101 error (_("fetch_register_using_p: early buf termination"));
6103 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6106 regcache_raw_supply (regcache, reg->regnum, regp);
6110 /* Fetch the registers included in the target's 'g' packet. */
6113 send_g_packet (void)
6115 struct remote_state *rs = get_remote_state ();
6118 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6119 remote_send (&rs->buf, &rs->buf_size);
6121 /* We can get out of synch in various cases. If the first character
6122 in the buffer is not a hex character, assume that has happened
6123 and try to fetch another packet to read. */
6124 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6125 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6126 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6127 && rs->buf[0] != 'x') /* New: unavailable register value. */
6130 fprintf_unfiltered (gdb_stdlog,
6131 "Bad register packet; fetching a new packet\n");
6132 getpkt (&rs->buf, &rs->buf_size, 0);
6135 buf_len = strlen (rs->buf);
6137 /* Sanity check the received packet. */
6138 if (buf_len % 2 != 0)
6139 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6145 process_g_packet (struct regcache *regcache)
6147 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6148 struct remote_state *rs = get_remote_state ();
6149 struct remote_arch_state *rsa = get_remote_arch_state ();
6154 buf_len = strlen (rs->buf);
6156 /* Further sanity checks, with knowledge of the architecture. */
6157 if (buf_len > 2 * rsa->sizeof_g_packet)
6158 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6160 /* Save the size of the packet sent to us by the target. It is used
6161 as a heuristic when determining the max size of packets that the
6162 target can safely receive. */
6163 if (rsa->actual_register_packet_size == 0)
6164 rsa->actual_register_packet_size = buf_len;
6166 /* If this is smaller than we guessed the 'g' packet would be,
6167 update our records. A 'g' reply that doesn't include a register's
6168 value implies either that the register is not available, or that
6169 the 'p' packet must be used. */
6170 if (buf_len < 2 * rsa->sizeof_g_packet)
6172 rsa->sizeof_g_packet = buf_len / 2;
6174 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6176 if (rsa->regs[i].pnum == -1)
6179 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6180 rsa->regs[i].in_g_packet = 0;
6182 rsa->regs[i].in_g_packet = 1;
6186 regs = alloca (rsa->sizeof_g_packet);
6188 /* Unimplemented registers read as all bits zero. */
6189 memset (regs, 0, rsa->sizeof_g_packet);
6191 /* Reply describes registers byte by byte, each byte encoded as two
6192 hex characters. Suck them all up, then supply them to the
6193 register cacheing/storage mechanism. */
6196 for (i = 0; i < rsa->sizeof_g_packet; i++)
6198 if (p[0] == 0 || p[1] == 0)
6199 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6200 internal_error (__FILE__, __LINE__,
6201 _("unexpected end of 'g' packet reply"));
6203 if (p[0] == 'x' && p[1] == 'x')
6204 regs[i] = 0; /* 'x' */
6206 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6210 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6212 struct packet_reg *r = &rsa->regs[i];
6216 if (r->offset * 2 >= strlen (rs->buf))
6217 /* This shouldn't happen - we adjusted in_g_packet above. */
6218 internal_error (__FILE__, __LINE__,
6219 _("unexpected end of 'g' packet reply"));
6220 else if (rs->buf[r->offset * 2] == 'x')
6222 gdb_assert (r->offset * 2 < strlen (rs->buf));
6223 /* The register isn't available, mark it as such (at
6224 the same time setting the value to zero). */
6225 regcache_raw_supply (regcache, r->regnum, NULL);
6228 regcache_raw_supply (regcache, r->regnum,
6235 fetch_registers_using_g (struct regcache *regcache)
6238 process_g_packet (regcache);
6241 /* Make the remote selected traceframe match GDB's selected
6245 set_remote_traceframe (void)
6248 struct remote_state *rs = get_remote_state ();
6250 if (rs->remote_traceframe_number == get_traceframe_number ())
6253 /* Avoid recursion, remote_trace_find calls us again. */
6254 rs->remote_traceframe_number = get_traceframe_number ();
6256 newnum = target_trace_find (tfind_number,
6257 get_traceframe_number (), 0, 0, NULL);
6259 /* Should not happen. If it does, all bets are off. */
6260 if (newnum != get_traceframe_number ())
6261 warning (_("could not set remote traceframe"));
6265 remote_fetch_registers (struct target_ops *ops,
6266 struct regcache *regcache, int regnum)
6268 struct remote_arch_state *rsa = get_remote_arch_state ();
6271 set_remote_traceframe ();
6272 set_general_thread (inferior_ptid);
6276 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6278 gdb_assert (reg != NULL);
6280 /* If this register might be in the 'g' packet, try that first -
6281 we are likely to read more than one register. If this is the
6282 first 'g' packet, we might be overly optimistic about its
6283 contents, so fall back to 'p'. */
6284 if (reg->in_g_packet)
6286 fetch_registers_using_g (regcache);
6287 if (reg->in_g_packet)
6291 if (fetch_register_using_p (regcache, reg))
6294 /* This register is not available. */
6295 regcache_raw_supply (regcache, reg->regnum, NULL);
6300 fetch_registers_using_g (regcache);
6302 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6303 if (!rsa->regs[i].in_g_packet)
6304 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6306 /* This register is not available. */
6307 regcache_raw_supply (regcache, i, NULL);
6311 /* Prepare to store registers. Since we may send them all (using a
6312 'G' request), we have to read out the ones we don't want to change
6316 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6318 struct remote_arch_state *rsa = get_remote_arch_state ();
6320 gdb_byte buf[MAX_REGISTER_SIZE];
6322 /* Make sure the entire registers array is valid. */
6323 switch (packet_support (PACKET_P))
6325 case PACKET_DISABLE:
6326 case PACKET_SUPPORT_UNKNOWN:
6327 /* Make sure all the necessary registers are cached. */
6328 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6329 if (rsa->regs[i].in_g_packet)
6330 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6337 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6338 packet was not recognized. */
6341 store_register_using_P (const struct regcache *regcache,
6342 struct packet_reg *reg)
6344 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6345 struct remote_state *rs = get_remote_state ();
6346 /* Try storing a single register. */
6347 char *buf = rs->buf;
6348 gdb_byte regp[MAX_REGISTER_SIZE];
6351 if (packet_support (PACKET_P) == PACKET_DISABLE)
6354 if (reg->pnum == -1)
6357 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6358 p = buf + strlen (buf);
6359 regcache_raw_collect (regcache, reg->regnum, regp);
6360 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6362 getpkt (&rs->buf, &rs->buf_size, 0);
6364 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6369 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6370 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6371 case PACKET_UNKNOWN:
6374 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6378 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6379 contents of the register cache buffer. FIXME: ignores errors. */
6382 store_registers_using_G (const struct regcache *regcache)
6384 struct remote_state *rs = get_remote_state ();
6385 struct remote_arch_state *rsa = get_remote_arch_state ();
6389 /* Extract all the registers in the regcache copying them into a
6394 regs = alloca (rsa->sizeof_g_packet);
6395 memset (regs, 0, rsa->sizeof_g_packet);
6396 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6398 struct packet_reg *r = &rsa->regs[i];
6401 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6405 /* Command describes registers byte by byte,
6406 each byte encoded as two hex characters. */
6409 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6411 bin2hex (regs, p, rsa->sizeof_g_packet);
6413 getpkt (&rs->buf, &rs->buf_size, 0);
6414 if (packet_check_result (rs->buf) == PACKET_ERROR)
6415 error (_("Could not write registers; remote failure reply '%s'"),
6419 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6420 of the register cache buffer. FIXME: ignores errors. */
6423 remote_store_registers (struct target_ops *ops,
6424 struct regcache *regcache, int regnum)
6426 struct remote_arch_state *rsa = get_remote_arch_state ();
6429 set_remote_traceframe ();
6430 set_general_thread (inferior_ptid);
6434 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6436 gdb_assert (reg != NULL);
6438 /* Always prefer to store registers using the 'P' packet if
6439 possible; we often change only a small number of registers.
6440 Sometimes we change a larger number; we'd need help from a
6441 higher layer to know to use 'G'. */
6442 if (store_register_using_P (regcache, reg))
6445 /* For now, don't complain if we have no way to write the
6446 register. GDB loses track of unavailable registers too
6447 easily. Some day, this may be an error. We don't have
6448 any way to read the register, either... */
6449 if (!reg->in_g_packet)
6452 store_registers_using_G (regcache);
6456 store_registers_using_G (regcache);
6458 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6459 if (!rsa->regs[i].in_g_packet)
6460 if (!store_register_using_P (regcache, &rsa->regs[i]))
6461 /* See above for why we do not issue an error here. */
6466 /* Return the number of hex digits in num. */
6469 hexnumlen (ULONGEST num)
6473 for (i = 0; num != 0; i++)
6479 /* Set BUF to the minimum number of hex digits representing NUM. */
6482 hexnumstr (char *buf, ULONGEST num)
6484 int len = hexnumlen (num);
6486 return hexnumnstr (buf, num, len);
6490 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6493 hexnumnstr (char *buf, ULONGEST num, int width)
6499 for (i = width - 1; i >= 0; i--)
6501 buf[i] = "0123456789abcdef"[(num & 0xf)];
6508 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6511 remote_address_masked (CORE_ADDR addr)
6513 unsigned int address_size = remote_address_size;
6515 /* If "remoteaddresssize" was not set, default to target address size. */
6517 address_size = gdbarch_addr_bit (target_gdbarch ());
6519 if (address_size > 0
6520 && address_size < (sizeof (ULONGEST) * 8))
6522 /* Only create a mask when that mask can safely be constructed
6523 in a ULONGEST variable. */
6526 mask = (mask << address_size) - 1;
6532 /* Determine whether the remote target supports binary downloading.
6533 This is accomplished by sending a no-op memory write of zero length
6534 to the target at the specified address. It does not suffice to send
6535 the whole packet, since many stubs strip the eighth bit and
6536 subsequently compute a wrong checksum, which causes real havoc with
6539 NOTE: This can still lose if the serial line is not eight-bit
6540 clean. In cases like this, the user should clear "remote
6544 check_binary_download (CORE_ADDR addr)
6546 struct remote_state *rs = get_remote_state ();
6548 switch (packet_support (PACKET_X))
6550 case PACKET_DISABLE:
6554 case PACKET_SUPPORT_UNKNOWN:
6560 p += hexnumstr (p, (ULONGEST) addr);
6562 p += hexnumstr (p, (ULONGEST) 0);
6566 putpkt_binary (rs->buf, (int) (p - rs->buf));
6567 getpkt (&rs->buf, &rs->buf_size, 0);
6569 if (rs->buf[0] == '\0')
6572 fprintf_unfiltered (gdb_stdlog,
6573 "binary downloading NOT "
6574 "supported by target\n");
6575 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6580 fprintf_unfiltered (gdb_stdlog,
6581 "binary downloading supported by target\n");
6582 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6589 /* Write memory data directly to the remote machine.
6590 This does not inform the data cache; the data cache uses this.
6591 HEADER is the starting part of the packet.
6592 MEMADDR is the address in the remote memory space.
6593 MYADDR is the address of the buffer in our space.
6594 LEN is the number of bytes.
6595 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6596 should send data as binary ('X'), or hex-encoded ('M').
6598 The function creates packet of the form
6599 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6601 where encoding of <DATA> is termined by PACKET_FORMAT.
6603 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6606 Return the transferred status, error or OK (an
6607 'enum target_xfer_status' value). Save the number of bytes
6608 transferred in *XFERED_LEN. Only transfer a single packet. */
6610 static enum target_xfer_status
6611 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6612 const gdb_byte *myaddr, ULONGEST len,
6613 ULONGEST *xfered_len, char packet_format,
6616 struct remote_state *rs = get_remote_state ();
6626 if (packet_format != 'X' && packet_format != 'M')
6627 internal_error (__FILE__, __LINE__,
6628 _("remote_write_bytes_aux: bad packet format"));
6631 return TARGET_XFER_EOF;
6633 payload_size = get_memory_write_packet_size ();
6635 /* The packet buffer will be large enough for the payload;
6636 get_memory_packet_size ensures this. */
6639 /* Compute the size of the actual payload by subtracting out the
6640 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6642 payload_size -= strlen ("$,:#NN");
6644 /* The comma won't be used. */
6646 header_length = strlen (header);
6647 payload_size -= header_length;
6648 payload_size -= hexnumlen (memaddr);
6650 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6652 strcat (rs->buf, header);
6653 p = rs->buf + strlen (header);
6655 /* Compute a best guess of the number of bytes actually transfered. */
6656 if (packet_format == 'X')
6658 /* Best guess at number of bytes that will fit. */
6659 todo = min (len, payload_size);
6661 payload_size -= hexnumlen (todo);
6662 todo = min (todo, payload_size);
6666 /* Num bytes that will fit. */
6667 todo = min (len, payload_size / 2);
6669 payload_size -= hexnumlen (todo);
6670 todo = min (todo, payload_size / 2);
6674 internal_error (__FILE__, __LINE__,
6675 _("minimum packet size too small to write data"));
6677 /* If we already need another packet, then try to align the end
6678 of this packet to a useful boundary. */
6679 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6680 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6682 /* Append "<memaddr>". */
6683 memaddr = remote_address_masked (memaddr);
6684 p += hexnumstr (p, (ULONGEST) memaddr);
6691 /* Append <len>. Retain the location/size of <len>. It may need to
6692 be adjusted once the packet body has been created. */
6694 plenlen = hexnumstr (p, (ULONGEST) todo);
6702 /* Append the packet body. */
6703 if (packet_format == 'X')
6705 /* Binary mode. Send target system values byte by byte, in
6706 increasing byte addresses. Only escape certain critical
6708 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6709 &nr_bytes, payload_size);
6711 /* If not all TODO bytes fit, then we'll need another packet. Make
6712 a second try to keep the end of the packet aligned. Don't do
6713 this if the packet is tiny. */
6714 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6718 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6720 if (new_nr_bytes != nr_bytes)
6721 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6722 (gdb_byte *) p, &nr_bytes,
6726 p += payload_length;
6727 if (use_length && nr_bytes < todo)
6729 /* Escape chars have filled up the buffer prematurely,
6730 and we have actually sent fewer bytes than planned.
6731 Fix-up the length field of the packet. Use the same
6732 number of characters as before. */
6733 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6734 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6739 /* Normal mode: Send target system values byte by byte, in
6740 increasing byte addresses. Each byte is encoded as a two hex
6742 nr_bytes = bin2hex (myaddr, p, todo);
6746 putpkt_binary (rs->buf, (int) (p - rs->buf));
6747 getpkt (&rs->buf, &rs->buf_size, 0);
6749 if (rs->buf[0] == 'E')
6750 return TARGET_XFER_E_IO;
6752 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6753 fewer bytes than we'd planned. */
6754 *xfered_len = (ULONGEST) nr_bytes;
6755 return TARGET_XFER_OK;
6758 /* Write memory data directly to the remote machine.
6759 This does not inform the data cache; the data cache uses this.
6760 MEMADDR is the address in the remote memory space.
6761 MYADDR is the address of the buffer in our space.
6762 LEN is the number of bytes.
6764 Return the transferred status, error or OK (an
6765 'enum target_xfer_status' value). Save the number of bytes
6766 transferred in *XFERED_LEN. Only transfer a single packet. */
6768 static enum target_xfer_status
6769 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6770 ULONGEST *xfered_len)
6772 char *packet_format = 0;
6774 /* Check whether the target supports binary download. */
6775 check_binary_download (memaddr);
6777 switch (packet_support (PACKET_X))
6780 packet_format = "X";
6782 case PACKET_DISABLE:
6783 packet_format = "M";
6785 case PACKET_SUPPORT_UNKNOWN:
6786 internal_error (__FILE__, __LINE__,
6787 _("remote_write_bytes: bad internal state"));
6789 internal_error (__FILE__, __LINE__, _("bad switch"));
6792 return remote_write_bytes_aux (packet_format,
6793 memaddr, myaddr, len, xfered_len,
6794 packet_format[0], 1);
6797 /* Read memory data directly from the remote machine.
6798 This does not use the data cache; the data cache uses this.
6799 MEMADDR is the address in the remote memory space.
6800 MYADDR is the address of the buffer in our space.
6801 LEN is the number of bytes.
6803 Return the transferred status, error or OK (an
6804 'enum target_xfer_status' value). Save the number of bytes
6805 transferred in *XFERED_LEN. */
6807 static enum target_xfer_status
6808 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6809 ULONGEST *xfered_len)
6811 struct remote_state *rs = get_remote_state ();
6812 int max_buf_size; /* Max size of packet output buffer. */
6817 max_buf_size = get_memory_read_packet_size ();
6818 /* The packet buffer will be large enough for the payload;
6819 get_memory_packet_size ensures this. */
6821 /* Number if bytes that will fit. */
6822 todo = min (len, max_buf_size / 2);
6824 /* Construct "m"<memaddr>","<len>". */
6825 memaddr = remote_address_masked (memaddr);
6828 p += hexnumstr (p, (ULONGEST) memaddr);
6830 p += hexnumstr (p, (ULONGEST) todo);
6833 getpkt (&rs->buf, &rs->buf_size, 0);
6834 if (rs->buf[0] == 'E'
6835 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6836 && rs->buf[3] == '\0')
6837 return TARGET_XFER_E_IO;
6838 /* Reply describes memory byte by byte, each byte encoded as two hex
6841 i = hex2bin (p, myaddr, todo);
6842 /* Return what we have. Let higher layers handle partial reads. */
6843 *xfered_len = (ULONGEST) i;
6844 return TARGET_XFER_OK;
6847 /* Using the set of read-only target sections of remote, read live
6850 For interface/parameters/return description see target.h,
6853 static enum target_xfer_status
6854 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6855 ULONGEST memaddr, ULONGEST len,
6856 ULONGEST *xfered_len)
6858 struct target_section *secp;
6859 struct target_section_table *table;
6861 secp = target_section_by_addr (ops, memaddr);
6863 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6864 secp->the_bfd_section)
6867 struct target_section *p;
6868 ULONGEST memend = memaddr + len;
6870 table = target_get_section_table (ops);
6872 for (p = table->sections; p < table->sections_end; p++)
6874 if (memaddr >= p->addr)
6876 if (memend <= p->endaddr)
6878 /* Entire transfer is within this section. */
6879 return remote_read_bytes_1 (memaddr, readbuf, len,
6882 else if (memaddr >= p->endaddr)
6884 /* This section ends before the transfer starts. */
6889 /* This section overlaps the transfer. Just do half. */
6890 len = p->endaddr - memaddr;
6891 return remote_read_bytes_1 (memaddr, readbuf, len,
6898 return TARGET_XFER_EOF;
6901 /* Similar to remote_read_bytes_1, but it reads from the remote stub
6902 first if the requested memory is unavailable in traceframe.
6903 Otherwise, fall back to remote_read_bytes_1. */
6905 static enum target_xfer_status
6906 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6907 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
6910 return TARGET_XFER_EOF;
6912 if (get_traceframe_number () != -1)
6914 VEC(mem_range_s) *available;
6916 /* If we fail to get the set of available memory, then the
6917 target does not support querying traceframe info, and so we
6918 attempt reading from the traceframe anyway (assuming the
6919 target implements the old QTro packet then). */
6920 if (traceframe_available_memory (&available, memaddr, len))
6922 struct cleanup *old_chain;
6924 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6926 if (VEC_empty (mem_range_s, available)
6927 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6929 enum target_xfer_status res;
6931 /* Don't read into the traceframe's available
6933 if (!VEC_empty (mem_range_s, available))
6935 LONGEST oldlen = len;
6937 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
6938 gdb_assert (len <= oldlen);
6941 do_cleanups (old_chain);
6943 /* This goes through the topmost target again. */
6944 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
6946 if (res == TARGET_XFER_OK)
6947 return TARGET_XFER_OK;
6950 /* No use trying further, we know some memory starting
6951 at MEMADDR isn't available. */
6953 return TARGET_XFER_UNAVAILABLE;
6957 /* Don't try to read more than how much is available, in
6958 case the target implements the deprecated QTro packet to
6959 cater for older GDBs (the target's knowledge of read-only
6960 sections may be outdated by now). */
6961 len = VEC_index (mem_range_s, available, 0)->length;
6963 do_cleanups (old_chain);
6967 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
6972 /* Sends a packet with content determined by the printf format string
6973 FORMAT and the remaining arguments, then gets the reply. Returns
6974 whether the packet was a success, a failure, or unknown. */
6976 static enum packet_result
6977 remote_send_printf (const char *format, ...)
6979 struct remote_state *rs = get_remote_state ();
6980 int max_size = get_remote_packet_size ();
6983 va_start (ap, format);
6986 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
6987 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
6989 if (putpkt (rs->buf) < 0)
6990 error (_("Communication problem with target."));
6993 getpkt (&rs->buf, &rs->buf_size, 0);
6995 return packet_check_result (rs->buf);
6999 restore_remote_timeout (void *p)
7001 int value = *(int *)p;
7003 remote_timeout = value;
7006 /* Flash writing can take quite some time. We'll set
7007 effectively infinite timeout for flash operations.
7008 In future, we'll need to decide on a better approach. */
7009 static const int remote_flash_timeout = 1000;
7012 remote_flash_erase (struct target_ops *ops,
7013 ULONGEST address, LONGEST length)
7015 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7016 int saved_remote_timeout = remote_timeout;
7017 enum packet_result ret;
7018 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7019 &saved_remote_timeout);
7021 remote_timeout = remote_flash_timeout;
7023 ret = remote_send_printf ("vFlashErase:%s,%s",
7024 phex (address, addr_size),
7028 case PACKET_UNKNOWN:
7029 error (_("Remote target does not support flash erase"));
7031 error (_("Error erasing flash with vFlashErase packet"));
7036 do_cleanups (back_to);
7039 static enum target_xfer_status
7040 remote_flash_write (struct target_ops *ops, ULONGEST address,
7041 ULONGEST length, ULONGEST *xfered_len,
7042 const gdb_byte *data)
7044 int saved_remote_timeout = remote_timeout;
7045 enum target_xfer_status ret;
7046 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7047 &saved_remote_timeout);
7049 remote_timeout = remote_flash_timeout;
7050 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7052 do_cleanups (back_to);
7058 remote_flash_done (struct target_ops *ops)
7060 int saved_remote_timeout = remote_timeout;
7062 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7063 &saved_remote_timeout);
7065 remote_timeout = remote_flash_timeout;
7066 ret = remote_send_printf ("vFlashDone");
7067 do_cleanups (back_to);
7071 case PACKET_UNKNOWN:
7072 error (_("Remote target does not support vFlashDone"));
7074 error (_("Error finishing flash operation"));
7081 remote_files_info (struct target_ops *ignore)
7083 puts_filtered ("Debugging a target over a serial line.\n");
7086 /* Stuff for dealing with the packets which are part of this protocol.
7087 See comment at top of file for details. */
7089 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7090 error to higher layers. Called when a serial error is detected.
7091 The exception message is STRING, followed by a colon and a blank,
7092 the system error message for errno at function entry and final dot
7093 for output compatibility with throw_perror_with_name. */
7096 unpush_and_perror (const char *string)
7098 int saved_errno = errno;
7100 remote_unpush_target ();
7101 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7102 safe_strerror (saved_errno));
7105 /* Read a single character from the remote end. */
7108 readchar (int timeout)
7111 struct remote_state *rs = get_remote_state ();
7113 ch = serial_readchar (rs->remote_desc, timeout);
7118 switch ((enum serial_rc) ch)
7121 remote_unpush_target ();
7122 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7125 unpush_and_perror (_("Remote communication error. "
7126 "Target disconnected."));
7128 case SERIAL_TIMEOUT:
7134 /* Wrapper for serial_write that closes the target and throws if
7138 remote_serial_write (const char *str, int len)
7140 struct remote_state *rs = get_remote_state ();
7142 if (serial_write (rs->remote_desc, str, len))
7144 unpush_and_perror (_("Remote communication error. "
7145 "Target disconnected."));
7149 /* Send the command in *BUF to the remote machine, and read the reply
7150 into *BUF. Report an error if we get an error reply. Resize
7151 *BUF using xrealloc if necessary to hold the result, and update
7155 remote_send (char **buf,
7159 getpkt (buf, sizeof_buf, 0);
7161 if ((*buf)[0] == 'E')
7162 error (_("Remote failure reply: %s"), *buf);
7165 /* Return a pointer to an xmalloc'ed string representing an escaped
7166 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7167 etc. The caller is responsible for releasing the returned
7171 escape_buffer (const char *buf, int n)
7173 struct cleanup *old_chain;
7174 struct ui_file *stb;
7177 stb = mem_fileopen ();
7178 old_chain = make_cleanup_ui_file_delete (stb);
7180 fputstrn_unfiltered (buf, n, '\\', stb);
7181 str = ui_file_xstrdup (stb, NULL);
7182 do_cleanups (old_chain);
7186 /* Display a null-terminated packet on stdout, for debugging, using C
7190 print_packet (const char *buf)
7192 puts_filtered ("\"");
7193 fputstr_filtered (buf, '"', gdb_stdout);
7194 puts_filtered ("\"");
7198 putpkt (const char *buf)
7200 return putpkt_binary (buf, strlen (buf));
7203 /* Send a packet to the remote machine, with error checking. The data
7204 of the packet is in BUF. The string in BUF can be at most
7205 get_remote_packet_size () - 5 to account for the $, # and checksum,
7206 and for a possible /0 if we are debugging (remote_debug) and want
7207 to print the sent packet as a string. */
7210 putpkt_binary (const char *buf, int cnt)
7212 struct remote_state *rs = get_remote_state ();
7214 unsigned char csum = 0;
7215 char *buf2 = alloca (cnt + 6);
7222 /* Catch cases like trying to read memory or listing threads while
7223 we're waiting for a stop reply. The remote server wouldn't be
7224 ready to handle this request, so we'd hang and timeout. We don't
7225 have to worry about this in synchronous mode, because in that
7226 case it's not possible to issue a command while the target is
7227 running. This is not a problem in non-stop mode, because in that
7228 case, the stub is always ready to process serial input. */
7229 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
7231 error (_("Cannot execute this command while the target is running.\n"
7232 "Use the \"interrupt\" command to stop the target\n"
7233 "and then try again."));
7236 /* We're sending out a new packet. Make sure we don't look at a
7237 stale cached response. */
7238 rs->cached_wait_status = 0;
7240 /* Copy the packet into buffer BUF2, encapsulating it
7241 and giving it a checksum. */
7246 for (i = 0; i < cnt; i++)
7252 *p++ = tohex ((csum >> 4) & 0xf);
7253 *p++ = tohex (csum & 0xf);
7255 /* Send it over and over until we get a positive ack. */
7259 int started_error_output = 0;
7263 struct cleanup *old_chain;
7267 str = escape_buffer (buf2, p - buf2);
7268 old_chain = make_cleanup (xfree, str);
7269 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7270 gdb_flush (gdb_stdlog);
7271 do_cleanups (old_chain);
7273 remote_serial_write (buf2, p - buf2);
7275 /* If this is a no acks version of the remote protocol, send the
7276 packet and move on. */
7280 /* Read until either a timeout occurs (-2) or '+' is read.
7281 Handle any notification that arrives in the mean time. */
7284 ch = readchar (remote_timeout);
7292 case SERIAL_TIMEOUT:
7295 if (started_error_output)
7297 putchar_unfiltered ('\n');
7298 started_error_output = 0;
7307 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7311 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7313 case SERIAL_TIMEOUT:
7317 break; /* Retransmit buffer. */
7321 fprintf_unfiltered (gdb_stdlog,
7322 "Packet instead of Ack, ignoring it\n");
7323 /* It's probably an old response sent because an ACK
7324 was lost. Gobble up the packet and ack it so it
7325 doesn't get retransmitted when we resend this
7328 remote_serial_write ("+", 1);
7329 continue; /* Now, go look for +. */
7336 /* If we got a notification, handle it, and go back to looking
7338 /* We've found the start of a notification. Now
7339 collect the data. */
7340 val = read_frame (&rs->buf, &rs->buf_size);
7345 struct cleanup *old_chain;
7348 str = escape_buffer (rs->buf, val);
7349 old_chain = make_cleanup (xfree, str);
7350 fprintf_unfiltered (gdb_stdlog,
7351 " Notification received: %s\n",
7353 do_cleanups (old_chain);
7355 handle_notification (rs->notif_state, rs->buf);
7356 /* We're in sync now, rewait for the ack. */
7363 if (!started_error_output)
7365 started_error_output = 1;
7366 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7368 fputc_unfiltered (ch & 0177, gdb_stdlog);
7369 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7378 if (!started_error_output)
7380 started_error_output = 1;
7381 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7383 fputc_unfiltered (ch & 0177, gdb_stdlog);
7387 break; /* Here to retransmit. */
7391 /* This is wrong. If doing a long backtrace, the user should be
7392 able to get out next time we call QUIT, without anything as
7393 violent as interrupt_query. If we want to provide a way out of
7394 here without getting to the next QUIT, it should be based on
7395 hitting ^C twice as in remote_wait. */
7406 /* Come here after finding the start of a frame when we expected an
7407 ack. Do our best to discard the rest of this packet. */
7416 c = readchar (remote_timeout);
7419 case SERIAL_TIMEOUT:
7420 /* Nothing we can do. */
7423 /* Discard the two bytes of checksum and stop. */
7424 c = readchar (remote_timeout);
7426 c = readchar (remote_timeout);
7429 case '*': /* Run length encoding. */
7430 /* Discard the repeat count. */
7431 c = readchar (remote_timeout);
7436 /* A regular character. */
7442 /* Come here after finding the start of the frame. Collect the rest
7443 into *BUF, verifying the checksum, length, and handling run-length
7444 compression. NUL terminate the buffer. If there is not enough room,
7445 expand *BUF using xrealloc.
7447 Returns -1 on error, number of characters in buffer (ignoring the
7448 trailing NULL) on success. (could be extended to return one of the
7449 SERIAL status indications). */
7452 read_frame (char **buf_p,
7459 struct remote_state *rs = get_remote_state ();
7466 c = readchar (remote_timeout);
7469 case SERIAL_TIMEOUT:
7471 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7475 fputs_filtered ("Saw new packet start in middle of old one\n",
7477 return -1; /* Start a new packet, count retries. */
7480 unsigned char pktcsum;
7486 check_0 = readchar (remote_timeout);
7488 check_1 = readchar (remote_timeout);
7490 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7493 fputs_filtered ("Timeout in checksum, retrying\n",
7497 else if (check_0 < 0 || check_1 < 0)
7500 fputs_filtered ("Communication error in checksum\n",
7505 /* Don't recompute the checksum; with no ack packets we
7506 don't have any way to indicate a packet retransmission
7511 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7512 if (csum == pktcsum)
7517 struct cleanup *old_chain;
7520 str = escape_buffer (buf, bc);
7521 old_chain = make_cleanup (xfree, str);
7522 fprintf_unfiltered (gdb_stdlog,
7523 "Bad checksum, sentsum=0x%x, "
7524 "csum=0x%x, buf=%s\n",
7525 pktcsum, csum, str);
7526 do_cleanups (old_chain);
7528 /* Number of characters in buffer ignoring trailing
7532 case '*': /* Run length encoding. */
7537 c = readchar (remote_timeout);
7539 repeat = c - ' ' + 3; /* Compute repeat count. */
7541 /* The character before ``*'' is repeated. */
7543 if (repeat > 0 && repeat <= 255 && bc > 0)
7545 if (bc + repeat - 1 >= *sizeof_buf - 1)
7547 /* Make some more room in the buffer. */
7548 *sizeof_buf += repeat;
7549 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7553 memset (&buf[bc], buf[bc - 1], repeat);
7559 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7563 if (bc >= *sizeof_buf - 1)
7565 /* Make some more room in the buffer. */
7567 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7578 /* Read a packet from the remote machine, with error checking, and
7579 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7580 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7581 rather than timing out; this is used (in synchronous mode) to wait
7582 for a target that is is executing user code to stop. */
7583 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7584 don't have to change all the calls to getpkt to deal with the
7585 return value, because at the moment I don't know what the right
7586 thing to do it for those. */
7594 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7598 /* Read a packet from the remote machine, with error checking, and
7599 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7600 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7601 rather than timing out; this is used (in synchronous mode) to wait
7602 for a target that is is executing user code to stop. If FOREVER ==
7603 0, this function is allowed to time out gracefully and return an
7604 indication of this to the caller. Otherwise return the number of
7605 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7606 enough reason to return to the caller. *IS_NOTIF is an output
7607 boolean that indicates whether *BUF holds a notification or not
7608 (a regular packet). */
7611 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7612 int expecting_notif, int *is_notif)
7614 struct remote_state *rs = get_remote_state ();
7620 /* We're reading a new response. Make sure we don't look at a
7621 previously cached response. */
7622 rs->cached_wait_status = 0;
7624 strcpy (*buf, "timeout");
7627 timeout = watchdog > 0 ? watchdog : -1;
7628 else if (expecting_notif)
7629 timeout = 0; /* There should already be a char in the buffer. If
7632 timeout = remote_timeout;
7636 /* Process any number of notifications, and then return when
7640 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
7642 for (tries = 1; tries <= MAX_TRIES; tries++)
7644 /* This can loop forever if the remote side sends us
7645 characters continuously, but if it pauses, we'll get
7646 SERIAL_TIMEOUT from readchar because of timeout. Then
7647 we'll count that as a retry.
7649 Note that even when forever is set, we will only wait
7650 forever prior to the start of a packet. After that, we
7651 expect characters to arrive at a brisk pace. They should
7652 show up within remote_timeout intervals. */
7654 c = readchar (timeout);
7655 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7657 if (c == SERIAL_TIMEOUT)
7659 if (expecting_notif)
7660 return -1; /* Don't complain, it's normal to not get
7661 anything in this case. */
7663 if (forever) /* Watchdog went off? Kill the target. */
7666 remote_unpush_target ();
7667 throw_error (TARGET_CLOSE_ERROR,
7668 _("Watchdog timeout has expired. "
7669 "Target detached."));
7672 fputs_filtered ("Timed out.\n", gdb_stdlog);
7676 /* We've found the start of a packet or notification.
7677 Now collect the data. */
7678 val = read_frame (buf, sizeof_buf);
7683 remote_serial_write ("-", 1);
7686 if (tries > MAX_TRIES)
7688 /* We have tried hard enough, and just can't receive the
7689 packet/notification. Give up. */
7690 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7692 /* Skip the ack char if we're in no-ack mode. */
7693 if (!rs->noack_mode)
7694 remote_serial_write ("+", 1);
7698 /* If we got an ordinary packet, return that to our caller. */
7703 struct cleanup *old_chain;
7706 str = escape_buffer (*buf, val);
7707 old_chain = make_cleanup (xfree, str);
7708 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7709 do_cleanups (old_chain);
7712 /* Skip the ack char if we're in no-ack mode. */
7713 if (!rs->noack_mode)
7714 remote_serial_write ("+", 1);
7715 if (is_notif != NULL)
7720 /* If we got a notification, handle it, and go back to looking
7724 gdb_assert (c == '%');
7728 struct cleanup *old_chain;
7731 str = escape_buffer (*buf, val);
7732 old_chain = make_cleanup (xfree, str);
7733 fprintf_unfiltered (gdb_stdlog,
7734 " Notification received: %s\n",
7736 do_cleanups (old_chain);
7738 if (is_notif != NULL)
7741 handle_notification (rs->notif_state, *buf);
7743 /* Notifications require no acknowledgement. */
7745 if (expecting_notif)
7752 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7754 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7758 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7761 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7767 remote_kill (struct target_ops *ops)
7769 volatile struct gdb_exception ex;
7771 /* Catch errors so the user can quit from gdb even when we
7772 aren't on speaking terms with the remote system. */
7773 TRY_CATCH (ex, RETURN_MASK_ERROR)
7779 if (ex.error == TARGET_CLOSE_ERROR)
7781 /* If we got an (EOF) error that caused the target
7782 to go away, then we're done, that's what we wanted.
7783 "k" is susceptible to cause a premature EOF, given
7784 that the remote server isn't actually required to
7785 reply to "k", and it can happen that it doesn't
7786 even get to reply ACK to the "k". */
7790 /* Otherwise, something went wrong. We didn't actually kill
7791 the target. Just propagate the exception, and let the
7792 user or higher layers decide what to do. */
7793 throw_exception (ex);
7796 /* We've killed the remote end, we get to mourn it. Since this is
7797 target remote, single-process, mourning the inferior also
7798 unpushes remote_ops. */
7799 target_mourn_inferior ();
7803 remote_vkill (int pid, struct remote_state *rs)
7805 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
7808 /* Tell the remote target to detach. */
7809 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7811 getpkt (&rs->buf, &rs->buf_size, 0);
7813 switch (packet_ok (rs->buf,
7814 &remote_protocol_packets[PACKET_vKill]))
7820 case PACKET_UNKNOWN:
7823 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7828 extended_remote_kill (struct target_ops *ops)
7831 int pid = ptid_get_pid (inferior_ptid);
7832 struct remote_state *rs = get_remote_state ();
7834 res = remote_vkill (pid, rs);
7835 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7837 /* Don't try 'k' on a multi-process aware stub -- it has no way
7838 to specify the pid. */
7842 getpkt (&rs->buf, &rs->buf_size, 0);
7843 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7846 /* Don't wait for it to die. I'm not really sure it matters whether
7847 we do or not. For the existing stubs, kill is a noop. */
7853 error (_("Can't kill process"));
7855 target_mourn_inferior ();
7859 remote_mourn (struct target_ops *ops)
7861 remote_mourn_1 (ops);
7864 /* Worker function for remote_mourn. */
7866 remote_mourn_1 (struct target_ops *target)
7868 unpush_target (target);
7870 /* remote_close takes care of doing most of the clean up. */
7871 generic_mourn_inferior ();
7875 extended_remote_mourn_1 (struct target_ops *target)
7877 struct remote_state *rs = get_remote_state ();
7879 /* In case we got here due to an error, but we're going to stay
7881 rs->waiting_for_stop_reply = 0;
7883 /* If the current general thread belonged to the process we just
7884 detached from or has exited, the remote side current general
7885 thread becomes undefined. Considering a case like this:
7887 - We just got here due to a detach.
7888 - The process that we're detaching from happens to immediately
7889 report a global breakpoint being hit in non-stop mode, in the
7890 same thread we had selected before.
7891 - GDB attaches to this process again.
7892 - This event happens to be the next event we handle.
7894 GDB would consider that the current general thread didn't need to
7895 be set on the stub side (with Hg), since for all it knew,
7896 GENERAL_THREAD hadn't changed.
7898 Notice that although in all-stop mode, the remote server always
7899 sets the current thread to the thread reporting the stop event,
7900 that doesn't happen in non-stop mode; in non-stop, the stub *must
7901 not* change the current thread when reporting a breakpoint hit,
7902 due to the decoupling of event reporting and event handling.
7904 To keep things simple, we always invalidate our notion of the
7906 record_currthread (rs, minus_one_ptid);
7908 /* Unlike "target remote", we do not want to unpush the target; then
7909 the next time the user says "run", we won't be connected. */
7911 /* Call common code to mark the inferior as not running. */
7912 generic_mourn_inferior ();
7914 if (!have_inferiors ())
7916 if (!remote_multi_process_p (rs))
7918 /* Check whether the target is running now - some remote stubs
7919 automatically restart after kill. */
7921 getpkt (&rs->buf, &rs->buf_size, 0);
7923 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7925 /* Assume that the target has been restarted. Set
7926 inferior_ptid so that bits of core GDB realizes
7927 there's something here, e.g., so that the user can
7928 say "kill" again. */
7929 inferior_ptid = magic_null_ptid;
7936 extended_remote_mourn (struct target_ops *ops)
7938 extended_remote_mourn_1 (ops);
7942 extended_remote_supports_disable_randomization (struct target_ops *self)
7944 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
7948 extended_remote_disable_randomization (int val)
7950 struct remote_state *rs = get_remote_state ();
7953 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7956 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7958 error (_("Target does not support QDisableRandomization."));
7959 if (strcmp (reply, "OK") != 0)
7960 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7964 extended_remote_run (char *args)
7966 struct remote_state *rs = get_remote_state ();
7969 /* If the user has disabled vRun support, or we have detected that
7970 support is not available, do not try it. */
7971 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
7974 strcpy (rs->buf, "vRun;");
7975 len = strlen (rs->buf);
7977 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7978 error (_("Remote file name too long for run packet"));
7979 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
7980 strlen (remote_exec_file));
7982 gdb_assert (args != NULL);
7985 struct cleanup *back_to;
7989 argv = gdb_buildargv (args);
7990 back_to = make_cleanup_freeargv (argv);
7991 for (i = 0; argv[i] != NULL; i++)
7993 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7994 error (_("Argument list too long for run packet"));
7995 rs->buf[len++] = ';';
7996 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
7999 do_cleanups (back_to);
8002 rs->buf[len++] = '\0';
8005 getpkt (&rs->buf, &rs->buf_size, 0);
8007 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8010 /* We have a wait response. All is well. */
8012 case PACKET_UNKNOWN:
8015 if (remote_exec_file[0] == '\0')
8016 error (_("Running the default executable on the remote target failed; "
8017 "try \"set remote exec-file\"?"));
8019 error (_("Running \"%s\" on the remote target failed"),
8022 gdb_assert_not_reached (_("bad switch"));
8026 /* In the extended protocol we want to be able to do things like
8027 "run" and have them basically work as expected. So we need
8028 a special create_inferior function. We support changing the
8029 executable file and the command line arguments, but not the
8033 extended_remote_create_inferior (struct target_ops *ops,
8034 char *exec_file, char *args,
8035 char **env, int from_tty)
8039 struct remote_state *rs = get_remote_state ();
8041 /* If running asynchronously, register the target file descriptor
8042 with the event loop. */
8043 if (target_can_async_p ())
8044 target_async (inferior_event_handler, 0);
8046 /* Disable address space randomization if requested (and supported). */
8047 if (extended_remote_supports_disable_randomization (ops))
8048 extended_remote_disable_randomization (disable_randomization);
8050 /* Now restart the remote server. */
8051 run_worked = extended_remote_run (args) != -1;
8054 /* vRun was not supported. Fail if we need it to do what the
8056 if (remote_exec_file[0])
8057 error (_("Remote target does not support \"set remote exec-file\""));
8059 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8061 /* Fall back to "R". */
8062 extended_remote_restart ();
8065 if (!have_inferiors ())
8067 /* Clean up from the last time we ran, before we mark the target
8068 running again. This will mark breakpoints uninserted, and
8069 get_offsets may insert breakpoints. */
8070 init_thread_list ();
8071 init_wait_for_inferior ();
8074 /* vRun's success return is a stop reply. */
8075 stop_reply = run_worked ? rs->buf : NULL;
8076 add_current_inferior_and_thread (stop_reply);
8078 /* Get updated offsets, if the stub uses qOffsets. */
8083 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8084 the list of conditions (in agent expression bytecode format), if any, the
8085 target needs to evaluate. The output is placed into the packet buffer
8086 started from BUF and ended at BUF_END. */
8089 remote_add_target_side_condition (struct gdbarch *gdbarch,
8090 struct bp_target_info *bp_tgt, char *buf,
8093 struct agent_expr *aexpr = NULL;
8096 char *buf_start = buf;
8098 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8101 buf += strlen (buf);
8102 xsnprintf (buf, buf_end - buf, "%s", ";");
8105 /* Send conditions to the target and free the vector. */
8107 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8110 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8111 buf += strlen (buf);
8112 for (i = 0; i < aexpr->len; ++i)
8113 buf = pack_hex_byte (buf, aexpr->buf[i]);
8120 remote_add_target_side_commands (struct gdbarch *gdbarch,
8121 struct bp_target_info *bp_tgt, char *buf)
8123 struct agent_expr *aexpr = NULL;
8126 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8129 buf += strlen (buf);
8131 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8132 buf += strlen (buf);
8134 /* Concatenate all the agent expressions that are commands into the
8137 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8140 sprintf (buf, "X%x,", aexpr->len);
8141 buf += strlen (buf);
8142 for (i = 0; i < aexpr->len; ++i)
8143 buf = pack_hex_byte (buf, aexpr->buf[i]);
8148 /* Insert a breakpoint. On targets that have software breakpoint
8149 support, we ask the remote target to do the work; on targets
8150 which don't, we insert a traditional memory breakpoint. */
8153 remote_insert_breakpoint (struct target_ops *ops,
8154 struct gdbarch *gdbarch,
8155 struct bp_target_info *bp_tgt)
8157 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8158 If it succeeds, then set the support to PACKET_ENABLE. If it
8159 fails, and the user has explicitly requested the Z support then
8160 report an error, otherwise, mark it disabled and go on. */
8162 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8164 CORE_ADDR addr = bp_tgt->reqstd_address;
8165 struct remote_state *rs;
8168 struct condition_list *cond = NULL;
8170 /* Make sure the remote is pointing at the right process, if
8172 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8173 set_general_process ();
8175 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8177 rs = get_remote_state ();
8179 endbuf = rs->buf + get_remote_packet_size ();
8184 addr = (ULONGEST) remote_address_masked (addr);
8185 p += hexnumstr (p, addr);
8186 xsnprintf (p, endbuf - p, ",%d", bpsize);
8188 if (remote_supports_cond_breakpoints (ops))
8189 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8191 if (remote_can_run_breakpoint_commands (ops))
8192 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8195 getpkt (&rs->buf, &rs->buf_size, 0);
8197 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8202 bp_tgt->placed_address = addr;
8203 bp_tgt->placed_size = bpsize;
8205 case PACKET_UNKNOWN:
8210 /* If this breakpoint has target-side commands but this stub doesn't
8211 support Z0 packets, throw error. */
8212 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8213 throw_error (NOT_SUPPORTED_ERROR, _("\
8214 Target doesn't support breakpoints that have target side commands."));
8216 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8220 remote_remove_breakpoint (struct target_ops *ops,
8221 struct gdbarch *gdbarch,
8222 struct bp_target_info *bp_tgt)
8224 CORE_ADDR addr = bp_tgt->placed_address;
8225 struct remote_state *rs = get_remote_state ();
8227 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8230 char *endbuf = rs->buf + get_remote_packet_size ();
8232 /* Make sure the remote is pointing at the right process, if
8234 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8235 set_general_process ();
8241 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8242 p += hexnumstr (p, addr);
8243 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8246 getpkt (&rs->buf, &rs->buf_size, 0);
8248 return (rs->buf[0] == 'E');
8251 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8255 watchpoint_to_Z_packet (int type)
8260 return Z_PACKET_WRITE_WP;
8263 return Z_PACKET_READ_WP;
8266 return Z_PACKET_ACCESS_WP;
8269 internal_error (__FILE__, __LINE__,
8270 _("hw_bp_to_z: bad watchpoint type %d"), type);
8275 remote_insert_watchpoint (struct target_ops *self,
8276 CORE_ADDR addr, int len, int type,
8277 struct expression *cond)
8279 struct remote_state *rs = get_remote_state ();
8280 char *endbuf = rs->buf + get_remote_packet_size ();
8282 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8284 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8287 /* Make sure the remote is pointing at the right process, if
8289 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8290 set_general_process ();
8292 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8293 p = strchr (rs->buf, '\0');
8294 addr = remote_address_masked (addr);
8295 p += hexnumstr (p, (ULONGEST) addr);
8296 xsnprintf (p, endbuf - p, ",%x", len);
8299 getpkt (&rs->buf, &rs->buf_size, 0);
8301 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8305 case PACKET_UNKNOWN:
8310 internal_error (__FILE__, __LINE__,
8311 _("remote_insert_watchpoint: reached end of function"));
8315 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8316 CORE_ADDR start, int length)
8318 CORE_ADDR diff = remote_address_masked (addr - start);
8320 return diff < length;
8325 remote_remove_watchpoint (struct target_ops *self,
8326 CORE_ADDR addr, int len, int type,
8327 struct expression *cond)
8329 struct remote_state *rs = get_remote_state ();
8330 char *endbuf = rs->buf + get_remote_packet_size ();
8332 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8334 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8337 /* Make sure the remote is pointing at the right process, if
8339 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8340 set_general_process ();
8342 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8343 p = strchr (rs->buf, '\0');
8344 addr = remote_address_masked (addr);
8345 p += hexnumstr (p, (ULONGEST) addr);
8346 xsnprintf (p, endbuf - p, ",%x", len);
8348 getpkt (&rs->buf, &rs->buf_size, 0);
8350 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8353 case PACKET_UNKNOWN:
8358 internal_error (__FILE__, __LINE__,
8359 _("remote_remove_watchpoint: reached end of function"));
8363 int remote_hw_watchpoint_limit = -1;
8364 int remote_hw_watchpoint_length_limit = -1;
8365 int remote_hw_breakpoint_limit = -1;
8368 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8369 CORE_ADDR addr, int len)
8371 if (remote_hw_watchpoint_length_limit == 0)
8373 else if (remote_hw_watchpoint_length_limit < 0)
8375 else if (len <= remote_hw_watchpoint_length_limit)
8382 remote_check_watch_resources (struct target_ops *self,
8383 int type, int cnt, int ot)
8385 if (type == bp_hardware_breakpoint)
8387 if (remote_hw_breakpoint_limit == 0)
8389 else if (remote_hw_breakpoint_limit < 0)
8391 else if (cnt <= remote_hw_breakpoint_limit)
8396 if (remote_hw_watchpoint_limit == 0)
8398 else if (remote_hw_watchpoint_limit < 0)
8402 else if (cnt <= remote_hw_watchpoint_limit)
8409 remote_stopped_by_watchpoint (struct target_ops *ops)
8411 struct remote_state *rs = get_remote_state ();
8413 return rs->remote_stopped_by_watchpoint_p;
8417 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8419 struct remote_state *rs = get_remote_state ();
8422 if (remote_stopped_by_watchpoint (target))
8424 *addr_p = rs->remote_watch_data_address;
8433 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8434 struct bp_target_info *bp_tgt)
8436 CORE_ADDR addr = bp_tgt->reqstd_address;
8437 struct remote_state *rs;
8442 /* The length field should be set to the size of a breakpoint
8443 instruction, even though we aren't inserting one ourselves. */
8445 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8447 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8450 /* Make sure the remote is pointing at the right process, if
8452 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8453 set_general_process ();
8455 rs = get_remote_state ();
8457 endbuf = rs->buf + get_remote_packet_size ();
8463 addr = remote_address_masked (addr);
8464 p += hexnumstr (p, (ULONGEST) addr);
8465 xsnprintf (p, endbuf - p, ",%x", bpsize);
8467 if (remote_supports_cond_breakpoints (self))
8468 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8470 if (remote_can_run_breakpoint_commands (self))
8471 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8474 getpkt (&rs->buf, &rs->buf_size, 0);
8476 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8479 if (rs->buf[1] == '.')
8481 message = strchr (rs->buf + 2, '.');
8483 error (_("Remote failure reply: %s"), message + 1);
8486 case PACKET_UNKNOWN:
8489 bp_tgt->placed_address = addr;
8490 bp_tgt->placed_size = bpsize;
8493 internal_error (__FILE__, __LINE__,
8494 _("remote_insert_hw_breakpoint: reached end of function"));
8499 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8500 struct bp_target_info *bp_tgt)
8503 struct remote_state *rs = get_remote_state ();
8505 char *endbuf = rs->buf + get_remote_packet_size ();
8507 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8510 /* Make sure the remote is pointing at the right process, if
8512 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8513 set_general_process ();
8519 addr = remote_address_masked (bp_tgt->placed_address);
8520 p += hexnumstr (p, (ULONGEST) addr);
8521 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8524 getpkt (&rs->buf, &rs->buf_size, 0);
8526 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8529 case PACKET_UNKNOWN:
8534 internal_error (__FILE__, __LINE__,
8535 _("remote_remove_hw_breakpoint: reached end of function"));
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 /* It doesn't make sense to use qCRC if the remote target is
8549 connected but not running. */
8550 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8552 enum packet_result result;
8554 /* Make sure the remote is pointing at the right process. */
8555 set_general_process ();
8557 /* FIXME: assumes lma can fit into long. */
8558 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8559 (long) lma, (long) size);
8562 /* Be clever; compute the host_crc before waiting for target
8564 host_crc = xcrc32 (data, size, 0xffffffff);
8566 getpkt (&rs->buf, &rs->buf_size, 0);
8568 result = packet_ok (rs->buf,
8569 &remote_protocol_packets[PACKET_qCRC]);
8570 if (result == PACKET_ERROR)
8572 else if (result == PACKET_OK)
8574 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8575 target_crc = target_crc * 16 + fromhex (*tmp);
8577 return (host_crc == target_crc);
8581 return simple_verify_memory (ops, data, lma, size);
8584 /* compare-sections command
8586 With no arguments, compares each loadable section in the exec bfd
8587 with the same memory range on the target, and reports mismatches.
8588 Useful for verifying the image on the target against the exec file. */
8591 compare_sections_command (char *args, int from_tty)
8594 struct cleanup *old_chain;
8596 const char *sectname;
8605 error (_("command cannot be used without an exec file"));
8607 /* Make sure the remote is pointing at the right process. */
8608 set_general_process ();
8610 if (args != NULL && strcmp (args, "-r") == 0)
8616 for (s = exec_bfd->sections; s; s = s->next)
8618 if (!(s->flags & SEC_LOAD))
8619 continue; /* Skip non-loadable section. */
8621 if (read_only && (s->flags & SEC_READONLY) == 0)
8622 continue; /* Skip writeable sections */
8624 size = bfd_get_section_size (s);
8626 continue; /* Skip zero-length section. */
8628 sectname = bfd_get_section_name (exec_bfd, s);
8629 if (args && strcmp (args, sectname) != 0)
8630 continue; /* Not the section selected by user. */
8632 matched = 1; /* Do this section. */
8635 sectdata = xmalloc (size);
8636 old_chain = make_cleanup (xfree, sectdata);
8637 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8639 res = target_verify_memory (sectdata, lma, size);
8642 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8643 paddress (target_gdbarch (), lma),
8644 paddress (target_gdbarch (), lma + size));
8646 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8647 paddress (target_gdbarch (), lma),
8648 paddress (target_gdbarch (), lma + size));
8650 printf_filtered ("matched.\n");
8653 printf_filtered ("MIS-MATCHED!\n");
8657 do_cleanups (old_chain);
8660 warning (_("One or more sections of the target image does not match\n\
8661 the loaded file\n"));
8662 if (args && !matched)
8663 printf_filtered (_("No loaded section named '%s'.\n"), args);
8666 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8667 into remote target. The number of bytes written to the remote
8668 target is returned, or -1 for error. */
8670 static enum target_xfer_status
8671 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8672 const char *annex, const gdb_byte *writebuf,
8673 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
8674 struct packet_config *packet)
8678 struct remote_state *rs = get_remote_state ();
8679 int max_size = get_memory_write_packet_size ();
8681 if (packet->support == PACKET_DISABLE)
8682 return TARGET_XFER_E_IO;
8684 /* Insert header. */
8685 i = snprintf (rs->buf, max_size,
8686 "qXfer:%s:write:%s:%s:",
8687 object_name, annex ? annex : "",
8688 phex_nz (offset, sizeof offset));
8689 max_size -= (i + 1);
8691 /* Escape as much data as fits into rs->buf. */
8692 buf_len = remote_escape_output
8693 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8695 if (putpkt_binary (rs->buf, i + buf_len) < 0
8696 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8697 || packet_ok (rs->buf, packet) != PACKET_OK)
8698 return TARGET_XFER_E_IO;
8700 unpack_varlen_hex (rs->buf, &n);
8703 return TARGET_XFER_OK;
8706 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8707 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8708 number of bytes read is returned, or 0 for EOF, or -1 for error.
8709 The number of bytes read may be less than LEN without indicating an
8710 EOF. PACKET is checked and updated to indicate whether the remote
8711 target supports this object. */
8713 static enum target_xfer_status
8714 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8716 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8717 ULONGEST *xfered_len,
8718 struct packet_config *packet)
8720 struct remote_state *rs = get_remote_state ();
8721 LONGEST i, n, packet_len;
8723 if (packet->support == PACKET_DISABLE)
8724 return TARGET_XFER_E_IO;
8726 /* Check whether we've cached an end-of-object packet that matches
8728 if (rs->finished_object)
8730 if (strcmp (object_name, rs->finished_object) == 0
8731 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8732 && offset == rs->finished_offset)
8733 return TARGET_XFER_EOF;
8736 /* Otherwise, we're now reading something different. Discard
8738 xfree (rs->finished_object);
8739 xfree (rs->finished_annex);
8740 rs->finished_object = NULL;
8741 rs->finished_annex = NULL;
8744 /* Request only enough to fit in a single packet. The actual data
8745 may not, since we don't know how much of it will need to be escaped;
8746 the target is free to respond with slightly less data. We subtract
8747 five to account for the response type and the protocol frame. */
8748 n = min (get_remote_packet_size () - 5, len);
8749 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8750 object_name, annex ? annex : "",
8751 phex_nz (offset, sizeof offset),
8752 phex_nz (n, sizeof n));
8753 i = putpkt (rs->buf);
8755 return TARGET_XFER_E_IO;
8758 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8759 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8760 return TARGET_XFER_E_IO;
8762 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8763 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8765 /* 'm' means there is (or at least might be) more data after this
8766 batch. That does not make sense unless there's at least one byte
8767 of data in this reply. */
8768 if (rs->buf[0] == 'm' && packet_len == 1)
8769 error (_("Remote qXfer reply contained no data."));
8771 /* Got some data. */
8772 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8773 packet_len - 1, readbuf, n);
8775 /* 'l' is an EOF marker, possibly including a final block of data,
8776 or possibly empty. If we have the final block of a non-empty
8777 object, record this fact to bypass a subsequent partial read. */
8778 if (rs->buf[0] == 'l' && offset + i > 0)
8780 rs->finished_object = xstrdup (object_name);
8781 rs->finished_annex = xstrdup (annex ? annex : "");
8782 rs->finished_offset = offset + i;
8786 return TARGET_XFER_EOF;
8790 return TARGET_XFER_OK;
8794 static enum target_xfer_status
8795 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8796 const char *annex, gdb_byte *readbuf,
8797 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8798 ULONGEST *xfered_len)
8800 struct remote_state *rs;
8805 set_remote_traceframe ();
8806 set_general_thread (inferior_ptid);
8808 rs = get_remote_state ();
8810 /* Handle memory using the standard memory routines. */
8811 if (object == TARGET_OBJECT_MEMORY)
8813 /* If the remote target is connected but not running, we should
8814 pass this request down to a lower stratum (e.g. the executable
8816 if (!target_has_execution)
8817 return TARGET_XFER_EOF;
8819 if (writebuf != NULL)
8820 return remote_write_bytes (offset, writebuf, len, xfered_len);
8822 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
8825 /* Handle SPU memory using qxfer packets. */
8826 if (object == TARGET_OBJECT_SPU)
8829 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8830 xfered_len, &remote_protocol_packets
8831 [PACKET_qXfer_spu_read]);
8833 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8834 xfered_len, &remote_protocol_packets
8835 [PACKET_qXfer_spu_write]);
8838 /* Handle extra signal info using qxfer packets. */
8839 if (object == TARGET_OBJECT_SIGNAL_INFO)
8842 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8843 xfered_len, &remote_protocol_packets
8844 [PACKET_qXfer_siginfo_read]);
8846 return remote_write_qxfer (ops, "siginfo", annex,
8847 writebuf, offset, len, xfered_len,
8848 &remote_protocol_packets
8849 [PACKET_qXfer_siginfo_write]);
8852 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8855 return remote_read_qxfer (ops, "statictrace", annex,
8856 readbuf, offset, len, xfered_len,
8857 &remote_protocol_packets
8858 [PACKET_qXfer_statictrace_read]);
8860 return TARGET_XFER_E_IO;
8863 /* Only handle flash writes. */
8864 if (writebuf != NULL)
8870 case TARGET_OBJECT_FLASH:
8871 return remote_flash_write (ops, offset, len, xfered_len,
8875 return TARGET_XFER_E_IO;
8879 /* Map pre-existing objects onto letters. DO NOT do this for new
8880 objects!!! Instead specify new query packets. */
8883 case TARGET_OBJECT_AVR:
8887 case TARGET_OBJECT_AUXV:
8888 gdb_assert (annex == NULL);
8889 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8891 &remote_protocol_packets[PACKET_qXfer_auxv]);
8893 case TARGET_OBJECT_AVAILABLE_FEATURES:
8894 return remote_read_qxfer
8895 (ops, "features", annex, readbuf, offset, len, xfered_len,
8896 &remote_protocol_packets[PACKET_qXfer_features]);
8898 case TARGET_OBJECT_LIBRARIES:
8899 return remote_read_qxfer
8900 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
8901 &remote_protocol_packets[PACKET_qXfer_libraries]);
8903 case TARGET_OBJECT_LIBRARIES_SVR4:
8904 return remote_read_qxfer
8905 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
8906 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8908 case TARGET_OBJECT_MEMORY_MAP:
8909 gdb_assert (annex == NULL);
8910 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8912 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8914 case TARGET_OBJECT_OSDATA:
8915 /* Should only get here if we're connected. */
8916 gdb_assert (rs->remote_desc);
8917 return remote_read_qxfer
8918 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
8919 &remote_protocol_packets[PACKET_qXfer_osdata]);
8921 case TARGET_OBJECT_THREADS:
8922 gdb_assert (annex == NULL);
8923 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8925 &remote_protocol_packets[PACKET_qXfer_threads]);
8927 case TARGET_OBJECT_TRACEFRAME_INFO:
8928 gdb_assert (annex == NULL);
8929 return remote_read_qxfer
8930 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
8931 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8933 case TARGET_OBJECT_FDPIC:
8934 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8936 &remote_protocol_packets[PACKET_qXfer_fdpic]);
8938 case TARGET_OBJECT_OPENVMS_UIB:
8939 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
8941 &remote_protocol_packets[PACKET_qXfer_uib]);
8943 case TARGET_OBJECT_BTRACE:
8944 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
8946 &remote_protocol_packets[PACKET_qXfer_btrace]);
8949 return TARGET_XFER_E_IO;
8952 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
8953 large enough let the caller deal with it. */
8954 if (len < get_remote_packet_size ())
8955 return TARGET_XFER_E_IO;
8956 len = get_remote_packet_size ();
8958 /* Except for querying the minimum buffer size, target must be open. */
8959 if (!rs->remote_desc)
8960 error (_("remote query is only available after target open"));
8962 gdb_assert (annex != NULL);
8963 gdb_assert (readbuf != NULL);
8969 /* We used one buffer char for the remote protocol q command and
8970 another for the query type. As the remote protocol encapsulation
8971 uses 4 chars plus one extra in case we are debugging
8972 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8975 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8977 /* Bad caller may have sent forbidden characters. */
8978 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8983 gdb_assert (annex[i] == '\0');
8985 i = putpkt (rs->buf);
8987 return TARGET_XFER_E_IO;
8989 getpkt (&rs->buf, &rs->buf_size, 0);
8990 strcpy ((char *) readbuf, rs->buf);
8992 *xfered_len = strlen ((char *) readbuf);
8993 return TARGET_XFER_OK;
8997 remote_search_memory (struct target_ops* ops,
8998 CORE_ADDR start_addr, ULONGEST search_space_len,
8999 const gdb_byte *pattern, ULONGEST pattern_len,
9000 CORE_ADDR *found_addrp)
9002 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9003 struct remote_state *rs = get_remote_state ();
9004 int max_size = get_memory_write_packet_size ();
9005 struct packet_config *packet =
9006 &remote_protocol_packets[PACKET_qSearch_memory];
9007 /* Number of packet bytes used to encode the pattern;
9008 this could be more than PATTERN_LEN due to escape characters. */
9009 int escaped_pattern_len;
9010 /* Amount of pattern that was encodable in the packet. */
9011 int used_pattern_len;
9014 ULONGEST found_addr;
9016 /* Don't go to the target if we don't have to.
9017 This is done before checking packet->support to avoid the possibility that
9018 a success for this edge case means the facility works in general. */
9019 if (pattern_len > search_space_len)
9021 if (pattern_len == 0)
9023 *found_addrp = start_addr;
9027 /* If we already know the packet isn't supported, fall back to the simple
9028 way of searching memory. */
9030 if (packet_config_support (packet) == PACKET_DISABLE)
9032 /* Target doesn't provided special support, fall back and use the
9033 standard support (copy memory and do the search here). */
9034 return simple_search_memory (ops, start_addr, search_space_len,
9035 pattern, pattern_len, found_addrp);
9038 /* Make sure the remote is pointing at the right process. */
9039 set_general_process ();
9041 /* Insert header. */
9042 i = snprintf (rs->buf, max_size,
9043 "qSearch:memory:%s;%s;",
9044 phex_nz (start_addr, addr_size),
9045 phex_nz (search_space_len, sizeof (search_space_len)));
9046 max_size -= (i + 1);
9048 /* Escape as much data as fits into rs->buf. */
9049 escaped_pattern_len =
9050 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9051 &used_pattern_len, max_size);
9053 /* Bail if the pattern is too large. */
9054 if (used_pattern_len != pattern_len)
9055 error (_("Pattern is too large to transmit to remote target."));
9057 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9058 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9059 || packet_ok (rs->buf, packet) != PACKET_OK)
9061 /* The request may not have worked because the command is not
9062 supported. If so, fall back to the simple way. */
9063 if (packet->support == PACKET_DISABLE)
9065 return simple_search_memory (ops, start_addr, search_space_len,
9066 pattern, pattern_len, found_addrp);
9071 if (rs->buf[0] == '0')
9073 else if (rs->buf[0] == '1')
9076 if (rs->buf[1] != ',')
9077 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9078 unpack_varlen_hex (rs->buf + 2, &found_addr);
9079 *found_addrp = found_addr;
9082 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9088 remote_rcmd (struct target_ops *self, const char *command,
9089 struct ui_file *outbuf)
9091 struct remote_state *rs = get_remote_state ();
9094 if (!rs->remote_desc)
9095 error (_("remote rcmd is only available after target open"));
9097 /* Send a NULL command across as an empty command. */
9098 if (command == NULL)
9101 /* The query prefix. */
9102 strcpy (rs->buf, "qRcmd,");
9103 p = strchr (rs->buf, '\0');
9105 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9106 > get_remote_packet_size ())
9107 error (_("\"monitor\" command ``%s'' is too long."), command);
9109 /* Encode the actual command. */
9110 bin2hex ((const gdb_byte *) command, p, strlen (command));
9112 if (putpkt (rs->buf) < 0)
9113 error (_("Communication problem with target."));
9115 /* get/display the response */
9120 /* XXX - see also remote_get_noisy_reply(). */
9121 QUIT; /* Allow user to bail out with ^C. */
9123 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9125 /* Timeout. Continue to (try to) read responses.
9126 This is better than stopping with an error, assuming the stub
9127 is still executing the (long) monitor command.
9128 If needed, the user can interrupt gdb using C-c, obtaining
9129 an effect similar to stop on timeout. */
9134 error (_("Target does not support this command."));
9135 if (buf[0] == 'O' && buf[1] != 'K')
9137 remote_console_output (buf + 1); /* 'O' message from stub. */
9140 if (strcmp (buf, "OK") == 0)
9142 if (strlen (buf) == 3 && buf[0] == 'E'
9143 && isdigit (buf[1]) && isdigit (buf[2]))
9145 error (_("Protocol error with Rcmd"));
9147 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9149 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9151 fputc_unfiltered (c, outbuf);
9157 static VEC(mem_region_s) *
9158 remote_memory_map (struct target_ops *ops)
9160 VEC(mem_region_s) *result = NULL;
9161 char *text = target_read_stralloc (¤t_target,
9162 TARGET_OBJECT_MEMORY_MAP, NULL);
9166 struct cleanup *back_to = make_cleanup (xfree, text);
9168 result = parse_memory_map (text);
9169 do_cleanups (back_to);
9176 packet_command (char *args, int from_tty)
9178 struct remote_state *rs = get_remote_state ();
9180 if (!rs->remote_desc)
9181 error (_("command can only be used with remote target"));
9184 error (_("remote-packet command requires packet text as argument"));
9186 puts_filtered ("sending: ");
9187 print_packet (args);
9188 puts_filtered ("\n");
9191 getpkt (&rs->buf, &rs->buf_size, 0);
9192 puts_filtered ("received: ");
9193 print_packet (rs->buf);
9194 puts_filtered ("\n");
9198 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9200 static void display_thread_info (struct gdb_ext_thread_info *info);
9202 static void threadset_test_cmd (char *cmd, int tty);
9204 static void threadalive_test (char *cmd, int tty);
9206 static void threadlist_test_cmd (char *cmd, int tty);
9208 int get_and_display_threadinfo (threadref *ref);
9210 static void threadinfo_test_cmd (char *cmd, int tty);
9212 static int thread_display_step (threadref *ref, void *context);
9214 static void threadlist_update_test_cmd (char *cmd, int tty);
9216 static void init_remote_threadtests (void);
9218 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9221 threadset_test_cmd (char *cmd, int tty)
9223 int sample_thread = SAMPLE_THREAD;
9225 printf_filtered (_("Remote threadset test\n"));
9226 set_general_thread (sample_thread);
9231 threadalive_test (char *cmd, int tty)
9233 int sample_thread = SAMPLE_THREAD;
9234 int pid = ptid_get_pid (inferior_ptid);
9235 ptid_t ptid = ptid_build (pid, sample_thread, 0);
9237 if (remote_thread_alive (ptid))
9238 printf_filtered ("PASS: Thread alive test\n");
9240 printf_filtered ("FAIL: Thread alive test\n");
9243 void output_threadid (char *title, threadref *ref);
9246 output_threadid (char *title, threadref *ref)
9250 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9252 printf_filtered ("%s %s\n", title, (&hexid[0]));
9256 threadlist_test_cmd (char *cmd, int tty)
9259 threadref nextthread;
9260 int done, result_count;
9261 threadref threadlist[3];
9263 printf_filtered ("Remote Threadlist test\n");
9264 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9265 &result_count, &threadlist[0]))
9266 printf_filtered ("FAIL: threadlist test\n");
9269 threadref *scan = threadlist;
9270 threadref *limit = scan + result_count;
9272 while (scan < limit)
9273 output_threadid (" thread ", scan++);
9278 display_thread_info (struct gdb_ext_thread_info *info)
9280 output_threadid ("Threadid: ", &info->threadid);
9281 printf_filtered ("Name: %s\n ", info->shortname);
9282 printf_filtered ("State: %s\n", info->display);
9283 printf_filtered ("other: %s\n\n", info->more_display);
9287 get_and_display_threadinfo (threadref *ref)
9291 struct gdb_ext_thread_info threadinfo;
9293 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9294 | TAG_MOREDISPLAY | TAG_DISPLAY;
9295 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9296 display_thread_info (&threadinfo);
9301 threadinfo_test_cmd (char *cmd, int tty)
9303 int athread = SAMPLE_THREAD;
9307 int_to_threadref (&thread, athread);
9308 printf_filtered ("Remote Threadinfo test\n");
9309 if (!get_and_display_threadinfo (&thread))
9310 printf_filtered ("FAIL cannot get thread info\n");
9314 thread_display_step (threadref *ref, void *context)
9316 /* output_threadid(" threadstep ",ref); *//* simple test */
9317 return get_and_display_threadinfo (ref);
9321 threadlist_update_test_cmd (char *cmd, int tty)
9323 printf_filtered ("Remote Threadlist update test\n");
9324 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9328 init_remote_threadtests (void)
9330 add_com ("tlist", class_obscure, threadlist_test_cmd,
9331 _("Fetch and print the remote list of "
9332 "thread identifiers, one pkt only"));
9333 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9334 _("Fetch and display info about one thread"));
9335 add_com ("tset", class_obscure, threadset_test_cmd,
9336 _("Test setting to a different thread"));
9337 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9338 _("Iterate through updating all remote thread info"));
9339 add_com ("talive", class_obscure, threadalive_test,
9340 _(" Remote thread alive test "));
9345 /* Convert a thread ID to a string. Returns the string in a static
9349 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9351 static char buf[64];
9352 struct remote_state *rs = get_remote_state ();
9354 if (ptid_equal (ptid, null_ptid))
9355 return normal_pid_to_str (ptid);
9356 else if (ptid_is_pid (ptid))
9358 /* Printing an inferior target id. */
9360 /* When multi-process extensions are off, there's no way in the
9361 remote protocol to know the remote process id, if there's any
9362 at all. There's one exception --- when we're connected with
9363 target extended-remote, and we manually attached to a process
9364 with "attach PID". We don't record anywhere a flag that
9365 allows us to distinguish that case from the case of
9366 connecting with extended-remote and the stub already being
9367 attached to a process, and reporting yes to qAttached, hence
9368 no smart special casing here. */
9369 if (!remote_multi_process_p (rs))
9371 xsnprintf (buf, sizeof buf, "Remote target");
9375 return normal_pid_to_str (ptid);
9379 if (ptid_equal (magic_null_ptid, ptid))
9380 xsnprintf (buf, sizeof buf, "Thread <main>");
9381 else if (rs->extended && remote_multi_process_p (rs))
9382 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9383 ptid_get_pid (ptid), ptid_get_lwp (ptid));
9385 xsnprintf (buf, sizeof buf, "Thread %ld",
9386 ptid_get_lwp (ptid));
9391 /* Get the address of the thread local variable in OBJFILE which is
9392 stored at OFFSET within the thread local storage for thread PTID. */
9395 remote_get_thread_local_address (struct target_ops *ops,
9396 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9398 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
9400 struct remote_state *rs = get_remote_state ();
9402 char *endp = rs->buf + get_remote_packet_size ();
9403 enum packet_result result;
9405 strcpy (p, "qGetTLSAddr:");
9407 p = write_ptid (p, endp, ptid);
9409 p += hexnumstr (p, offset);
9411 p += hexnumstr (p, lm);
9415 getpkt (&rs->buf, &rs->buf_size, 0);
9416 result = packet_ok (rs->buf,
9417 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9418 if (result == PACKET_OK)
9422 unpack_varlen_hex (rs->buf, &result);
9425 else if (result == PACKET_UNKNOWN)
9426 throw_error (TLS_GENERIC_ERROR,
9427 _("Remote target doesn't support qGetTLSAddr packet"));
9429 throw_error (TLS_GENERIC_ERROR,
9430 _("Remote target failed to process qGetTLSAddr request"));
9433 throw_error (TLS_GENERIC_ERROR,
9434 _("TLS not supported or disabled on this target"));
9439 /* Provide thread local base, i.e. Thread Information Block address.
9440 Returns 1 if ptid is found and thread_local_base is non zero. */
9443 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
9445 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
9447 struct remote_state *rs = get_remote_state ();
9449 char *endp = rs->buf + get_remote_packet_size ();
9450 enum packet_result result;
9452 strcpy (p, "qGetTIBAddr:");
9454 p = write_ptid (p, endp, ptid);
9458 getpkt (&rs->buf, &rs->buf_size, 0);
9459 result = packet_ok (rs->buf,
9460 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9461 if (result == PACKET_OK)
9465 unpack_varlen_hex (rs->buf, &result);
9467 *addr = (CORE_ADDR) result;
9470 else if (result == PACKET_UNKNOWN)
9471 error (_("Remote target doesn't support qGetTIBAddr packet"));
9473 error (_("Remote target failed to process qGetTIBAddr request"));
9476 error (_("qGetTIBAddr not supported or disabled on this target"));
9481 /* Support for inferring a target description based on the current
9482 architecture and the size of a 'g' packet. While the 'g' packet
9483 can have any size (since optional registers can be left off the
9484 end), some sizes are easily recognizable given knowledge of the
9485 approximate architecture. */
9487 struct remote_g_packet_guess
9490 const struct target_desc *tdesc;
9492 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9493 DEF_VEC_O(remote_g_packet_guess_s);
9495 struct remote_g_packet_data
9497 VEC(remote_g_packet_guess_s) *guesses;
9500 static struct gdbarch_data *remote_g_packet_data_handle;
9503 remote_g_packet_data_init (struct obstack *obstack)
9505 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9509 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9510 const struct target_desc *tdesc)
9512 struct remote_g_packet_data *data
9513 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9514 struct remote_g_packet_guess new_guess, *guess;
9517 gdb_assert (tdesc != NULL);
9520 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9522 if (guess->bytes == bytes)
9523 internal_error (__FILE__, __LINE__,
9524 _("Duplicate g packet description added for size %d"),
9527 new_guess.bytes = bytes;
9528 new_guess.tdesc = tdesc;
9529 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9532 /* Return 1 if remote_read_description would do anything on this target
9533 and architecture, 0 otherwise. */
9536 remote_read_description_p (struct target_ops *target)
9538 struct remote_g_packet_data *data
9539 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9541 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9547 static const struct target_desc *
9548 remote_read_description (struct target_ops *target)
9550 struct remote_g_packet_data *data
9551 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9553 /* Do not try this during initial connection, when we do not know
9554 whether there is a running but stopped thread. */
9555 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9556 return target->beneath->to_read_description (target->beneath);
9558 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9560 struct remote_g_packet_guess *guess;
9562 int bytes = send_g_packet ();
9565 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9567 if (guess->bytes == bytes)
9568 return guess->tdesc;
9570 /* We discard the g packet. A minor optimization would be to
9571 hold on to it, and fill the register cache once we have selected
9572 an architecture, but it's too tricky to do safely. */
9575 return target->beneath->to_read_description (target->beneath);
9578 /* Remote file transfer support. This is host-initiated I/O, not
9579 target-initiated; for target-initiated, see remote-fileio.c. */
9581 /* If *LEFT is at least the length of STRING, copy STRING to
9582 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9583 decrease *LEFT. Otherwise raise an error. */
9586 remote_buffer_add_string (char **buffer, int *left, char *string)
9588 int len = strlen (string);
9591 error (_("Packet too long for target."));
9593 memcpy (*buffer, string, len);
9597 /* NUL-terminate the buffer as a convenience, if there is
9603 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9604 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9605 decrease *LEFT. Otherwise raise an error. */
9608 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9611 if (2 * len > *left)
9612 error (_("Packet too long for target."));
9614 bin2hex (bytes, *buffer, len);
9618 /* NUL-terminate the buffer as a convenience, if there is
9624 /* If *LEFT is large enough, convert VALUE to hex and add it to
9625 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9626 decrease *LEFT. Otherwise raise an error. */
9629 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9631 int len = hexnumlen (value);
9634 error (_("Packet too long for target."));
9636 hexnumstr (*buffer, value);
9640 /* NUL-terminate the buffer as a convenience, if there is
9646 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9647 value, *REMOTE_ERRNO to the remote error number or zero if none
9648 was included, and *ATTACHMENT to point to the start of the annex
9649 if any. The length of the packet isn't needed here; there may
9650 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9652 Return 0 if the packet could be parsed, -1 if it could not. If
9653 -1 is returned, the other variables may not be initialized. */
9656 remote_hostio_parse_result (char *buffer, int *retcode,
9657 int *remote_errno, char **attachment)
9664 if (buffer[0] != 'F')
9668 *retcode = strtol (&buffer[1], &p, 16);
9669 if (errno != 0 || p == &buffer[1])
9672 /* Check for ",errno". */
9676 *remote_errno = strtol (p + 1, &p2, 16);
9677 if (errno != 0 || p + 1 == p2)
9682 /* Check for ";attachment". If there is no attachment, the
9683 packet should end here. */
9686 *attachment = p + 1;
9689 else if (*p == '\0')
9695 /* Send a prepared I/O packet to the target and read its response.
9696 The prepared packet is in the global RS->BUF before this function
9697 is called, and the answer is there when we return.
9699 COMMAND_BYTES is the length of the request to send, which may include
9700 binary data. WHICH_PACKET is the packet configuration to check
9701 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9702 is set to the error number and -1 is returned. Otherwise the value
9703 returned by the function is returned.
9705 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9706 attachment is expected; an error will be reported if there's a
9707 mismatch. If one is found, *ATTACHMENT will be set to point into
9708 the packet buffer and *ATTACHMENT_LEN will be set to the
9709 attachment's length. */
9712 remote_hostio_send_command (int command_bytes, int which_packet,
9713 int *remote_errno, char **attachment,
9714 int *attachment_len)
9716 struct remote_state *rs = get_remote_state ();
9717 int ret, bytes_read;
9718 char *attachment_tmp;
9720 if (!rs->remote_desc
9721 || packet_support (which_packet) == PACKET_DISABLE)
9723 *remote_errno = FILEIO_ENOSYS;
9727 putpkt_binary (rs->buf, command_bytes);
9728 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9730 /* If it timed out, something is wrong. Don't try to parse the
9734 *remote_errno = FILEIO_EINVAL;
9738 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9741 *remote_errno = FILEIO_EINVAL;
9743 case PACKET_UNKNOWN:
9744 *remote_errno = FILEIO_ENOSYS;
9750 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9753 *remote_errno = FILEIO_EINVAL;
9757 /* Make sure we saw an attachment if and only if we expected one. */
9758 if ((attachment_tmp == NULL && attachment != NULL)
9759 || (attachment_tmp != NULL && attachment == NULL))
9761 *remote_errno = FILEIO_EINVAL;
9765 /* If an attachment was found, it must point into the packet buffer;
9766 work out how many bytes there were. */
9767 if (attachment_tmp != NULL)
9769 *attachment = attachment_tmp;
9770 *attachment_len = bytes_read - (*attachment - rs->buf);
9776 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9777 remote file descriptor, or -1 if an error occurs (and set
9781 remote_hostio_open (struct target_ops *self,
9782 const char *filename, int flags, int mode,
9785 struct remote_state *rs = get_remote_state ();
9787 int left = get_remote_packet_size () - 1;
9789 remote_buffer_add_string (&p, &left, "vFile:open:");
9791 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9793 remote_buffer_add_string (&p, &left, ",");
9795 remote_buffer_add_int (&p, &left, flags);
9796 remote_buffer_add_string (&p, &left, ",");
9798 remote_buffer_add_int (&p, &left, mode);
9800 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9801 remote_errno, NULL, NULL);
9804 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9805 Return the number of bytes written, or -1 if an error occurs (and
9806 set *REMOTE_ERRNO). */
9809 remote_hostio_pwrite (struct target_ops *self,
9810 int fd, const gdb_byte *write_buf, int len,
9811 ULONGEST offset, int *remote_errno)
9813 struct remote_state *rs = get_remote_state ();
9815 int left = get_remote_packet_size ();
9818 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9820 remote_buffer_add_int (&p, &left, fd);
9821 remote_buffer_add_string (&p, &left, ",");
9823 remote_buffer_add_int (&p, &left, offset);
9824 remote_buffer_add_string (&p, &left, ",");
9826 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9827 get_remote_packet_size () - (p - rs->buf));
9829 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9830 remote_errno, NULL, NULL);
9833 /* Read up to LEN bytes FD on the remote target into READ_BUF
9834 Return the number of bytes read, or -1 if an error occurs (and
9835 set *REMOTE_ERRNO). */
9838 remote_hostio_pread (struct target_ops *self,
9839 int fd, gdb_byte *read_buf, int len,
9840 ULONGEST offset, int *remote_errno)
9842 struct remote_state *rs = get_remote_state ();
9845 int left = get_remote_packet_size ();
9846 int ret, attachment_len;
9849 remote_buffer_add_string (&p, &left, "vFile:pread:");
9851 remote_buffer_add_int (&p, &left, fd);
9852 remote_buffer_add_string (&p, &left, ",");
9854 remote_buffer_add_int (&p, &left, len);
9855 remote_buffer_add_string (&p, &left, ",");
9857 remote_buffer_add_int (&p, &left, offset);
9859 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9860 remote_errno, &attachment,
9866 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9868 if (read_len != ret)
9869 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9874 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9875 (and set *REMOTE_ERRNO). */
9878 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
9880 struct remote_state *rs = get_remote_state ();
9882 int left = get_remote_packet_size () - 1;
9884 remote_buffer_add_string (&p, &left, "vFile:close:");
9886 remote_buffer_add_int (&p, &left, fd);
9888 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9889 remote_errno, NULL, NULL);
9892 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9893 occurs (and set *REMOTE_ERRNO). */
9896 remote_hostio_unlink (struct target_ops *self,
9897 const char *filename, int *remote_errno)
9899 struct remote_state *rs = get_remote_state ();
9901 int left = get_remote_packet_size () - 1;
9903 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9905 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9908 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9909 remote_errno, NULL, NULL);
9912 /* Read value of symbolic link FILENAME on the remote target. Return
9913 a null-terminated string allocated via xmalloc, or NULL if an error
9914 occurs (and set *REMOTE_ERRNO). */
9917 remote_hostio_readlink (struct target_ops *self,
9918 const char *filename, int *remote_errno)
9920 struct remote_state *rs = get_remote_state ();
9923 int left = get_remote_packet_size ();
9924 int len, attachment_len;
9928 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9930 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9933 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9934 remote_errno, &attachment,
9940 ret = xmalloc (len + 1);
9942 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9943 (gdb_byte *) ret, len);
9944 if (read_len != len)
9945 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9952 remote_fileio_errno_to_host (int errnum)
9976 case FILEIO_ENOTDIR:
9996 case FILEIO_ENAMETOOLONG:
9997 return ENAMETOOLONG;
10003 remote_hostio_error (int errnum)
10005 int host_error = remote_fileio_errno_to_host (errnum);
10007 if (host_error == -1)
10008 error (_("Unknown remote I/O error %d"), errnum);
10010 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10014 remote_hostio_close_cleanup (void *opaque)
10016 int fd = *(int *) opaque;
10019 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10024 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10026 const char *filename = bfd_get_filename (abfd);
10027 int fd, remote_errno;
10030 gdb_assert (remote_filename_p (filename));
10032 fd = remote_hostio_open (find_target_at (process_stratum),
10033 filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
10036 errno = remote_fileio_errno_to_host (remote_errno);
10037 bfd_set_error (bfd_error_system_call);
10041 stream = xmalloc (sizeof (int));
10047 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10049 int fd = *(int *)stream;
10054 /* Ignore errors on close; these may happen if the remote
10055 connection was already torn down. */
10056 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10058 /* Zero means success. */
10063 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10064 file_ptr nbytes, file_ptr offset)
10066 int fd = *(int *)stream;
10068 file_ptr pos, bytes;
10071 while (nbytes > pos)
10073 bytes = remote_hostio_pread (find_target_at (process_stratum),
10074 fd, (gdb_byte *) buf + pos, nbytes - pos,
10075 offset + pos, &remote_errno);
10077 /* Success, but no bytes, means end-of-file. */
10081 errno = remote_fileio_errno_to_host (remote_errno);
10082 bfd_set_error (bfd_error_system_call);
10093 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10095 /* FIXME: We should probably implement remote_hostio_stat. */
10096 sb->st_size = INT_MAX;
10101 remote_filename_p (const char *filename)
10103 return strncmp (filename,
10104 REMOTE_SYSROOT_PREFIX,
10105 sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
10109 remote_bfd_open (const char *remote_file, const char *target)
10111 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10112 remote_bfd_iovec_open, NULL,
10113 remote_bfd_iovec_pread,
10114 remote_bfd_iovec_close,
10115 remote_bfd_iovec_stat);
10121 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10123 struct cleanup *back_to, *close_cleanup;
10124 int retcode, fd, remote_errno, bytes, io_size;
10127 int bytes_in_buffer;
10130 struct remote_state *rs = get_remote_state ();
10132 if (!rs->remote_desc)
10133 error (_("command can only be used with remote target"));
10135 file = gdb_fopen_cloexec (local_file, "rb");
10137 perror_with_name (local_file);
10138 back_to = make_cleanup_fclose (file);
10140 fd = remote_hostio_open (find_target_at (process_stratum),
10141 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10143 0700, &remote_errno);
10145 remote_hostio_error (remote_errno);
10147 /* Send up to this many bytes at once. They won't all fit in the
10148 remote packet limit, so we'll transfer slightly fewer. */
10149 io_size = get_remote_packet_size ();
10150 buffer = xmalloc (io_size);
10151 make_cleanup (xfree, buffer);
10153 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10155 bytes_in_buffer = 0;
10158 while (bytes_in_buffer || !saw_eof)
10162 bytes = fread (buffer + bytes_in_buffer, 1,
10163 io_size - bytes_in_buffer,
10168 error (_("Error reading %s."), local_file);
10171 /* EOF. Unless there is something still in the
10172 buffer from the last iteration, we are done. */
10174 if (bytes_in_buffer == 0)
10182 bytes += bytes_in_buffer;
10183 bytes_in_buffer = 0;
10185 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10187 offset, &remote_errno);
10190 remote_hostio_error (remote_errno);
10191 else if (retcode == 0)
10192 error (_("Remote write of %d bytes returned 0!"), bytes);
10193 else if (retcode < bytes)
10195 /* Short write. Save the rest of the read data for the next
10197 bytes_in_buffer = bytes - retcode;
10198 memmove (buffer, buffer + retcode, bytes_in_buffer);
10204 discard_cleanups (close_cleanup);
10205 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10206 remote_hostio_error (remote_errno);
10209 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10210 do_cleanups (back_to);
10214 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10216 struct cleanup *back_to, *close_cleanup;
10217 int fd, remote_errno, bytes, io_size;
10221 struct remote_state *rs = get_remote_state ();
10223 if (!rs->remote_desc)
10224 error (_("command can only be used with remote target"));
10226 fd = remote_hostio_open (find_target_at (process_stratum),
10227 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10229 remote_hostio_error (remote_errno);
10231 file = gdb_fopen_cloexec (local_file, "wb");
10233 perror_with_name (local_file);
10234 back_to = make_cleanup_fclose (file);
10236 /* Send up to this many bytes at once. They won't all fit in the
10237 remote packet limit, so we'll transfer slightly fewer. */
10238 io_size = get_remote_packet_size ();
10239 buffer = xmalloc (io_size);
10240 make_cleanup (xfree, buffer);
10242 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10247 bytes = remote_hostio_pread (find_target_at (process_stratum),
10248 fd, buffer, io_size, offset, &remote_errno);
10250 /* Success, but no bytes, means end-of-file. */
10253 remote_hostio_error (remote_errno);
10257 bytes = fwrite (buffer, 1, bytes, file);
10259 perror_with_name (local_file);
10262 discard_cleanups (close_cleanup);
10263 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10264 remote_hostio_error (remote_errno);
10267 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10268 do_cleanups (back_to);
10272 remote_file_delete (const char *remote_file, int from_tty)
10274 int retcode, remote_errno;
10275 struct remote_state *rs = get_remote_state ();
10277 if (!rs->remote_desc)
10278 error (_("command can only be used with remote target"));
10280 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10281 remote_file, &remote_errno);
10283 remote_hostio_error (remote_errno);
10286 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10290 remote_put_command (char *args, int from_tty)
10292 struct cleanup *back_to;
10296 error_no_arg (_("file to put"));
10298 argv = gdb_buildargv (args);
10299 back_to = make_cleanup_freeargv (argv);
10300 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10301 error (_("Invalid parameters to remote put"));
10303 remote_file_put (argv[0], argv[1], from_tty);
10305 do_cleanups (back_to);
10309 remote_get_command (char *args, int from_tty)
10311 struct cleanup *back_to;
10315 error_no_arg (_("file to get"));
10317 argv = gdb_buildargv (args);
10318 back_to = make_cleanup_freeargv (argv);
10319 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10320 error (_("Invalid parameters to remote get"));
10322 remote_file_get (argv[0], argv[1], from_tty);
10324 do_cleanups (back_to);
10328 remote_delete_command (char *args, int from_tty)
10330 struct cleanup *back_to;
10334 error_no_arg (_("file to delete"));
10336 argv = gdb_buildargv (args);
10337 back_to = make_cleanup_freeargv (argv);
10338 if (argv[0] == NULL || argv[1] != NULL)
10339 error (_("Invalid parameters to remote delete"));
10341 remote_file_delete (argv[0], from_tty);
10343 do_cleanups (back_to);
10347 remote_command (char *args, int from_tty)
10349 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
10353 remote_can_execute_reverse (struct target_ops *self)
10355 if (packet_support (PACKET_bs) == PACKET_ENABLE
10356 || packet_support (PACKET_bc) == PACKET_ENABLE)
10363 remote_supports_non_stop (struct target_ops *self)
10369 remote_supports_disable_randomization (struct target_ops *self)
10371 /* Only supported in extended mode. */
10376 remote_supports_multi_process (struct target_ops *self)
10378 struct remote_state *rs = get_remote_state ();
10380 /* Only extended-remote handles being attached to multiple
10381 processes, even though plain remote can use the multi-process
10382 thread id extensions, so that GDB knows the target process's
10384 return rs->extended && remote_multi_process_p (rs);
10388 remote_supports_cond_tracepoints (void)
10390 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
10394 remote_supports_cond_breakpoints (struct target_ops *self)
10396 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
10400 remote_supports_fast_tracepoints (void)
10402 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
10406 remote_supports_static_tracepoints (void)
10408 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
10412 remote_supports_install_in_trace (void)
10414 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
10418 remote_supports_enable_disable_tracepoint (struct target_ops *self)
10420 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10425 remote_supports_string_tracing (struct target_ops *self)
10427 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
10431 remote_can_run_breakpoint_commands (struct target_ops *self)
10433 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
10437 remote_trace_init (struct target_ops *self)
10440 remote_get_noisy_reply (&target_buf, &target_buf_size);
10441 if (strcmp (target_buf, "OK") != 0)
10442 error (_("Target does not support this command."));
10445 static void free_actions_list (char **actions_list);
10446 static void free_actions_list_cleanup_wrapper (void *);
10448 free_actions_list_cleanup_wrapper (void *al)
10450 free_actions_list (al);
10454 free_actions_list (char **actions_list)
10458 if (actions_list == 0)
10461 for (ndx = 0; actions_list[ndx]; ndx++)
10462 xfree (actions_list[ndx]);
10464 xfree (actions_list);
10467 /* Recursive routine to walk through command list including loops, and
10468 download packets for each command. */
10471 remote_download_command_source (int num, ULONGEST addr,
10472 struct command_line *cmds)
10474 struct remote_state *rs = get_remote_state ();
10475 struct command_line *cmd;
10477 for (cmd = cmds; cmd; cmd = cmd->next)
10479 QUIT; /* Allow user to bail out with ^C. */
10480 strcpy (rs->buf, "QTDPsrc:");
10481 encode_source_string (num, addr, "cmd", cmd->line,
10482 rs->buf + strlen (rs->buf),
10483 rs->buf_size - strlen (rs->buf));
10485 remote_get_noisy_reply (&target_buf, &target_buf_size);
10486 if (strcmp (target_buf, "OK"))
10487 warning (_("Target does not support source download."));
10489 if (cmd->control_type == while_control
10490 || cmd->control_type == while_stepping_control)
10492 remote_download_command_source (num, addr, *cmd->body_list);
10494 QUIT; /* Allow user to bail out with ^C. */
10495 strcpy (rs->buf, "QTDPsrc:");
10496 encode_source_string (num, addr, "cmd", "end",
10497 rs->buf + strlen (rs->buf),
10498 rs->buf_size - strlen (rs->buf));
10500 remote_get_noisy_reply (&target_buf, &target_buf_size);
10501 if (strcmp (target_buf, "OK"))
10502 warning (_("Target does not support source download."));
10508 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
10510 #define BUF_SIZE 2048
10514 char buf[BUF_SIZE];
10515 char **tdp_actions;
10516 char **stepping_actions;
10518 struct cleanup *old_chain = NULL;
10519 struct agent_expr *aexpr;
10520 struct cleanup *aexpr_chain = NULL;
10522 struct breakpoint *b = loc->owner;
10523 struct tracepoint *t = (struct tracepoint *) b;
10525 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10526 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10528 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10531 tpaddr = loc->address;
10532 sprintf_vma (addrbuf, tpaddr);
10533 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10534 addrbuf, /* address */
10535 (b->enable_state == bp_enabled ? 'E' : 'D'),
10536 t->step_count, t->pass_count);
10537 /* Fast tracepoints are mostly handled by the target, but we can
10538 tell the target how big of an instruction block should be moved
10540 if (b->type == bp_fast_tracepoint)
10542 /* Only test for support at download time; we may not know
10543 target capabilities at definition time. */
10544 if (remote_supports_fast_tracepoints ())
10548 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10549 tpaddr, &isize, NULL))
10550 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10553 /* If it passed validation at definition but fails now,
10554 something is very wrong. */
10555 internal_error (__FILE__, __LINE__,
10556 _("Fast tracepoint not "
10557 "valid during download"));
10560 /* Fast tracepoints are functionally identical to regular
10561 tracepoints, so don't take lack of support as a reason to
10562 give up on the trace run. */
10563 warning (_("Target does not support fast tracepoints, "
10564 "downloading %d as regular tracepoint"), b->number);
10566 else if (b->type == bp_static_tracepoint)
10568 /* Only test for support at download time; we may not know
10569 target capabilities at definition time. */
10570 if (remote_supports_static_tracepoints ())
10572 struct static_tracepoint_marker marker;
10574 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10575 strcat (buf, ":S");
10577 error (_("Static tracepoint not valid during download"));
10580 /* Fast tracepoints are functionally identical to regular
10581 tracepoints, so don't take lack of support as a reason
10582 to give up on the trace run. */
10583 error (_("Target does not support static tracepoints"));
10585 /* If the tracepoint has a conditional, make it into an agent
10586 expression and append to the definition. */
10589 /* Only test support at download time, we may not know target
10590 capabilities at definition time. */
10591 if (remote_supports_cond_tracepoints ())
10593 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10594 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10595 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10597 pkt = buf + strlen (buf);
10598 for (ndx = 0; ndx < aexpr->len; ++ndx)
10599 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10601 do_cleanups (aexpr_chain);
10604 warning (_("Target does not support conditional tracepoints, "
10605 "ignoring tp %d cond"), b->number);
10608 if (b->commands || *default_collect)
10611 remote_get_noisy_reply (&target_buf, &target_buf_size);
10612 if (strcmp (target_buf, "OK"))
10613 error (_("Target does not support tracepoints."));
10615 /* do_single_steps (t); */
10618 for (ndx = 0; tdp_actions[ndx]; ndx++)
10620 QUIT; /* Allow user to bail out with ^C. */
10621 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10622 b->number, addrbuf, /* address */
10624 ((tdp_actions[ndx + 1] || stepping_actions)
10627 remote_get_noisy_reply (&target_buf,
10629 if (strcmp (target_buf, "OK"))
10630 error (_("Error on target while setting tracepoints."));
10633 if (stepping_actions)
10635 for (ndx = 0; stepping_actions[ndx]; ndx++)
10637 QUIT; /* Allow user to bail out with ^C. */
10638 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10639 b->number, addrbuf, /* address */
10640 ((ndx == 0) ? "S" : ""),
10641 stepping_actions[ndx],
10642 (stepping_actions[ndx + 1] ? "-" : ""));
10644 remote_get_noisy_reply (&target_buf,
10646 if (strcmp (target_buf, "OK"))
10647 error (_("Error on target while setting tracepoints."));
10651 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
10653 if (b->addr_string)
10655 strcpy (buf, "QTDPsrc:");
10656 encode_source_string (b->number, loc->address,
10657 "at", b->addr_string, buf + strlen (buf),
10658 2048 - strlen (buf));
10661 remote_get_noisy_reply (&target_buf, &target_buf_size);
10662 if (strcmp (target_buf, "OK"))
10663 warning (_("Target does not support source download."));
10665 if (b->cond_string)
10667 strcpy (buf, "QTDPsrc:");
10668 encode_source_string (b->number, loc->address,
10669 "cond", b->cond_string, buf + strlen (buf),
10670 2048 - strlen (buf));
10672 remote_get_noisy_reply (&target_buf, &target_buf_size);
10673 if (strcmp (target_buf, "OK"))
10674 warning (_("Target does not support source download."));
10676 remote_download_command_source (b->number, loc->address,
10677 breakpoint_commands (b));
10680 do_cleanups (old_chain);
10684 remote_can_download_tracepoint (struct target_ops *self)
10686 struct remote_state *rs = get_remote_state ();
10687 struct trace_status *ts;
10690 /* Don't try to install tracepoints until we've relocated our
10691 symbols, and fetched and merged the target's tracepoint list with
10693 if (rs->starting_up)
10696 ts = current_trace_status ();
10697 status = remote_get_trace_status (self, ts);
10699 if (status == -1 || !ts->running_known || !ts->running)
10702 /* If we are in a tracing experiment, but remote stub doesn't support
10703 installing tracepoint in trace, we have to return. */
10704 if (!remote_supports_install_in_trace ())
10712 remote_download_trace_state_variable (struct target_ops *self,
10713 struct trace_state_variable *tsv)
10715 struct remote_state *rs = get_remote_state ();
10718 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10719 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10721 p = rs->buf + strlen (rs->buf);
10722 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10723 error (_("Trace state variable name too long for tsv definition packet"));
10724 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
10727 remote_get_noisy_reply (&target_buf, &target_buf_size);
10728 if (*target_buf == '\0')
10729 error (_("Target does not support this command."));
10730 if (strcmp (target_buf, "OK") != 0)
10731 error (_("Error on target while downloading trace state variable."));
10735 remote_enable_tracepoint (struct target_ops *self,
10736 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 (), "QTEnable:%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 enabling tracepoints while a trace run is ongoing."));
10748 if (strcmp (rs->buf, "OK") != 0)
10749 error (_("Error on target while enabling tracepoint."));
10753 remote_disable_tracepoint (struct target_ops *self,
10754 struct bp_location *location)
10756 struct remote_state *rs = get_remote_state ();
10759 sprintf_vma (addr_buf, location->address);
10760 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10761 location->owner->number, addr_buf);
10763 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10764 if (*rs->buf == '\0')
10765 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10766 if (strcmp (rs->buf, "OK") != 0)
10767 error (_("Error on target while disabling tracepoint."));
10771 remote_trace_set_readonly_regions (struct target_ops *self)
10775 bfd_size_type size;
10781 return; /* No information to give. */
10783 strcpy (target_buf, "QTro");
10784 offset = strlen (target_buf);
10785 for (s = exec_bfd->sections; s; s = s->next)
10787 char tmp1[40], tmp2[40];
10790 if ((s->flags & SEC_LOAD) == 0 ||
10791 /* (s->flags & SEC_CODE) == 0 || */
10792 (s->flags & SEC_READONLY) == 0)
10796 vma = bfd_get_section_vma (abfd, s);
10797 size = bfd_get_section_size (s);
10798 sprintf_vma (tmp1, vma);
10799 sprintf_vma (tmp2, vma + size);
10800 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10801 if (offset + sec_length + 1 > target_buf_size)
10803 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
10805 Too many sections for read-only sections definition packet."));
10808 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10810 offset += sec_length;
10814 putpkt (target_buf);
10815 getpkt (&target_buf, &target_buf_size, 0);
10820 remote_trace_start (struct target_ops *self)
10822 putpkt ("QTStart");
10823 remote_get_noisy_reply (&target_buf, &target_buf_size);
10824 if (*target_buf == '\0')
10825 error (_("Target does not support this command."));
10826 if (strcmp (target_buf, "OK") != 0)
10827 error (_("Bogus reply from target: %s"), target_buf);
10831 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
10833 /* Initialize it just to avoid a GCC false warning. */
10835 /* FIXME we need to get register block size some other way. */
10836 extern int trace_regblock_size;
10837 volatile struct gdb_exception ex;
10838 enum packet_result result;
10840 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
10843 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10845 putpkt ("qTStatus");
10847 TRY_CATCH (ex, RETURN_MASK_ERROR)
10849 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10853 if (ex.error != TARGET_CLOSE_ERROR)
10855 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10858 throw_exception (ex);
10861 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10863 /* If the remote target doesn't do tracing, flag it. */
10864 if (result == PACKET_UNKNOWN)
10867 /* We're working with a live target. */
10868 ts->filename = NULL;
10871 error (_("Bogus trace status reply from target: %s"), target_buf);
10873 /* Function 'parse_trace_status' sets default value of each field of
10874 'ts' at first, so we don't have to do it here. */
10875 parse_trace_status (p, ts);
10877 return ts->running;
10881 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
10882 struct uploaded_tp *utp)
10884 struct remote_state *rs = get_remote_state ();
10886 struct bp_location *loc;
10887 struct tracepoint *tp = (struct tracepoint *) bp;
10888 size_t size = get_remote_packet_size ();
10892 tp->base.hit_count = 0;
10893 tp->traceframe_usage = 0;
10894 for (loc = tp->base.loc; loc; loc = loc->next)
10896 /* If the tracepoint was never downloaded, don't go asking for
10898 if (tp->number_on_target == 0)
10900 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10901 phex_nz (loc->address, 0));
10903 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10904 if (reply && *reply)
10907 parse_tracepoint_status (reply + 1, bp, utp);
10913 utp->hit_count = 0;
10914 utp->traceframe_usage = 0;
10915 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10916 phex_nz (utp->addr, 0));
10918 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10919 if (reply && *reply)
10922 parse_tracepoint_status (reply + 1, bp, utp);
10928 remote_trace_stop (struct target_ops *self)
10931 remote_get_noisy_reply (&target_buf, &target_buf_size);
10932 if (*target_buf == '\0')
10933 error (_("Target does not support this command."));
10934 if (strcmp (target_buf, "OK") != 0)
10935 error (_("Bogus reply from target: %s"), target_buf);
10939 remote_trace_find (struct target_ops *self,
10940 enum trace_find_type type, int num,
10941 CORE_ADDR addr1, CORE_ADDR addr2,
10944 struct remote_state *rs = get_remote_state ();
10945 char *endbuf = rs->buf + get_remote_packet_size ();
10947 int target_frameno = -1, target_tracept = -1;
10949 /* Lookups other than by absolute frame number depend on the current
10950 trace selected, so make sure it is correct on the remote end
10952 if (type != tfind_number)
10953 set_remote_traceframe ();
10956 strcpy (p, "QTFrame:");
10957 p = strchr (p, '\0');
10961 xsnprintf (p, endbuf - p, "%x", num);
10964 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
10967 xsnprintf (p, endbuf - p, "tdp:%x", num);
10970 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10971 phex_nz (addr2, 0));
10973 case tfind_outside:
10974 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10975 phex_nz (addr2, 0));
10978 error (_("Unknown trace find type %d"), type);
10982 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
10983 if (*reply == '\0')
10984 error (_("Target does not support this command."));
10986 while (reply && *reply)
10991 target_frameno = (int) strtol (p, &reply, 16);
10993 error (_("Unable to parse trace frame number"));
10994 /* Don't update our remote traceframe number cache on failure
10995 to select a remote traceframe. */
10996 if (target_frameno == -1)
11001 target_tracept = (int) strtol (p, &reply, 16);
11003 error (_("Unable to parse tracepoint number"));
11005 case 'O': /* "OK"? */
11006 if (reply[1] == 'K' && reply[2] == '\0')
11009 error (_("Bogus reply from target: %s"), reply);
11012 error (_("Bogus reply from target: %s"), reply);
11015 *tpp = target_tracept;
11017 rs->remote_traceframe_number = target_frameno;
11018 return target_frameno;
11022 remote_get_trace_state_variable_value (struct target_ops *self,
11023 int tsvnum, LONGEST *val)
11025 struct remote_state *rs = get_remote_state ();
11029 set_remote_traceframe ();
11031 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11033 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11034 if (reply && *reply)
11038 unpack_varlen_hex (reply + 1, &uval);
11039 *val = (LONGEST) uval;
11047 remote_save_trace_data (struct target_ops *self, const char *filename)
11049 struct remote_state *rs = get_remote_state ();
11053 strcpy (p, "QTSave:");
11055 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11056 error (_("Remote file name too long for trace save packet"));
11057 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
11060 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11061 if (*reply == '\0')
11062 error (_("Target does not support this command."));
11063 if (strcmp (reply, "OK") != 0)
11064 error (_("Bogus reply from target: %s"), reply);
11068 /* This is basically a memory transfer, but needs to be its own packet
11069 because we don't know how the target actually organizes its trace
11070 memory, plus we want to be able to ask for as much as possible, but
11071 not be unhappy if we don't get as much as we ask for. */
11074 remote_get_raw_trace_data (struct target_ops *self,
11075 gdb_byte *buf, ULONGEST offset, LONGEST len)
11077 struct remote_state *rs = get_remote_state ();
11083 strcpy (p, "qTBuffer:");
11085 p += hexnumstr (p, offset);
11087 p += hexnumstr (p, len);
11091 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11092 if (reply && *reply)
11094 /* 'l' by itself means we're at the end of the buffer and
11095 there is nothing more to get. */
11099 /* Convert the reply into binary. Limit the number of bytes to
11100 convert according to our passed-in buffer size, rather than
11101 what was returned in the packet; if the target is
11102 unexpectedly generous and gives us a bigger reply than we
11103 asked for, we don't want to crash. */
11104 rslt = hex2bin (target_buf, buf, len);
11108 /* Something went wrong, flag as an error. */
11113 remote_set_disconnected_tracing (struct target_ops *self, int val)
11115 struct remote_state *rs = get_remote_state ();
11117 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
11121 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11123 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11124 if (*reply == '\0')
11125 error (_("Target does not support this command."));
11126 if (strcmp (reply, "OK") != 0)
11127 error (_("Bogus reply from target: %s"), reply);
11130 warning (_("Target does not support disconnected tracing."));
11134 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11136 struct thread_info *info = find_thread_ptid (ptid);
11138 if (info && info->private)
11139 return info->private->core;
11144 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11146 struct remote_state *rs = get_remote_state ();
11149 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11151 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11152 if (*reply == '\0')
11153 error (_("Target does not support this command."));
11154 if (strcmp (reply, "OK") != 0)
11155 error (_("Bogus reply from target: %s"), reply);
11158 static struct traceframe_info *
11159 remote_traceframe_info (struct target_ops *self)
11163 text = target_read_stralloc (¤t_target,
11164 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11167 struct traceframe_info *info;
11168 struct cleanup *back_to = make_cleanup (xfree, text);
11170 info = parse_traceframe_info (text);
11171 do_cleanups (back_to);
11178 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11179 instruction on which a fast tracepoint may be placed. Returns -1
11180 if the packet is not supported, and 0 if the minimum instruction
11181 length is unknown. */
11184 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
11186 struct remote_state *rs = get_remote_state ();
11189 /* If we're not debugging a process yet, the IPA can't be
11191 if (!target_has_execution)
11194 /* Make sure the remote is pointing at the right process. */
11195 set_general_process ();
11197 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11199 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11200 if (*reply == '\0')
11204 ULONGEST min_insn_len;
11206 unpack_varlen_hex (reply, &min_insn_len);
11208 return (int) min_insn_len;
11213 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
11215 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
11217 struct remote_state *rs = get_remote_state ();
11218 char *buf = rs->buf;
11219 char *endbuf = rs->buf + get_remote_packet_size ();
11220 enum packet_result result;
11222 gdb_assert (val >= 0 || val == -1);
11223 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11224 /* Send -1 as literal "-1" to avoid host size dependency. */
11228 buf += hexnumstr (buf, (ULONGEST) -val);
11231 buf += hexnumstr (buf, (ULONGEST) val);
11234 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11235 result = packet_ok (rs->buf,
11236 &remote_protocol_packets[PACKET_QTBuffer_size]);
11238 if (result != PACKET_OK)
11239 warning (_("Bogus reply from target: %s"), rs->buf);
11244 remote_set_trace_notes (struct target_ops *self,
11245 const char *user, const char *notes,
11246 const char *stop_notes)
11248 struct remote_state *rs = get_remote_state ();
11250 char *buf = rs->buf;
11251 char *endbuf = rs->buf + get_remote_packet_size ();
11254 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11257 buf += xsnprintf (buf, endbuf - buf, "user:");
11258 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
11264 buf += xsnprintf (buf, endbuf - buf, "notes:");
11265 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
11271 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11272 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
11276 /* Ensure the buffer is terminated. */
11280 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11281 if (*reply == '\0')
11284 if (strcmp (reply, "OK") != 0)
11285 error (_("Bogus reply from target: %s"), reply);
11291 remote_use_agent (struct target_ops *self, int use)
11293 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
11295 struct remote_state *rs = get_remote_state ();
11297 /* If the stub supports QAgent. */
11298 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11300 getpkt (&rs->buf, &rs->buf_size, 0);
11302 if (strcmp (rs->buf, "OK") == 0)
11313 remote_can_use_agent (struct target_ops *self)
11315 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
11318 struct btrace_target_info
11320 /* The ptid of the traced thread. */
11324 /* Check whether the target supports branch tracing. */
11327 remote_supports_btrace (struct target_ops *self)
11329 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
11331 if (packet_support (PACKET_Qbtrace_bts) != PACKET_ENABLE)
11333 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
11339 /* Enable branch tracing. */
11341 static struct btrace_target_info *
11342 remote_enable_btrace (struct target_ops *self, ptid_t ptid)
11344 struct btrace_target_info *tinfo = NULL;
11345 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11346 struct remote_state *rs = get_remote_state ();
11347 char *buf = rs->buf;
11348 char *endbuf = rs->buf + get_remote_packet_size ();
11350 if (packet_config_support (packet) != PACKET_ENABLE)
11351 error (_("Target does not support branch tracing."));
11353 set_general_thread (ptid);
11355 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11357 getpkt (&rs->buf, &rs->buf_size, 0);
11359 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11361 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11362 error (_("Could not enable branch tracing for %s: %s"),
11363 target_pid_to_str (ptid), rs->buf + 2);
11365 error (_("Could not enable branch tracing for %s."),
11366 target_pid_to_str (ptid));
11369 tinfo = xzalloc (sizeof (*tinfo));
11370 tinfo->ptid = ptid;
11375 /* Disable branch tracing. */
11378 remote_disable_btrace (struct target_ops *self,
11379 struct btrace_target_info *tinfo)
11381 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11382 struct remote_state *rs = get_remote_state ();
11383 char *buf = rs->buf;
11384 char *endbuf = rs->buf + get_remote_packet_size ();
11386 if (packet_config_support (packet) != PACKET_ENABLE)
11387 error (_("Target does not support branch tracing."));
11389 set_general_thread (tinfo->ptid);
11391 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11393 getpkt (&rs->buf, &rs->buf_size, 0);
11395 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11397 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11398 error (_("Could not disable branch tracing for %s: %s"),
11399 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11401 error (_("Could not disable branch tracing for %s."),
11402 target_pid_to_str (tinfo->ptid));
11408 /* Teardown branch tracing. */
11411 remote_teardown_btrace (struct target_ops *self,
11412 struct btrace_target_info *tinfo)
11414 /* We must not talk to the target during teardown. */
11418 /* Read the branch trace. */
11420 static enum btrace_error
11421 remote_read_btrace (struct target_ops *self,
11422 VEC (btrace_block_s) **btrace,
11423 struct btrace_target_info *tinfo,
11424 enum btrace_read_type type)
11426 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11427 struct remote_state *rs = get_remote_state ();
11428 struct cleanup *cleanup;
11432 if (packet_config_support (packet) != PACKET_ENABLE)
11433 error (_("Target does not support branch tracing."));
11435 #if !defined(HAVE_LIBEXPAT)
11436 error (_("Cannot process branch tracing result. XML parsing not supported."));
11441 case BTRACE_READ_ALL:
11444 case BTRACE_READ_NEW:
11447 case BTRACE_READ_DELTA:
11451 internal_error (__FILE__, __LINE__,
11452 _("Bad branch tracing read type: %u."),
11453 (unsigned int) type);
11456 xml = target_read_stralloc (¤t_target,
11457 TARGET_OBJECT_BTRACE, annex);
11459 return BTRACE_ERR_UNKNOWN;
11461 cleanup = make_cleanup (xfree, xml);
11462 *btrace = parse_xml_btrace (xml);
11463 do_cleanups (cleanup);
11465 return BTRACE_ERR_NONE;
11469 remote_augmented_libraries_svr4_read (struct target_ops *self)
11471 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11475 /* Implementation of to_load. */
11478 remote_load (struct target_ops *self, const char *name, int from_tty)
11480 generic_load (name, from_tty);
11484 init_remote_ops (void)
11486 remote_ops.to_shortname = "remote";
11487 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11488 remote_ops.to_doc =
11489 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11490 Specify the serial device it is connected to\n\
11491 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11492 remote_ops.to_open = remote_open;
11493 remote_ops.to_close = remote_close;
11494 remote_ops.to_detach = remote_detach;
11495 remote_ops.to_disconnect = remote_disconnect;
11496 remote_ops.to_resume = remote_resume;
11497 remote_ops.to_wait = remote_wait;
11498 remote_ops.to_fetch_registers = remote_fetch_registers;
11499 remote_ops.to_store_registers = remote_store_registers;
11500 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11501 remote_ops.to_files_info = remote_files_info;
11502 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11503 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11504 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11505 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11506 remote_ops.to_watchpoint_addr_within_range =
11507 remote_watchpoint_addr_within_range;
11508 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11509 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11510 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11511 remote_ops.to_region_ok_for_hw_watchpoint
11512 = remote_region_ok_for_hw_watchpoint;
11513 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11514 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11515 remote_ops.to_kill = remote_kill;
11516 remote_ops.to_load = remote_load;
11517 remote_ops.to_mourn_inferior = remote_mourn;
11518 remote_ops.to_pass_signals = remote_pass_signals;
11519 remote_ops.to_program_signals = remote_program_signals;
11520 remote_ops.to_thread_alive = remote_thread_alive;
11521 remote_ops.to_update_thread_list = remote_update_thread_list;
11522 remote_ops.to_pid_to_str = remote_pid_to_str;
11523 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11524 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11525 remote_ops.to_stop = remote_stop;
11526 remote_ops.to_xfer_partial = remote_xfer_partial;
11527 remote_ops.to_rcmd = remote_rcmd;
11528 remote_ops.to_log_command = serial_log_command;
11529 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11530 remote_ops.to_stratum = process_stratum;
11531 remote_ops.to_has_all_memory = default_child_has_all_memory;
11532 remote_ops.to_has_memory = default_child_has_memory;
11533 remote_ops.to_has_stack = default_child_has_stack;
11534 remote_ops.to_has_registers = default_child_has_registers;
11535 remote_ops.to_has_execution = default_child_has_execution;
11536 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11537 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11538 remote_ops.to_magic = OPS_MAGIC;
11539 remote_ops.to_memory_map = remote_memory_map;
11540 remote_ops.to_flash_erase = remote_flash_erase;
11541 remote_ops.to_flash_done = remote_flash_done;
11542 remote_ops.to_read_description = remote_read_description;
11543 remote_ops.to_search_memory = remote_search_memory;
11544 remote_ops.to_can_async_p = remote_can_async_p;
11545 remote_ops.to_is_async_p = remote_is_async_p;
11546 remote_ops.to_async = remote_async;
11547 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11548 remote_ops.to_terminal_ours = remote_terminal_ours;
11549 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11550 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11551 remote_ops.to_supports_disable_randomization
11552 = remote_supports_disable_randomization;
11553 remote_ops.to_fileio_open = remote_hostio_open;
11554 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11555 remote_ops.to_fileio_pread = remote_hostio_pread;
11556 remote_ops.to_fileio_close = remote_hostio_close;
11557 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11558 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11559 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11560 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11561 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11562 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11563 remote_ops.to_trace_init = remote_trace_init;
11564 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11565 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11566 remote_ops.to_download_trace_state_variable
11567 = remote_download_trace_state_variable;
11568 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11569 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11570 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11571 remote_ops.to_trace_start = remote_trace_start;
11572 remote_ops.to_get_trace_status = remote_get_trace_status;
11573 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11574 remote_ops.to_trace_stop = remote_trace_stop;
11575 remote_ops.to_trace_find = remote_trace_find;
11576 remote_ops.to_get_trace_state_variable_value
11577 = remote_get_trace_state_variable_value;
11578 remote_ops.to_save_trace_data = remote_save_trace_data;
11579 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11580 remote_ops.to_upload_trace_state_variables
11581 = remote_upload_trace_state_variables;
11582 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11583 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11584 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11585 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11586 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11587 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11588 remote_ops.to_core_of_thread = remote_core_of_thread;
11589 remote_ops.to_verify_memory = remote_verify_memory;
11590 remote_ops.to_get_tib_address = remote_get_tib_address;
11591 remote_ops.to_set_permissions = remote_set_permissions;
11592 remote_ops.to_static_tracepoint_marker_at
11593 = remote_static_tracepoint_marker_at;
11594 remote_ops.to_static_tracepoint_markers_by_strid
11595 = remote_static_tracepoint_markers_by_strid;
11596 remote_ops.to_traceframe_info = remote_traceframe_info;
11597 remote_ops.to_use_agent = remote_use_agent;
11598 remote_ops.to_can_use_agent = remote_can_use_agent;
11599 remote_ops.to_supports_btrace = remote_supports_btrace;
11600 remote_ops.to_enable_btrace = remote_enable_btrace;
11601 remote_ops.to_disable_btrace = remote_disable_btrace;
11602 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11603 remote_ops.to_read_btrace = remote_read_btrace;
11604 remote_ops.to_augmented_libraries_svr4_read =
11605 remote_augmented_libraries_svr4_read;
11608 /* Set up the extended remote vector by making a copy of the standard
11609 remote vector and adding to it. */
11612 init_extended_remote_ops (void)
11614 extended_remote_ops = remote_ops;
11616 extended_remote_ops.to_shortname = "extended-remote";
11617 extended_remote_ops.to_longname =
11618 "Extended remote serial target in gdb-specific protocol";
11619 extended_remote_ops.to_doc =
11620 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11621 Specify the serial device it is connected to (e.g. /dev/ttya).";
11622 extended_remote_ops.to_open = extended_remote_open;
11623 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11624 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11625 extended_remote_ops.to_detach = extended_remote_detach;
11626 extended_remote_ops.to_attach = extended_remote_attach;
11627 extended_remote_ops.to_post_attach = extended_remote_post_attach;
11628 extended_remote_ops.to_kill = extended_remote_kill;
11629 extended_remote_ops.to_supports_disable_randomization
11630 = extended_remote_supports_disable_randomization;
11634 remote_can_async_p (struct target_ops *ops)
11636 struct remote_state *rs = get_remote_state ();
11638 if (!target_async_permitted)
11639 /* We only enable async when the user specifically asks for it. */
11642 /* We're async whenever the serial device is. */
11643 return serial_can_async_p (rs->remote_desc);
11647 remote_is_async_p (struct target_ops *ops)
11649 struct remote_state *rs = get_remote_state ();
11651 if (!target_async_permitted)
11652 /* We only enable async when the user specifically asks for it. */
11655 /* We're async whenever the serial device is. */
11656 return serial_is_async_p (rs->remote_desc);
11659 /* Pass the SERIAL event on and up to the client. One day this code
11660 will be able to delay notifying the client of an event until the
11661 point where an entire packet has been received. */
11663 static serial_event_ftype remote_async_serial_handler;
11666 remote_async_serial_handler (struct serial *scb, void *context)
11668 struct remote_state *rs = context;
11670 /* Don't propogate error information up to the client. Instead let
11671 the client find out about the error by querying the target. */
11672 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
11676 remote_async_inferior_event_handler (gdb_client_data data)
11678 inferior_event_handler (INF_REG_EVENT, NULL);
11682 remote_async (struct target_ops *ops,
11683 void (*callback) (enum inferior_event_type event_type,
11687 struct remote_state *rs = get_remote_state ();
11689 if (callback != NULL)
11691 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11692 rs->async_client_callback = callback;
11693 rs->async_client_context = context;
11696 serial_async (rs->remote_desc, NULL, NULL);
11700 set_remote_cmd (char *args, int from_tty)
11702 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
11706 show_remote_cmd (char *args, int from_tty)
11708 /* We can't just use cmd_show_list here, because we want to skip
11709 the redundant "show remote Z-packet" and the legacy aliases. */
11710 struct cleanup *showlist_chain;
11711 struct cmd_list_element *list = remote_show_cmdlist;
11712 struct ui_out *uiout = current_uiout;
11714 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11715 for (; list != NULL; list = list->next)
11716 if (strcmp (list->name, "Z-packet") == 0)
11718 else if (list->type == not_set_cmd)
11719 /* Alias commands are exactly like the original, except they
11720 don't have the normal type. */
11724 struct cleanup *option_chain
11725 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11727 ui_out_field_string (uiout, "name", list->name);
11728 ui_out_text (uiout, ": ");
11729 if (list->type == show_cmd)
11730 do_show_command ((char *) NULL, from_tty, list);
11732 cmd_func (list, NULL, from_tty);
11733 /* Close the tuple. */
11734 do_cleanups (option_chain);
11737 /* Close the tuple. */
11738 do_cleanups (showlist_chain);
11742 /* Function to be called whenever a new objfile (shlib) is detected. */
11744 remote_new_objfile (struct objfile *objfile)
11746 struct remote_state *rs = get_remote_state ();
11748 if (rs->remote_desc != 0) /* Have a remote connection. */
11749 remote_check_symbols ();
11752 /* Pull all the tracepoints defined on the target and create local
11753 data structures representing them. We don't want to create real
11754 tracepoints yet, we don't want to mess up the user's existing
11758 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
11760 struct remote_state *rs = get_remote_state ();
11763 /* Ask for a first packet of tracepoint definition. */
11765 getpkt (&rs->buf, &rs->buf_size, 0);
11767 while (*p && *p != 'l')
11769 parse_tracepoint_definition (p, utpp);
11770 /* Ask for another packet of tracepoint definition. */
11772 getpkt (&rs->buf, &rs->buf_size, 0);
11779 remote_upload_trace_state_variables (struct target_ops *self,
11780 struct uploaded_tsv **utsvp)
11782 struct remote_state *rs = get_remote_state ();
11785 /* Ask for a first packet of variable definition. */
11787 getpkt (&rs->buf, &rs->buf_size, 0);
11789 while (*p && *p != 'l')
11791 parse_tsv_definition (p, utsvp);
11792 /* Ask for another packet of variable definition. */
11794 getpkt (&rs->buf, &rs->buf_size, 0);
11800 /* The "set/show range-stepping" show hook. */
11803 show_range_stepping (struct ui_file *file, int from_tty,
11804 struct cmd_list_element *c,
11807 fprintf_filtered (file,
11808 _("Debugger's willingness to use range stepping "
11809 "is %s.\n"), value);
11812 /* The "set/show range-stepping" set hook. */
11815 set_range_stepping (char *ignore_args, int from_tty,
11816 struct cmd_list_element *c)
11818 struct remote_state *rs = get_remote_state ();
11820 /* Whene enabling, check whether range stepping is actually
11821 supported by the target, and warn if not. */
11822 if (use_range_stepping)
11824 if (rs->remote_desc != NULL)
11826 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
11827 remote_vcont_probe (rs);
11829 if (packet_support (PACKET_vCont) == PACKET_ENABLE
11830 && rs->supports_vCont.r)
11834 warning (_("Range stepping is not supported by the current target"));
11839 _initialize_remote (void)
11841 struct remote_state *rs;
11842 struct cmd_list_element *cmd;
11843 const char *cmd_name;
11845 /* architecture specific data */
11846 remote_gdbarch_data_handle =
11847 gdbarch_data_register_post_init (init_remote_state);
11848 remote_g_packet_data_handle =
11849 gdbarch_data_register_pre_init (remote_g_packet_data_init);
11851 /* Initialize the per-target state. At the moment there is only one
11852 of these, not one per target. Only one target is active at a
11854 remote_state = new_remote_state ();
11856 init_remote_ops ();
11857 add_target (&remote_ops);
11859 init_extended_remote_ops ();
11860 add_target (&extended_remote_ops);
11862 /* Hook into new objfile notification. */
11863 observer_attach_new_objfile (remote_new_objfile);
11864 /* We're no longer interested in notification events of an inferior
11866 observer_attach_inferior_exit (discard_pending_stop_replies);
11868 /* Set up signal handlers. */
11869 async_sigint_remote_token =
11870 create_async_signal_handler (async_remote_interrupt, NULL);
11871 async_sigint_remote_twice_token =
11872 create_async_signal_handler (async_remote_interrupt_twice, NULL);
11875 init_remote_threadtests ();
11878 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
11879 /* set/show remote ... */
11881 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
11882 Remote protocol specific variables\n\
11883 Configure various remote-protocol specific variables such as\n\
11884 the packets being used"),
11885 &remote_set_cmdlist, "set remote ",
11886 0 /* allow-unknown */, &setlist);
11887 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
11888 Remote protocol specific variables\n\
11889 Configure various remote-protocol specific variables such as\n\
11890 the packets being used"),
11891 &remote_show_cmdlist, "show remote ",
11892 0 /* allow-unknown */, &showlist);
11894 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11895 Compare section data on target to the exec file.\n\
11896 Argument is a single section name (default: all loaded sections).\n\
11897 To compare only read-only loaded sections, specify the -r option."),
11900 add_cmd ("packet", class_maintenance, packet_command, _("\
11901 Send an arbitrary packet to a remote target.\n\
11902 maintenance packet TEXT\n\
11903 If GDB is talking to an inferior via the GDB serial protocol, then\n\
11904 this command sends the string TEXT to the inferior, and displays the\n\
11905 response packet. GDB supplies the initial `$' character, and the\n\
11906 terminating `#' character and checksum."),
11909 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11910 Set whether to send break if interrupted."), _("\
11911 Show whether to send break if interrupted."), _("\
11912 If set, a break, instead of a cntrl-c, is sent to the remote target."),
11913 set_remotebreak, show_remotebreak,
11914 &setlist, &showlist);
11915 cmd_name = "remotebreak";
11916 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11917 deprecate_cmd (cmd, "set remote interrupt-sequence");
11918 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11919 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11920 deprecate_cmd (cmd, "show remote interrupt-sequence");
11922 add_setshow_enum_cmd ("interrupt-sequence", class_support,
11923 interrupt_sequence_modes, &interrupt_sequence_mode,
11925 Set interrupt sequence to remote target."), _("\
11926 Show interrupt sequence to remote target."), _("\
11927 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11928 NULL, show_interrupt_sequence,
11929 &remote_set_cmdlist,
11930 &remote_show_cmdlist);
11932 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11933 &interrupt_on_connect, _("\
11934 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11935 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11936 If set, interrupt sequence is sent to remote target."),
11938 &remote_set_cmdlist, &remote_show_cmdlist);
11940 /* Install commands for configuring memory read/write packets. */
11942 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11943 Set the maximum number of bytes per memory write packet (deprecated)."),
11945 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11946 Show the maximum number of bytes per memory write packet (deprecated)."),
11948 add_cmd ("memory-write-packet-size", no_class,
11949 set_memory_write_packet_size, _("\
11950 Set the maximum number of bytes per memory-write packet.\n\
11951 Specify the number of bytes in a packet or 0 (zero) for the\n\
11952 default packet size. The actual limit is further reduced\n\
11953 dependent on the target. Specify ``fixed'' to disable the\n\
11954 further restriction and ``limit'' to enable that restriction."),
11955 &remote_set_cmdlist);
11956 add_cmd ("memory-read-packet-size", no_class,
11957 set_memory_read_packet_size, _("\
11958 Set the maximum number of bytes per memory-read packet.\n\
11959 Specify the number of bytes in a packet or 0 (zero) for the\n\
11960 default packet size. The actual limit is further reduced\n\
11961 dependent on the target. Specify ``fixed'' to disable the\n\
11962 further restriction and ``limit'' to enable that restriction."),
11963 &remote_set_cmdlist);
11964 add_cmd ("memory-write-packet-size", no_class,
11965 show_memory_write_packet_size,
11966 _("Show the maximum number of bytes per memory-write packet."),
11967 &remote_show_cmdlist);
11968 add_cmd ("memory-read-packet-size", no_class,
11969 show_memory_read_packet_size,
11970 _("Show the maximum number of bytes per memory-read packet."),
11971 &remote_show_cmdlist);
11973 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
11974 &remote_hw_watchpoint_limit, _("\
11975 Set the maximum number of target hardware watchpoints."), _("\
11976 Show the maximum number of target hardware watchpoints."), _("\
11977 Specify a negative limit for unlimited."),
11978 NULL, NULL, /* FIXME: i18n: The maximum
11979 number of target hardware
11980 watchpoints is %s. */
11981 &remote_set_cmdlist, &remote_show_cmdlist);
11982 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11983 &remote_hw_watchpoint_length_limit, _("\
11984 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11985 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11986 Specify a negative limit for unlimited."),
11987 NULL, NULL, /* FIXME: i18n: The maximum
11988 length (in bytes) of a target
11989 hardware watchpoint is %s. */
11990 &remote_set_cmdlist, &remote_show_cmdlist);
11991 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
11992 &remote_hw_breakpoint_limit, _("\
11993 Set the maximum number of target hardware breakpoints."), _("\
11994 Show the maximum number of target hardware breakpoints."), _("\
11995 Specify a negative limit for unlimited."),
11996 NULL, NULL, /* FIXME: i18n: The maximum
11997 number of target hardware
11998 breakpoints is %s. */
11999 &remote_set_cmdlist, &remote_show_cmdlist);
12001 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12002 &remote_address_size, _("\
12003 Set the maximum size of the address (in bits) in a memory packet."), _("\
12004 Show the maximum size of the address (in bits) in a memory packet."), NULL,
12006 NULL, /* FIXME: i18n: */
12007 &setlist, &showlist);
12009 init_all_packet_configs ();
12011 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
12012 "X", "binary-download", 1);
12014 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
12015 "vCont", "verbose-resume", 0);
12017 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12018 "QPassSignals", "pass-signals", 0);
12020 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12021 "QProgramSignals", "program-signals", 0);
12023 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12024 "qSymbol", "symbol-lookup", 0);
12026 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12027 "P", "set-register", 1);
12029 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12030 "p", "fetch-register", 1);
12032 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12033 "Z0", "software-breakpoint", 0);
12035 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12036 "Z1", "hardware-breakpoint", 0);
12038 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12039 "Z2", "write-watchpoint", 0);
12041 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12042 "Z3", "read-watchpoint", 0);
12044 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12045 "Z4", "access-watchpoint", 0);
12047 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12048 "qXfer:auxv:read", "read-aux-vector", 0);
12050 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12051 "qXfer:features:read", "target-features", 0);
12053 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12054 "qXfer:libraries:read", "library-info", 0);
12056 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12057 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12059 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12060 "qXfer:memory-map:read", "memory-map", 0);
12062 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12063 "qXfer:spu:read", "read-spu-object", 0);
12065 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12066 "qXfer:spu:write", "write-spu-object", 0);
12068 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12069 "qXfer:osdata:read", "osdata", 0);
12071 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12072 "qXfer:threads:read", "threads", 0);
12074 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12075 "qXfer:siginfo:read", "read-siginfo-object", 0);
12077 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12078 "qXfer:siginfo:write", "write-siginfo-object", 0);
12080 add_packet_config_cmd
12081 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12082 "qXfer:traceframe-info:read", "traceframe-info", 0);
12084 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12085 "qXfer:uib:read", "unwind-info-block", 0);
12087 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12088 "qGetTLSAddr", "get-thread-local-storage-address",
12091 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12092 "qGetTIBAddr", "get-thread-information-block-address",
12095 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12096 "bc", "reverse-continue", 0);
12098 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12099 "bs", "reverse-step", 0);
12101 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12102 "qSupported", "supported-packets", 0);
12104 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12105 "qSearch:memory", "search-memory", 0);
12107 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12108 "qTStatus", "trace-status", 0);
12110 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12111 "vFile:open", "hostio-open", 0);
12113 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12114 "vFile:pread", "hostio-pread", 0);
12116 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12117 "vFile:pwrite", "hostio-pwrite", 0);
12119 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12120 "vFile:close", "hostio-close", 0);
12122 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12123 "vFile:unlink", "hostio-unlink", 0);
12125 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12126 "vFile:readlink", "hostio-readlink", 0);
12128 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12129 "vAttach", "attach", 0);
12131 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12134 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12135 "QStartNoAckMode", "noack", 0);
12137 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12138 "vKill", "kill", 0);
12140 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12141 "qAttached", "query-attached", 0);
12143 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12144 "ConditionalTracepoints",
12145 "conditional-tracepoints", 0);
12147 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12148 "ConditionalBreakpoints",
12149 "conditional-breakpoints", 0);
12151 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12152 "BreakpointCommands",
12153 "breakpoint-commands", 0);
12155 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12156 "FastTracepoints", "fast-tracepoints", 0);
12158 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12159 "TracepointSource", "TracepointSource", 0);
12161 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12162 "QAllow", "allow", 0);
12164 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12165 "StaticTracepoints", "static-tracepoints", 0);
12167 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12168 "InstallInTrace", "install-in-trace", 0);
12170 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12171 "qXfer:statictrace:read", "read-sdata-object", 0);
12173 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12174 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12176 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12177 "QDisableRandomization", "disable-randomization", 0);
12179 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12180 "QAgent", "agent", 0);
12182 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12183 "QTBuffer:size", "trace-buffer-size", 0);
12185 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12186 "Qbtrace:off", "disable-btrace", 0);
12188 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12189 "Qbtrace:bts", "enable-btrace", 0);
12191 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12192 "qXfer:btrace", "read-btrace", 0);
12194 /* Assert that we've registered commands for all packet configs. */
12198 for (i = 0; i < PACKET_MAX; i++)
12200 /* Ideally all configs would have a command associated. Some
12201 still don't though. */
12206 case PACKET_QNonStop:
12207 case PACKET_multiprocess_feature:
12208 case PACKET_EnableDisableTracepoints_feature:
12209 case PACKET_tracenz_feature:
12210 case PACKET_DisconnectedTracing_feature:
12211 case PACKET_augmented_libraries_svr4_read_feature:
12213 /* Additions to this list need to be well justified:
12214 pre-existing packets are OK; new packets are not. */
12222 /* This catches both forgetting to add a config command, and
12223 forgetting to remove a packet from the exception list. */
12224 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12228 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12229 Z sub-packet has its own set and show commands, but users may
12230 have sets to this variable in their .gdbinit files (or in their
12232 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12233 &remote_Z_packet_detect, _("\
12234 Set use of remote protocol `Z' packets"), _("\
12235 Show use of remote protocol `Z' packets "), _("\
12236 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12238 set_remote_protocol_Z_packet_cmd,
12239 show_remote_protocol_Z_packet_cmd,
12240 /* FIXME: i18n: Use of remote protocol
12241 `Z' packets is %s. */
12242 &remote_set_cmdlist, &remote_show_cmdlist);
12244 add_prefix_cmd ("remote", class_files, remote_command, _("\
12245 Manipulate files on the remote system\n\
12246 Transfer files to and from the remote target system."),
12247 &remote_cmdlist, "remote ",
12248 0 /* allow-unknown */, &cmdlist);
12250 add_cmd ("put", class_files, remote_put_command,
12251 _("Copy a local file to the remote system."),
12254 add_cmd ("get", class_files, remote_get_command,
12255 _("Copy a remote file to the local system."),
12258 add_cmd ("delete", class_files, remote_delete_command,
12259 _("Delete a remote file."),
12262 remote_exec_file = xstrdup ("");
12263 add_setshow_string_noescape_cmd ("exec-file", class_files,
12264 &remote_exec_file, _("\
12265 Set the remote pathname for \"run\""), _("\
12266 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12267 &remote_set_cmdlist, &remote_show_cmdlist);
12269 add_setshow_boolean_cmd ("range-stepping", class_run,
12270 &use_range_stepping, _("\
12271 Enable or disable range stepping."), _("\
12272 Show whether target-assisted range stepping is enabled."), _("\
12273 If on, and the target supports it, when stepping a source line, GDB\n\
12274 tells the target to step the corresponding range of addresses itself instead\n\
12275 of issuing multiple single-steps. This speeds up source level\n\
12276 stepping. If off, GDB always issues single-steps, even if range\n\
12277 stepping is supported by the target. The default is on."),
12278 set_range_stepping,
12279 show_range_stepping,
12283 /* Eventually initialize fileio. See fileio.c */
12284 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12286 /* Take advantage of the fact that the TID field is not used, to tag
12287 special ptids with it set to != 0. */
12288 magic_null_ptid = ptid_build (42000, -1, 1);
12289 not_sent_ptid = ptid_build (42000, -2, 1);
12290 any_thread_ptid = ptid_build (42000, 0, 1);
12292 target_buf_size = 2048;
12293 target_buf = xmalloc (target_buf_size);